
function buy_prod(prod_id)
{
	var p = $("#ul-" + prod_id).parent().parent();
	var href = $( p ).children("a.buy-prod").attr("href");
	var fields_num =  $("ul#ul-" + prod_id + "  select").length;
	var values = [];
	var errors = 0;
	var index = -1;
	$("ul#ul-" + prod_id + "  select").each(
		function() {
			if( $(this).val() == "" ) {
                errors++;
			} else {
				values[++index] = $(this).val();
			}
		}
	);
	if(errors > 0) {
		alert("Tutte le opzioni sono obbligatorie!");
		return false;
	}
	$.ajax({
		type: "POST",
		url: SITE_PATH_REL + "ajax/jajax.php",
		data: "m=base64_encode&data=" + values.join("___"),
		success: function(result) {
			if(result.match(/^Error:/)) {
				alert( "Si \xE8 verificato un errore" );
				return;
			}
            window.location.replace( href + "?cf=" + result );
		}
	});
}

function close_fields_div(prod_id)
{
    $("#cf-prod-" + prod_id).hide("normal");
}

var buy_img = '';
var custom_fields_el = '<div id="cf-prod-FIELDS_ID" class="custom-fields-el-home">';
custom_fields_el += '</div>'
$(document).ready(
	function() {
		$(".buy-prod").click(
			function() {
                var current_img = $(this).children("img").attr("src");
				var _tmp_ = this;
				var split_id = this.id.split("__SEP__");
				var _id = split_id[1];
				if(split_id[2] == 0 && split_id[4] < 1) {
					alert("Il prodotto non \xE8 disponibile");
					return false;
				}
				if(split_id[3] == 0) {
					return true;
				}
				if($("#cf-prod-" + _id).css("display") == "block") {
					close_fields_div(_id)
				} else if($("#cf-prod-" + _id).css("display") == "none") {
					$("#cf-prod-" + _id).show("normal");
				} else {
					$.ajax({
						type: "POST",
						url: SITE_PATH_REL + "ajax/jajax.php",
						data: "m=get_custom_fields&w=home&pid=" + _id,
						success: function(result) {
							if(result.match(/^Error:/)) {
								alert( result.replace("Error:","") );
								return;
							}
							if(result) {
		                        $(_tmp_).parent().append( custom_fields_el.replace("FIELDS_ID",_id) );
		                        $("#cf-prod-" + _id).append( result ).show("normal");
							}
						}
					});
				}
				return false;
			}
		);
	}
);