// -------------------------------------------------------------------------------------------------

//  character conversion for css/javascript
//  '/' -> '___'
//  '.' -> '_-_'
//  ' ' -> '---'

// constants

// var SERVER_URL = 'http://callandclick/stub';
var ROTATOR_WIDTH = 248;	 // rotator width in px
var ROTATOR_SPEED = 500;	 // rotator speed in ms
var ROTATOR_INTERVAL = 7000; // autorotate interval in ms
var THUMB_WIDTH = 64;		// 'other products' thumbnails width in px
var PAGESIZE = 8;			// how many products show in one page

var product_cache = {};
var autoslide = 1;		   // flag to stop autoslide during lightbox usage

var free_brand = '';
var free_model = '';
var free_text = '';

var hashencrypt = false;

//function load_brand_category(prefix, what, showphones, autoload)


// -------------------------------------------------------------------------------------------------
window.onload = function() {
	msie = $.browser.msie;
	safari = $.browser.safari;
}


// -------------------------------------------------------------------------------------------------
function init_rotators() {
	var elm = $('#rot1 .body .stripe img').length;
	$('#rot1 .body .rcontroller').html(create_rcontroller('rot1', elm));
	$('#rot1 .body .stripe').css('width', ROTATOR_WIDTH * elm);

	var elm = $('#rot2 .body .stripe img').length;
	$('#rot2 .body .rcontroller').html(create_rcontroller('rot2', elm));
	$('#rot2 .body .stripe').css('width', ROTATOR_WIDTH * elm);

	var elm = $('#rot3 .body .stripe img').length;
	$('#rot3 .body .stripe').css('width', ROTATOR_WIDTH * elm);

	// rot3 slides only automatically
	setInterval(function() {
			rotate_right('rot3');
		}, ROTATOR_INTERVAL
	);
}


// -------------------------------------------------------------------------------------------------
function init_big_rotator() {
	var elm = $('#image .body .stripe img').length;
	$('#image .body .rcontroller').html(create_rcontroller('image', elm));
	$('#image .body .stripe').css('width', ROTATOR_WIDTH * elm);

	setInterval(function() {
			rotate_right('image');
		}, ROTATOR_INTERVAL
	);
}


// -------------------------------------------------------------------------------------------------
function init_promo_rotator() {
	var elm = $('#promo_image .body .stripe img').length;
	$('#promo_image .body .rcontroller').html(create_rcontroller('promo_image', elm));
	$('#promo_image .body .stripe').css('width', ROTATOR_WIDTH * elm);

	setInterval(function() {
			rotate_right('promo_image');
		}, ROTATOR_INTERVAL
	);
}


// -------------------------------------------------------------------------------------------------
function create_rcontroller(name, count) {
	if (count < 2)
		return '';

	var html = '';

	for (var i=0; i<count; i++) {
		html += "<div class='goto goto" + i + (i==0 ? " selected" : "") + "' onclick='goto(\"" + name + "\"," + i + ")'></div>";
	}

	html += "<div class='lrotate' onclick='rotate_left(\"" + name + "\")'></div><div class='rrotate' onclick='rotate_right(\"" + name + "\")'></div>";

	return html;
}


// -------------------------------------------------------------------------------------------------
function goto(name, position) {
	$('#' + name + ' .body .rcontroller .goto').removeClass('selected');
	$('#' + name + ' .body .stripe').animate({marginLeft: -position * ROTATOR_WIDTH}, ROTATOR_SPEED, 'swing');
	$('#' + name + ' .body .rcontroller .goto' + position).addClass('selected');
}


// -------------------------------------------------------------------------------------------------
function rotate_left(name) {
	$('#' + name + ' .body .rcontroller .goto').removeClass('selected');

	var object = $('#' + name + ' .body .stripe');

	var ml = parseInt(object.css('margin-left'), 10);
	var w = parseInt(object.css('width'), 10);

	var position = -ml / ROTATOR_WIDTH;

	if (ml < 0) {
		$('#' + name + ' .body .rcontroller .goto' + (position-1)).addClass('selected');
		object.animate({marginLeft: '+=' + ROTATOR_WIDTH}, ROTATOR_SPEED, 'swing');
	}
	else {
		$('#' + name + ' .body .rcontroller .goto' + (w/ROTATOR_WIDTH-1)).addClass('selected');
		object.animate({marginLeft: ROTATOR_WIDTH - w}, ROTATOR_SPEED, 'linear');
	}
}


// -------------------------------------------------------------------------------------------------
function rotate_right(name) {
	if (!autoslide)
		return;

	$('#' + name + ' .body .rcontroller .goto').removeClass('selected');

	var object = $('#' + name + ' .body .stripe');

	var ml = parseInt(object.css('margin-left'), 10);
	var w = parseInt(object.css('width'), 10);

	var position = -ml / ROTATOR_WIDTH;

	if (ml > ROTATOR_WIDTH - w) {
		$('#' + name + ' .body .rcontroller .goto' + (position+1)).addClass('selected');
		object.animate({marginLeft: '-=' + ROTATOR_WIDTH}, ROTATOR_SPEED, 'swing');
	}
	else {
		$('#' + name + ' .body .rcontroller .goto0').addClass('selected');
		object.animate({marginLeft: '0'}, ROTATOR_SPEED, 'linear');
	}
}

// -------------------------------------------------------------------------------------------------

function show_sheet(barcode, id) {
	// throbber
	$('#sheetbox').html("<div class='throbber' style='height: 450px'></div>");

	// show
	open_lightbox_sheet();
	var appserver = $("#appserver").val();
	var sid = $("#sid").val();
	// load full data
	$.ajax({
		url: $("#appserver").val(),
		async: false,
		type: 'POST',
		data: {
			tok: 'ck_dati_prodotto',
			sid: $("#sid").val(),
			barcode: barcode,
			fulldata: 1
		},
		success: function(data) {
			data = jQuery.parseJSON(data);
			var barcode = data[0][0];
			data = data[0][1];
			var html = '';

			if (data.promo == 'Y') {
				html += '<div class="tag_schedina"><a href="' + appserver + '?tok=ck_show_promo&sid=' + sid + '&id_promo=' + data.id_promo + '"><img src="/img/tags/promo_tag3.png" style="border: 0;"></a></div>';
			}
			else if ((data.prenota == 'PRENOTA') && (data.avail == '0.0')) {
				//html += "<div class='tag_schedina'><img src='/img/tags/book_tag3.png' border='0' /></div>";
				html += "<div class='tag_schedina'><img src='/img/tags/" + barcode + "_3.png' border='0' /></div>";
			}
			else if (data.news == 'Y') {
				html += "<div class='tag_schedina'><img src='/img/tags/new_tag3.png' border='0' /></div>";
			}
			else if (data.evidenza == 'CONSIGLIATO') {
				html += "<div class='tag_schedina'><img src='/img/tags/cons_tag3.png' border='0' /></div>";
			}

			html += "<div id='text'>";
			html += "<img src='/img/foto/marchi/medium/" + data.id_brand + ".png' />";
			html += "<strong>" + data.modelname + "</strong>";
			html += data['descrizione_catalogo'];
			html += "<div class='price'>";
			if (data.flag_prezzo == 'SHOW') {
				html += "<div class='euro'><strong>&euro; " + data.price + "</strong> iva esclusa</div>";
			}
			if (data.macroclasse == '5') {
				html += "<div class='public'>&nbsp;</div>";
			}
			else {
				html += "<div class='public'>(prezzo al pubblico &euro; " + data.retail + ")</div>";
			}
			// html += "<div class='kart'></div>";
			if (data.flag_prezzo == 'SHOW') {
				if (data.qty == '0') {
					if (data.avail != '0.0') {
						html += "<div class='kart' title='ordina' id='sheet_kart'>";
						html += "<input type='text' class='qty' value='1' id='sheet_qty' />";
						html += "<div class='add' onclick=\"ajax_order('" + barcode + "','sheet');\"></div>";
						html += "</div>";
					}
					else if (data.prenota == 'PRENOTA') {
						html += "<div class='kart blue' title='prenota' id='sheet_kart'>";
						html += "<input type='text' class='qty' value='1'  id='sheet_qty' />";
						html += "<div class='add' onclick=\"ajax_book('" + barcode + "','sheet');\"></div>";
						html += "</div>";
					}
					else {
						html += "<div class='kart red'></div>";
					}
				}
				else {
					html += "<div class='kart gray'></div>";
				}
			}
			html += "</div>"; // price
			html += "<div class='barcode'>cod art. " + data.codart + "</div>";
			html += "<div class='bcode'>barcode " + data.barcode + "</div>";
			// html += "<div class='barcode'>barcode " + barcode + "</div>";
			if (data.scheda_tecnica != '') {
				html += "<a class='pdf' href='/schede/" + data.scheda_tecnica + "'><strong>scheda tecnica</strong><br />download PDF</a>";
			}
			html += "</div>"; // text
			html += "<div id='image' style=\"background-image: url('/img/foto/240x350/" + data.image + "');\"></div>";

			html += "<div id='tabs'>";
			html +="<div id='tablist'>";
			html += "<div class='first tab' onclick=\"show_tab('compat', this, 3)\">compatibilità</div>";
			html += "<div class='tab selected' onclick=\"show_tab('products', this)\">altri prodotti</div>";
			html += "</div>"; // tablists

			html += "<div class='folder' id='compat'>";

			// ajax request (compatibility)

			$.ajax({
				url: $("#appserver").val(),
				async: false,
				type: 'POST',
				data: {
					tok: 'ck_lista_compat',
					sid: $("#sid").val(),
					barcode: barcode,
					id_articolo: barcode
				},
				success: function(data) {
					var response = jQuery.parseJSON(data);
					if (response.length > 0) {
						for (var brand in response) {
							html += '<a><b>' + response[brand][0] + '</b>: ';
							var l = response[brand][1].length - 1;
							for (var item in response[brand][1]) {
								if (item) {
									html += '<a>';
								}
								html += response[brand][1][item];
								if (item < l) {
									html += ',';
								}
								html += '</a> ';
							}
						}
					}
				}
			});

			html += "</div>"; // compat

			html += "<div class='first folder' id='products'>";

			html += "<div id='product_slider'>";
			html += "<div class='stripe'>";

			for (var bcode in product_cache[id]) {
				html += "<img onclick=\"show_sheet('" + product_cache[id][bcode] + "', '" + id + "');\" src='/img/foto/50x50/" + product_cache[id][bcode] + ".jpg' />";
			}

			html += "</div>"; // stripe
			html += "</div>"; // product_slider
			html += "<div id='product_left' onclick=\"slide_left();\"></div>";
			html += "<div id='product_right' onclick=\"slide_right();\"></div>";

			html += "</div>"; // products
			html += "</div>"; // tabs
			
			$('#sheetbox').html(html);
		}
	});

	// load strip data (once!)

	var elm = $('#product_slider img').size();
	$('#product_slider .stripe').css('width', THUMB_WIDTH * elm);
	if (elm > 7) {
		$('#product_slider').css({'width': '400px', 'margin-left': '36px'});
		$('#product_left, #product_right').show();
		set_product_arrows();
	}
	else {
		$('#product_slider').css({'width': '480px', 'margin-left': '-5px'});
		$('#product_left, #product_right').hide();
	}
}


// -------------------------------------------------------------------------------------------------
function slide_right() {
	var ml = parseInt($('#product_slider .stripe').css('margin-left'), 10);
	var w = parseInt($('#product_slider .stripe').css('width'), 10);

	if (w + ml > THUMB_WIDTH * 6) {
		$('#product_slider .stripe').animate({marginLeft: '-=' + THUMB_WIDTH * 6}, 500, 'swing', set_product_arrows);
	}
}


// -------------------------------------------------------------------------------------------------
function slide_left() {
	var ml = parseInt($('#product_slider .stripe').css('margin-left'), 10);

	if (ml < 0) {
		$('#product_slider .stripe').animate({marginLeft: '+=' + THUMB_WIDTH * 6}, 500, 'swing', set_product_arrows);
	}
}


// -------------------------------------------------------------------------------------------------
function set_product_arrows() {
	var ml = parseInt($('#product_slider .stripe').css('margin-left'), 10);
	var w = parseInt($('#product_slider .stripe').css('width'), 10);

	if (w + ml > THUMB_WIDTH * 6)
		$('#product_right').removeClass('inactive');
	else
		$('#product_right').addClass('inactive');

	if (ml < 0)
		$('#product_left').removeClass('inactive');
	else
		$('#product_left').addClass('inactive');
}


// -------------------------------------------------------------------------------------------------
function columnize(name, columns) { // tested only with 2 and 3 columns
	var foldername = '#' + name;
	// columnize
	if (columns != undefined && $(foldername + ' .column').size() == 0) {
		// add (empty) columns
		for (var idx=1; idx <= columns; idx++) {
			$(foldername).append("<div class='column col" + idx + "'></div>");
			if (idx < columns) {
				$(foldername).append("<div class='divider'></div>");
			}
		}

		// ROUGHLY distribute content between columns
		var size = $(foldername + ' > a').size();
		var elm_per_column = Math.ceil(size / columns);

		$(foldername + ' > a').each(function(index) {
			var column = Math.floor(index / elm_per_column) + 1;
			$(this).append(' ').appendTo(foldername + ' .col' + column);
		});
	}

	// trick to autoresize on column heights
	if ($(foldername + ' .column').size())
		$(foldername).css('height', $(foldername).height() + 'px');
}


// -------------------------------------------------------------------------------------------------
function show_tab(name, obj, columns) {
	columnize(name, columns);

	var foldername = '#' + name;

	$('.folder').hide();
	$(foldername).show();

	$('.tab').removeClass('selected');
	$(obj).addClass('selected');

	var folder_h = $(foldername).height();

	if (folder_h < 70) {
		$('#tabs').animate({height: 100}, 500);
	}
	else
		$('#tabs').animate({height: folder_h + 30}, 500);
}


// -------------------------------------------------------------------------------------------------
function show_movie(code) {
	$('#moviebox').html("<div class='throbber' style='height: 450px'></div>");
	open_lightbox_movie();
}


// -------------------------------------------------------------------------------------------------
function open_lightbox_sheet() {
	autoslide = 0;
	$("#forcefield").show();
	$("#sheet").css('opacity', 0).show().animate({opacity: 1}, 500);
}


// -------------------------------------------------------------------------------------------------
function open_lightbox_movie() {
	autoslide = 0;
	$("#forcefield").show();
	$("#movie").css('opacity', 0).show().animate({opacity: 1}, 500);
}


// -------------------------------------------------------------------------------------------------
function close_lightbox() {
	$("#moviebox").html('');
	$("#movie").hide();
	$("#sheet").hide();
	$("#forcefield").unbind("click").hide();
	autoslide = 1;
}


// -------------------------------------------------------------------------------------------------
function load_brands(autoload) {
	var response = [];

	init_bbq(); // init jQuery back button handling

	var html = "<div id='breadcrumbs'>Ricambi | Ricerca per marca</div>";

	$.ajax({
		url: $("#appserver").val(),
		async: false,
		type: 'POST',
		data: {
			tok: 'getBrands',
			sid: $("#sid").val()
		},
		success: function(data) {
			response = jQuery.parseJSON(data);
		},
		error: function() {
			//alert('Impossibile contattare server');
			response = [];
		}
	});

	for (var brand in response) {
		var obj = response[brand];
		html += "<div class='collapsable collapsed' id='" + obj[0] + "'>";
		html += "<a id='bookmark_" + obj[0] + "' />";
		html += "<div class='collapser'>";

		html += "<div class='brand' style=\"background-image: url('/img/foto/marchi/medium/" + obj[0] + ".png')\"></div>";

		if (obj.length > 2) {
			html += "<div class='banner' style=\"background-image: url('/img/" + obj[2] + "')\"></div>";
			html += "<div class='sensible overlay' onclick=\"expand('brand','" + obj[0] + "')\"></div>"
		}
		else {
			html += "<div class='banner'></div>";
			html += "<div class='sensible' onclick=\"expand('brand','" + obj[0] + "')\"></div>"
		}

		html += "</div>"; // collapser

		html += "<div class='filters'></div>";
		html += "<div class='paging'></div>";
		html += "<div class='results'></div>";
		html += "<div class='paging'></div>";

		html += "</div>"; // collapsable
	}

	$('#rside').html(html);

	//if (autoload != undefined) {
	//	expand('brand', autoload);
	//}

	var params = bbq_params();

	if (params['cmd'] == 'expand' && params['what'] == 'brand') {
		$(window).trigger("hashchange");
	}
	else if (autoload != undefined) {
		bbq_pushState({cmd: 'expand', what: 'brand', id: autoload});
	}
	else {
		bbq_pushState({cmd: 'expand', what: '', id: ''});
	}
}


// -------------------------------------------------------------------------------------------------
function list_brands() {
	var response = [];
	var html = '';

	if ($('#biglist').length == 0) {
		var html = '';
		html += "<div id='breadcrumbs'></div>";
		html += "<div class='half' onclick='list_brands();' style='margin-right: 10px'>Ricerca per Marca</div>";
		html += "<div class='half' onclick='list_categories();'>Ricerca per Categoria</div>";
		html += "<div id='biglist'></div>";
		$('#rside').html(html);
		html = '';
	}

	$.ajax({
		url: $("#appserver").val(),
		async: false,
		type: 'POST',
		data: {
			tok: 'ck_lista_marchi_ricambi',
			sid: $("#sid").val()
		},
		success: function(data) {
			response = jQuery.parseJSON(data);
		},
		error: function() {
			//alert('Impossibile contattare server');
			response = [];
		}
	});

	for (var brand in response) {
		var obj = response[brand];
		html += "<div class='listitem' id='" + obj[0] + "' style=\"background-image: url('/img/foto/marchi/medium/" + obj[1] + ".png')\" onclick=\"load_compatible_brands('" + obj[0] + "');\"></div>";
	}

	$('#biglist').html(html).show();

	$('#breadcrumbs').html('Ricambi | Ricerca per marca');
}


// -------------------------------------------------------------------------------------------------
function load_compatible_brands(autoload) {
	var response = [];

	init_bbq();

	var html = "<div id='breadcrumbs'>Ricambi | Ricerca per marca <span class='alternate' onclick='list_categories()'> Ricerca per categoria </span></div>";
	$.ajax({
		url: $("#appserver").val(),
		async: false,
		type: 'POST',
		data: {
			tok: 'ck_lista_marchi_ricambi',
			sid: $("#sid").val()
		},
		success: function(data) {
			response = jQuery.parseJSON(data);
		},
		error: function() {
			//alert('Impossibile contattare server');
			response = [];
		}
	});

	for (var brand in response) {
		var obj = response[brand];
		html += "<div class='collapsable collapsed' id='" + obj[0] + "'>";
		html += "<a id='bookmark_" + obj[0] + "' />";

		html += "<div class='collapser'>";
		html += "<div class='brand' style=\"background-image: url('/img/foto/marchi/medium/" + obj[0] + ".png')\"></div>";
		html += "<div class='model'></div>";
		html += "<div class='sensible' onclick=\"expand('compatible', '" + obj[0] + "')\"></div>"
		html += "</div>"; // collapser

		html += "<div class='paging'></div>";
		html += "<div class='thumbs'></div>";
		html += "<div class='results'></div>";
		html += "<div class='paging'></div>";
		html += "</div>"; // collapsable
	}

	$('#rside').html(html);

	//if (autoload != undefined) {
	//	expand('compatible', autoload);
	//}

    var params = bbq_params();
    if (params['cmd'] == 'expand' && params['what'] == 'compatible') {
		$(window).trigger("hashchange");
	}
    else if (autoload != undefined) {
		bbq_pushState({cmd: 'expand', what: 'compatible', id: autoload});
	}
    else {
		bbq_pushState({cmd: 'expand', what: '', id: ''});
	}
}


// -------------------------------------------------------------------------------------------------
function load_categories(autoload) {
	var response = [];
	var html = "<div id='breadcrumbs'>Ricambi | Ricerca per categoria <span class='alternate' onclick='list_brands()'> Ricerca per marca </span></div>";

	$.ajax({
		url: $("#appserver").val(),
		async: false,
		type: 'POST',
		data: {
			tok: 'ck_show_class',
			sid: $("#sid").val(),
			macroclasse: $("#macroclasse").val()
		},
		success: function(data) {
			response = jQuery.parseJSON(data);
		},
		error: function() {
			//alert('Impossibile contattare server');
			response = [];
		}
	});

	for (var category in response) {
		var obj = response[category];
		html += "<div class='collapsable collapsed' id='" + obj[0] + "'>";
		html += "<a id='bookmark_" + obj[0] + "' />";

		html += "<div class='collapser'>";
		if ($("#macroclasse").val() == '3') {
			html += "<div class='brand' style=\"background-image: url('/img/foto/marchi/medium/" + obj[0] + ".png')\"></div>";
		}
		else {
			html += "<div class='category'>" + obj[1] + "</div>";
		}
		html += "<div class='sensible' onclick=\"expand('category','" + obj[0] + "')\"></div>"
		html += "</div>"; // collapser

		html += "<div class='filters'></div>";
		html += "<div class='paging'></div>";
		html += "<div class='results'></div>";
		html += "<div class='paging'></div>";

		html += "</div>"; // collapsable
	}

	$('#rside').html(html);

	if (autoload != undefined) {
		expand('category', autoload);
	}
}


// -------------------------------------------------------------------------------------------------
function list_categories() {
	var response = [];
	var html = '';

	if ($('#biglist').length == 0) {
		var html = '';
		html += "<div id='breadcrumbs'></div>";
		html += "<div class='half' onclick='list_brands();' style='margin-right: 10px'>Ricerca per Marca</div>";
		html += "<div class='half' onclick='list_categories();'>Ricerca per Categoria</div>";
		html += "<div id='biglist'></div>";
		$('#rside').html(html);
		html = '';
	}

	$.ajax({
		url: $("#appserver").val(),
		async: false,
		type: 'POST',
		data: {
			tok: 'ck_show_class',
			sid: $("#sid").val(),
			macroclasse: '5'
		},
		success: function(data) {
			response = jQuery.parseJSON(data);
		},
		error: function() {
			//alert('Impossibile contattare server');
			response = [];
		}
	});

	for (var brand in response) {
		var obj = response[brand];
		html += "<div class='listitem' id='" + obj[0] + "' onclick=\"load_categories('" + obj[0] + "')\">" + obj[1] + "</div>";
	}

	$('#biglist').html(html).show();

	$('#breadcrumbs').html('Ricambi | Ricerca per categoria');
}


// -------------------------------------------------------------------------------------------------
function expand(what, id) {
	// don't push (re)collapsing
	var params = bbq_params();
	if (params['what'] == what && params['id'] == id) {
		bbq_expand(what, id);
		return;
	}
	bbq_pushState({cmd: 'expand', what: what, id: id});
}


// -------------------------------------------------------------------------------------------------
function bbq_expand(what, id) {
	if ($('#'+id).hasClass('collapsed')) {
		$('.collapsable').addClass('collapsed');
		$('.collapser .model').hide();
		$('.thumbs').hide();

		if ($('#' + id + ' .filters').size() == 0 || $('#' + id + ' .filters').html() == '' || $('#' + id + ' .model').html() == '') {
			$('#' + id + ' .filters').html("<div class='throbber' style='height: 80px'></div>");
			$('#' + id + ' .model').html("<div class='throbber' style='width: 100px; height: 38px'></div>").show();
			$('#' + id + ' .results').html('');
			$('#' + id).removeClass('collapsed');

			var response = [];
			var html = "<b>Filtra articoli:</b>" +
				"<div class='filters_btn selected' id=\"filters_all\" onclick=\"set_all_filters('" + id + "', true)\">tutti</div> " +
				"<div class='filters_btn' id=\"filters_none\" onclick=\"set_all_filters('" + id + "', false)\">nessuno</div> " +
				"<div class='apply' onclick=\"apply_filters('" + what + "','" + id + "')\">Applica filtri</div><br />";

			//var html = "<b>Filtra articoli<div class='apply' onclick=\"apply_filters('" + what + "','" + id + "')\">Applica filtri</div><br /></b>";

			if (what == 'brand') {
				data = {
					tok: 'ck_show_sottoclassi',
					sid: $("#sid").val(),
					macroclasse: $("#macroclasse").val(),
					id_classe: id
				}
			}
			else if (what == 'category') {
				data = {
					tok: 'ck_show_sottoclassi',
					sid: $("#sid").val(),
					macroclasse: $("#macroclasse").val(),
					id_classe: id
				}
			}
			else if (what == 'compatible') {
				data = {
					tok: 'ck_lista_telefoni_marca',
					sid: $("#sid").val(),
					id_marca: id,
					macroclasse: $("#macroclasse").val()
				}
			}
			else if (what == 'quick') {
				data = {
					tok: 'ck_show_sottoclassi_free',
					sid: $("#sid").val(),
					id_marca: free_brand,
					id_telefono: free_model,
					prodotto: free_text
				}
			}
			else if (what == 'news') {
				data = {
					tok: 'ck_show_sottoclassi_news',
					sid: $("#sid").val(),
					buffer: $("#buffer").val()
				}
			}
			else if (what == 'cons') {
				data = {
					tok: 'ck_show_sottoclassi_cons',
					sid: $("#sid").val(),
					buffer: $("#buffer").val()
				}
			}
			else {
				alert('unknown filter list');
				return;
			}

			$.ajax({
				url: $("#appserver").val(),
				async: false,
				type: 'POST',
				data: data,
				success: function(data) {
					response = jQuery.parseJSON(data);
					if (response == false) {
						alert('ko');
					}
					else {
						if ($('#' + id + ' .filters').size()) {// filters
							for (var filter in response) {
								// set all filters as inactive but with status change requested (to trigger initial population of products)
								html += "<div class='filter inactive changed " + response[filter][0] + "' onclick=\"toggle_filter('" + id + "','" + response[filter][0] + "')\">" + response[filter][1] + "</div>";
							}
	
							for (var i = 0; i < 6 - response.length % 6; i++) {
								html += "<div class='filter empty'>&nbsp;</div>";
							}
	
							$('#' + id + ' .filters').html(html);
	
						}
						else
						{// dropdown list
							html = "Seleziona modello ";
							html += "<select class='selected_model' onchange=\"update_product_list('" + what + "','" + id + "');\">";
							html += "<option value=''> -- modello -- </option>";
	
							for (var model in response) {
								html += "<option value='" + response[model][0] + "'>" + response[model][1] +"</option>";
							}
							html += "</select>";
	
							$('#' + id + ' .model').html(html).show();
	
							// add image list (an alternative to dropdown list usage
	
							html = '';
							for (var model in response) {
								html += "<div class='thumb " + response[model][0] + "' onclick=\"set_selected_model('" + id + "','" + response[model][0] + "'); update_product_list('" + what + "','" + id + "');\">";
								html += "<div class='throbber' style='height: 180px'></div>";
								html += "</div>";
							}
	
							$('#' + id + ' .thumbs').html(html).show();
	
							// enqueue ajax requests
							var lista_telefoni = '';
							for (var model in response) {
								lista_telefoni += response[model][0] + ' ';
							}
							$.ajax({
								url: $("#appserver").val(),
								async: true,
								type: 'POST',
								data: {
									tok: 'ck_dati_telefono',
									sid: $("#sid").val(),
									id_telefono: lista_telefoni,
									thumb: 1
								},
								success: function(data) {
									var resp = jQuery.parseJSON(data);
									for (var item in resp) {
										var html = '';
										html += "<div class='foot'>" + resp[item][1]['modelname'] + "</div>";
										$('#' + id + ' .thumbs .thumb.' + resp[item][0]).html(html).css({'background-image': "url('/img/foto/telefoni/190x135/" + resp[item][0] + ".jpg')"});
									}
								}
							});
						}
					}
				},
				error: function() {
					//alert('Impossibile contattare server');
					response = [];
				}
			});
		}

		$('#' + id).removeClass('collapsed');
		$('#' + id + ' .model').show();
		$('#' + id + ' .thumbs').show();

		apply_filters(what, id);
	}
	else {
		$('.collapsable').addClass('collapsed');
		$('.collapser .model').hide();
		$('.thumbs').hide();

		// remove paging if in thumbs mode
		if (id != '' && $('#' + id + ' .filters').size() == 0) {
			$('#' + id + ' .paging').html('');
		}

		// jump to correct location
		$('html, body').animate({scrollTop: 0});
	}
}


// -------------------------------------------------------------------------------------------------
function set_selected_model(id, barcode)
{
	$('#' + id + ' .selected_model').val(barcode);
}


// -------------------------------------------------------------------------------------------------
function toggle_filter(id, filter) {
	$('#' + id + ' .filter.' + filter).toggleClass('changed');
	if ($('#' + id + ' .filter.changed').size()) {
		$('#' + id + ' .apply').show();
	}
	else {
		$('#' + id + ' .apply').hide();
	}
}


// ---------------------------------------------------------------------------
function set_all_filters(id, selected) {
	var apply = false;

	$('#' + id + ' .apply').hide();

	$('#' + id + ' .filter').each(function() {
		var obj = $(this);

		if (obj.hasClass('empty'))
			return;

		var inactive = obj.hasClass('inactive');
		var changed = obj.hasClass('changed');

		if (selected && inactive) {
			obj.addClass('changed');
			apply = true;
		}
		else if (!selected && !inactive) {
			obj.addClass('changed');
			apply = true;
		}
        else {
        	obj.removeClass('changed');
        }
	});

	if (apply) {
		$('#' + id + ' .apply').show();
	}
	
	if (selected) {
		$('#filters_all').addClass('selected');
		$('#filters_none').removeClass('selected');
	}
	else {
		$('#filters_all').removeClass('selected');
		$('#filters_none').addClass('selected');	
	}
}


// -------------------------------------------------------------------------------------------------
function apply_filters(what, id) {
	var changed = $('#' + id + ' .filter.changed').size();
	$('#' + id + ' .filter.inactive.changed').removeClass('inactive').removeClass('changed');
	$('#' + id + ' .filter.changed').addClass('inactive').removeClass('changed');
	$('#' + id + ' .apply').hide();

	// if any change in filter --> update product list
	if (changed) {
		var tm = new Date();
		update_product_list(what, id, tm.getTime());
	}
	else {
		// jump to correct page location
		$('html, body').animate({scrollTop: $('#bookmark_'+id)[0].offsetTop + 5});
	}
}


// -------------------------------------------------------------------------------------------------
function update_product_list(what, id, unique) {
	var barcode = $('#' + id + ' .selected_model').val();
	if (barcode == '') {
		bbq_pushState({cmd: 'expand', what: what, id: id, unique: unique}); // no product selected: show thumbnails
	}
	else {
		bbq_pushState({cmd: 'update_product_list', what: what, id: id, barcode: barcode, unique: unique});
	}
}


// -------------------------------------------------------------------------------------------------
function bbq_update_product_list(what, id) {
	// hide thumbnails
	$('#' + id + ' .thumbs').html('').hide();

	// find selected filters
	var filters = "";
	$('#' + id + ' .filters .filter').each(function(index) {
		if ($(this).hasClass('inactive')) {
			return;
		}
		var classes = $(this).attr('class').split(/\s+/);
		for (var i in classes) {
			var cls = classes[i];
			if (cls != 'filter' && cls != 'empty' && cls != 'inactive') {
				filters += cls + ' ';
			}
		}
	});
	// to avoid search for all if no filter is selected
	if (filters == '') {
		filters = '*#*#';
	}
	// request matching product list
	var response = [];

	if (what == 'brand') {
		data = {
			tok: 'ck_lista_prodotti',
			sid: $("#sid").val(),
			microclasse: id,
			filters: filters
		}
	}
	else if (what == 'category') {
		data = {
			tok: 'ck_lista_prodotti',
			sid: $("#sid").val(),
			microclasse: id,
			filters: filters
		}
	}
	else if (what == 'search') {
		data = {
			tok: 'ck_lista_prodotti',
			sid: $("#sid").val(),
			id_marca: $("#id_marca").val(),
			id_telefono: $("#id_telefono").val(),
			prodotto: $("#prodotto").val(),
			filters: filters
		}
	}
	else if (what == 'compatible') {
		data = {
			tok: 'ck_lista_prodotti',
			sid: $("#sid").val(),
			id_marca: id,
			id_telefono: $('#' + id + ' .selected_model').val(),
			macroclasse: $("#macroclasse").val()
		}
	}
	else if (what == 'quick') {
		data = {
			tok: 'ck_lista_quick',
			sid: $("#sid").val(),
			id_marca: free_brand,
			id_telefono: free_model,
			prodotto: free_text,
			filters: filters
		}
	}
	else if (what == 'news') {
		data = {
			tok: 'ck_lista_news',
			sid: $("#sid").val(),
			buffer: $("#buffer").val(),
			filters: filters
		}
	}
	else if (what == 'cons') {
		data = {
			tok: 'ck_lista_cons',
			sid: $("#sid").val(),
			buffer: $("#buffer").val(),
			filters: filters
		}
	}
	else {
		alert('unknown filter list');
		return;
	}

	$.ajax({
		url: $("#appserver").val(),
		async: false,
		type: 'POST',
		data: data,
		success: function(data) {
			response = jQuery.parseJSON(data);
			product_cache[id] = response;

			if ($('#' + id + ' .backtopages').size()) {
				unpaged(id);
			}
			else {
				goto_page(id, 1);
			}
		},
		error: function() {
			//alert('Impossibile contattare server');
			response = [];
		}
	});
}


// -------------------------------------------------------------------------------------------------
function goto_page(id, page) {
	var staticphoto = $('#' + id + ' .filters').size() == 0;
	var pagesize = PAGESIZE;

	if (staticphoto)
		pagesize = PAGESIZE - 1; // make room for the static photo

	var productlist = [];
	var lowerlimit = (page-1) * pagesize;
	var upperlimit = page * pagesize;
	var pages = Math.ceil(product_cache[id].length / pagesize);

	html = page + ' di ' + pages + ' ';
	html +=  page > 1 ? '<a href="javascript:goto_page(\'' + id + '\',' + (page-1) + ');">&lt;</a>' : '&lt;';
	html += ' &middot; ';
	html +=  page < pages  ? '<a href="javascript:goto_page(\'' + id + '\',' + (page+1) + ');">&gt;</a>' : '&gt;';
	html += ' | <a class="all" href="javascript:unpaged(\'' + id + '\');">mostra tutte</a>';
	$('#' + id + ' .paging').html(html);

	if (staticphoto) {
		productlist = ['STATIC' + $('#' + id + ' .selected_model').val()]; // STATIC is a keyword for inplace_update()
	}

	for (var idx in product_cache[id]) {
		if (idx < lowerlimit) {
			continue;
		}
		if (idx >= upperlimit) {
			break;
		}
		productlist.push(product_cache[id][idx]);
	}
	in_place_update(id, productlist);
}


// -------------------------------------------------------------------------------------------------
function unpaged(id) {
	var staticphoto = $('#' + id + ' .filters').size() == 0;

	html = product_cache[id].length + ' prodotti | ';
	html += '<a class="backtopages" href="javascript:goto_page(\'' + id + '\', 1);">mostra pagine</a>';
	$('#' + id + ' .paging').html(html);

	if (staticphoto) {
		productlist = ['STATIC' + $('#' + id + ' .selected_model').val()]; // STATIC is a keyword for inplace_update()
		productlist = productlist.concat(product_cache[id]);
		in_place_update(id, productlist);
	}
	else {
		in_place_update(id, product_cache[id]);
	}
}


// -------------------------------------------------------------------------------------------------
function in_place_update(id, productlist)
{
	// mark products already in page
	var page_elm = [];
	$('#' + id + ' .results .result').removeClass('keep')

	for (var candidate in productlist) {
		var barcode = productlist[candidate];
		page_elm.push(barcode);

		// mark product if already displayed
		$('#' + id + ' .results .' + barcode).addClass('keep');
	}

	// remove products not in list
	$('#' + id + ' .results .result').each(function() {
		if ($(this).hasClass('keep')) {
			return;
		}
		$(this).remove();
	});

	// add/sort products
	
	var id_telefono = '';
	
	for (var idx in page_elm) {
		var barcode = page_elm[idx];
		var elm = $('#' + id + ' .results .' + barcode);
		if (elm.size() == 0) {
			// new product: create and append to the end of the list
			elm = jQuery('<div />', {'class': 'result ' + barcode, 'html': "<div class='throbber'></div>"});
			$('#' + id + ' .results').append(elm);
			// send ajax request to populate div
			if (barcode.indexOf('STATIC') == 0) {
				$.ajax({
					url: $("#appserver").val(),
					async: false,
					type: 'POST',
					data: {
						tok: 'ck_dati_telefono',
						sid: $("#sid").val(),
						id_telefono: barcode.substring(6), // 'STATIC' removed from query
						static: 1					  // ! response could be different from standard
					},
					success: function(data) {
						var response = jQuery.parseJSON(data);
						for (var item in response) {
							$('#' + id + ' .results .STATIC' + response[item][0]).html(make_staticphoto(response[item], id));
						}
					}
				});
			}
			else {
				id_telefono += barcode + ' ';
			}
		}
		else {
			// product already displayed: move at the end of the list
			elm.detach().appendTo($('#' + id + ' .results'));
		}
	}

	$.ajax({
		url: $("#appserver").val(),
		async: false,
		type: 'POST',
		data: {
			tok: 'ck_dati_prodotto',
			sid: $("#sid").val(),
			barcode: id_telefono
		},
		success: function(data) {
			var response = jQuery.parseJSON(data);
			for (var item in response) {
				$('#' + id + ' .results .' + response[item][0]).html(make_quicksheet(response[item], id));
			}
		}
	});

	// jump to correct page location
	$('html, body').animate({scrollTop: $('#bookmark_'+id)[0].offsetTop + 5});
}


// -------------------------------------------------------------------------------------------------
function make_quicksheet(data, id) {
	var html = '';
	var barcode = data[0];
	var appserver = $("#appserver").val();
	var sid = $("#sid").val();
	data = data[1];
	html += "<div class='head'>";
	html += "<div class='brand' onclick=\"show_sheet('" + barcode + "', '" + id + "')\" style=\"background-image: url('/img/foto/marchi/medium/" + data.id_brand + ".png')\"></div>";
	//html += "<div class='sensible' onclick=\"show_bigimg('" + data.bigimg + "')\"></div>";
	html += "<div class='sensible' onclick=\"show_sheet('" + barcode + "', '" + id + "')\"></div>";
	html += "</div>";

	html += "<div class='image' onclick=\"show_sheet('" + barcode + "', '" + id + "')\" style=\"background-image: url('/img/foto/190x135/" + data.image + "')\"></div>";
	if (data.promo == 'Y') {
		html += '<div class="promo"><a href="' + appserver + '?tok=ck_show_promo&sid=' + sid + '&id_promo=' + data.id_promo + '"><img src="/img/tags/promo_tag.png" style="border: 0;"></a></div>';
	}
	else if ((data.prenota == 'PRENOTA') && (data.avail == '0.0')) {
		//html += "<div class='book'></div>";
		html += "<div class='book'><img src='/img/tags/" + barcode + "_1.png' border='0' /></div>";
	}
	else if (data.news == 'Y') {
		html += "<div class='new'></div>";
	}
	else if (data.evidenza == 'CONSIGLIATO') {
		html += "<div class='cons'></div>";
	}
	//html += "<div class='name'>" + data.name + "</div>";
	//html += "<div class='descr'>" + data.descr + "</div>";
	html += "<div class='namedescr'><b>" + data.name + "</b><br>" + data.descr + "</div>";
	html += "<div class='codart'>barcode . " + data.barcode + "</div>";

	if (data.flag_prezzo == 'SHOW') {
		html += "<div class='price'>";
		html += "<div class='euro'><strong>&euro; " + data.price + "</strong> iva esclusa</div>";
		if (data.macroclasse == '5') {
			html += "<div class='public'>&nbsp;</div>";
		}
		else {
			html += "<div class='public'>(prezzo al pubblico &euro; " + data.retail + ")</div>";
		}	
		if (data.qty == '0') {
			if (data.avail != '0.0') {
				html += "<div class='kart' title='ordina'>";
				html += "<input type='text' class='qty' value='1' />";
				html += "<div class='add' onclick=\"ajax_order('" + barcode + "');\"></div>";
				html += "</div>";
			}
			else if (data.prenota == 'PRENOTA') {
				html += "<div class='kart blue' title='prenota'>";
				html += "<input type='text' class='qty' value='1' />";
				html += "<div class='add' onclick=\"ajax_book('" + barcode + "');\"></div>";
				html += "</div>";
			}
			else {
				html += "<div class='kart red'></div>";
			}
		}
		else {
			html += "<div class='kart gray'></div>";
		}
	}

	html += "<div class='barcode'>cod art . " + barcode.replace('___', '\/').replace('_-_', '.').replace('_-_', '.').replace('---', ' ') + "</div>";
	// html += "<div class='barcode'>barcode . " + barcode + "</div>";

	html += "<div class='footer'>";
	//html += "<div class='comp' onclick=\"show_compatibility('" + barcode.replace('___', '\/').replace('_-_', '.').replace('_-_', '.').replace('---', ' ') + "')\">compatibilit&agrave;</div>";
	html += "<div class='comp' onclick=\"show_compatibility('" + barcode + "')\">compatibilit&agrave;</div>";
	//html += "<div class='sheet' onclick=\"show_sheet('" + barcode + "', '" + id + "')\">scheda</div>";

	if (data.scheda_prodotto == 'Y') {
		html += '<div class="sheet"><a href="' + appserver + '?tok=ck_show_prodotto&sid=' + sid + '&id_articolo=' + barcode + '" style="color:#0aa; text-decoration: none;">scheda</a></div>';
	}
	else {
		html += '<div class="sheet inactive">scheda</div>';
	}
	if (data.video != '') {
		//html += "<div class='movie' onclick=\"show_movie('" + barcode + "', '" + id + "')\">video</div>";
		html += '<div class="movie"><a href="#" rel="div.overlay">video</a></div>';
		html += "<div class='overlay'>";
		//html += '<a id="player" href="/video/' + data.video + '">&nbsp;</a>';
		html += '<a id="' + data.video + '" href="/video/' + data.video + '">&nbsp;</a>';
		html += "</div>";
	}
	else {
		html += "<div class='movie inactive'>video</div>";
	}
	html += "</div>";
	return html
}


// -------------------------------------------------------------------------------------------------
function make_staticphoto(data, id) {
	var html = '';
	var barcode = data[0];
	data = data[1];

	html += "<div class='head gray'></div>";

	//html += "<div class='staticphoto' style=\"background-image: url('/img/foto/telefoni/190x285/" + data.static + ".jpg')\"></div>";
	html += "<div class='staticphoto' style=\"background-image: url('/img/foto/telefoni/190x285/" + barcode + ".jpg')\"></div>";

	html += "<div class='footer gray'>" + data.modelname + "</div>";

	return html
}


// -------------------------------------------------------------------------------------------------
function show_compatibility(code) {
	$('#forcefield').click(hide_compatibility).show();

	var html = "<div class='throbber'></div>";
	html += "<div class='close' onclick='hide_compatibility()'></div>";

	// relative div positioning (and left/right ramp choosing)
	var res_offset = $('.results .result.' + code).offset();
	var ref_offset = $('.results .result.' + code).parent('.results').offset();

	var ypos = res_offset.top + 50;
	var xpos = res_offset.left + 140;

	if (res_offset.left - ref_offset.left < 300) {
		html += "<div class='ramp_left'></div>";
	}
	else {
		xpos = res_offset.left - 430;
		html += "<div class='ramp_right'></div>";
	}

	$('#compatibility_list').html(html).css({top: ypos + 'px', left: xpos + 'px', height: '100px'}).show();

	// ajax request

	$.ajax({
		url: $("#appserver").val(),
		async: false,
		type: 'POST',
		data: {
			tok: 'ck_lista_compat',
			sid: $("#sid").val(),
			barcode: code,
			id_articolo: code
		},
		success: function(data) {
			var response = jQuery.parseJSON(data);

			html = 'no data';
			if (response.length > 0) {
				// count elements
				var cnt = 0;
				for (var brand in response) {
					for (var item in response[brand][1]) {
						cnt++;
					}
				}

				var half = Math.ceil(cnt / 2);

				var idx = 0;
				html = "<div class='column col1'>"
				for (var brand in response) {
					html += '<a><b>' + response[brand][0] + '</b>: ';
					var l = response[brand][1].length - 1;
					for (var item in response[brand][1]) {
						if (item) {
							html += '<a>';
						}
						html += response[brand][1][item];
						if (item < l) {
							html += ',';
						}
						html += '</a> ';

						idx++;

						if (idx == half) {
							html += "</div><div class='divider'></div><div class='column col2'>";
						}
					}
				}
				html += "</div>"

			}

			$('#compatibility_list .throbber').remove();
			$('#compatibility_list').append(html);

			// autoresize column heights
			var h = Math.max(
				$('#compatibility_list .col1').height(),
				$('#compatibility_list .col2').height()
				);
			if (h < 40) {
				h = 40
			}
			$('#compatibility_list').css('height', h + 'px');
		},
		error: function() {
			hide_compatibility();
		}
	});
}


// -------------------------------------------------------------------------------------------------
function hide_compatibility() {
	$('#compatibility_list').hide();
	$('#forcefield').unbind('click').hide();
}


// -------------------------------------------------------------------------------------------------
function show_bigimg(file) {
	$('#forcefield').click(hide_bigimg).show();
	var html = "<div class='throbber'></div>";
	html += "<div class='close' onclick='hide_bigimg()'></div>";
	$('#compatibility_list').html(html).css({top: '50%', left: '50%', height: '100px', width: '100px', 'margin-top': '-50px', 'margin-left': '-50px'}).show();

	// load image
	$('#compatibility_list').html(
		$("<img/>")
		.attr("src", '/img/' + file)
		.load(function() {
			$('#compatibility_list').animate(
			{top: '50%', left: '50%', height: this.height, width: this.width, 'margin-top': this.height/-2, 'margin-left': this.width/-2}, 500)
		})).append("<div class='close' onclick='hide_bigimg()'></div>");
}


// -------------------------------------------------------------------------------------------------
function hide_bigimg() {
	$('#compatibility_list').html('').css({top: '50%', left: '50%', height: '100px', width: '420px', 'margin-top': 0, 'margin-left': 0}).hide();
	$('#forcefield').unbind('click').hide();
}


// -------------------------------------------------------------------------------------------------
function get_qty(barcode, sheet) {
	var qty = 0;

	if (sheet != undefined) {
		qty = $('#sheet_qty').val() * 1;
	}
	else {
		qty = $('.results .' + barcode + ' .qty').val() * 1;
	}

	if (isNaN(qty)) {
		return 0;
	}

	return Math.floor(qty);
}


// -------------------------------------------------------------------------------------------------
function ajax_order(barcode, sheet) {
	var qty = get_qty(barcode, sheet);

	if (qty < 1 || qty > 99) {
		$('.results .' + barcode + ' .qty, #sheet_qty, #buttons .qty').val('1');
		return;
	}

	// throbber
	$('.results .' + barcode + ' .kart, #sheet_kart, #buttons').html("<div class='smallthrobber'></div>");

	// ajax request

	$.ajax({
		url: $("#appserver").val(),
		async: false,
		type: 'POST',
		data: {
			tok: 'ck_add_item',
			sid: $("#sid").val(),
			id_cliente: $("#id_cliente").val(),
			id_articolo: barcode,
			quantita: qty
		},
		success: function(data) {
			var response = jQuery.parseJSON(data);

			var cart_value = response[0];
			var qty = response[1];

			// update cart's totale
			$('#tot').html('tot &euro; ' + cart_value);

			// update kart box status
			if (barcode.indexOf('PROMO') == 0) {
				$('#promo_buttons').html('').addClass('gray');
			}
			else {
				$('.results .' + barcode + ' .kart, #sheet_kart, #buttons').html('').addClass('gray');
			}
		}
	});
}


// -------------------------------------------------------------------------------------------------
function ajax_book(barcode, sheet) {
	var qty = get_qty(barcode, sheet);

	if (qty < 1 || qty > 99) {
		$('.results .' + barcode + ' .qty, #sheet_qty, #buttons .qty').val('1');
		return;
	}

	$('.results .' + barcode + ' .kart, #sheet_kart, #buttons').html("<div class='smallthrobber'></div>");

	// ajax request

	$.ajax({
		url: $("#appserver").val(),
		async: false,
		type: 'POST',
		data: {
			tok: 'ck_add_item',
			sid: $("#sid").val(),
			id_cliente: $("#id_cliente").val(),
			id_articolo: barcode,
			status: 'PRENOTA',
			quantita: qty
		},
		success: function(data) {
			var response = jQuery.parseJSON(data);

			var cart_value = response[0];
			var qty = response[1];

			// update cart's totale
			$('#tot').html('tot &euro; ' + cart_value);

			// update kart box status
			$('.results .' + barcode + ' .kart, #sheet_kart, #buttons').html('').removeClass('blue').addClass('gray');
		}
	});
}


// -------------------------------------------------------------------------------------------------
function freesearch()
{
	init_bbq(); // init jQuery back button handling
	
	var tmp_brand = $("#id_marca").val();
	var tmp_model = $("#id_telefono").val();
	var tmp_text = $("#prodotto").val();

	if (tmp_brand == 'marca') {
		tmp_brand = '';
	}
	if (tmp_model == 'modello') {
		tmp_model = '';
	}
	if (tmp_text  == 'ricerca libera') {
		tmp_text = '';
	}

	if (tmp_brand == '' && tmp_model == '' && tmp_text == '') {
		alert('Inserire almeno un parametro di ricerca');
		return;
	}

	free_brand = tmp_brand;
	free_model = tmp_model;
	free_text = tmp_text;

	var html = "<div id='breadcrumbs'>Ricerca libera ";
	//if (free_brand != '') html += free_brand;
	//else				   html += '(all)';

	//if (free_model != '') html += " + " + free_model;
	//else				   html += " + (all)"

	//if (free_text != '') html += " + " + free_text;
	html += "</div>";

	html += "<div class='collapsable collapsed' id='free_result'>";
	html += "<a id='bookmark_free_result' />";

	html += "<div class='filters'></div>";
	html += "<div class='paging'></div>";
	html += "<div class='results'></div>";
	html += "<div class='paging'></div>";

	$('#rside').html(html);

	expand('quick','free_result');
}


// -------------------------------------------------------------------------------------------------
function qtyup(barcode) {
	var obj = $('#QTY' + barcode);
	obj.focus();
	obj.val(parseInt(obj.val()) + 1);
	obj[0].onchange();
	obj.blur();
}


// -------------------------------------------------------------------------------------------------
function qtydown(barcode) {
	var obj = $('#QTY' + barcode);
	obj.focus();
	obj.val(parseInt(obj.val()) - 1);
	obj[0].onchange();
	obj.blur();
}


// -------------------------------------------------------------------------------------------------
function qtyzero(barcode) {
	var obj = $('#QTY' + barcode);
	obj.focus();
	obj.val(0);
	obj[0].onchange();
	obj.blur();
}


// -------------------------------------------------------------------------------------------------
function qtychange(barcode) {
	var obj = $('#QTY' + barcode);
	var qty = parseInt(obj.val());

	if (qty <= 0) {
		qty = 0;

		if (!confirm("Confermi rimozione articolo?")) {
			qty = -1; // reload without changes
		}
	}

	// ajax request


	$.ajax({
		url: $("#appserver").val(),
		async: false,
		type: 'POST',
		data: {
			tok: 'ck_upd_item',
			sid: $("#sid").val(),
			id_articolo: barcode,
			quantita: qty
		},
		success: function(data) {
			var response = jQuery.parseJSON(data);

			var cart_value = response[0];
			var qty = response[1];
			var line_value = response[2];

			$('#tot').html('tot &euro; ' + cart_value);
			$('#number').html(cart_value + " &euro;");

			if (qty == '0') {
				$("#ART" + barcode).remove();
				return;
			}

			// qty > 0
			$('#QTY' + barcode).val(qty);
			$('#VAL' + barcode).html("<p>" + line_value + " &euro;</p>");
		}
	});
}


// -------------------------------------------------------------------------------------------------
function load_brand_category(prefix, what, showphones, autoload) {
	var response = [];

	init_bbq(); // init jQuery back button handling
	
	var html = "<div id='breadcrumbs'></div>";

	if (what == 'brand') {
 		if (prefix in  {'Compatibili': '', 'Ricambi': ''}) {
			html = '<div id="breadcrumbs">' + prefix + ' | ' +
				'<div class="type_btn selected" id="type_marca" onclick=\'load_brand_category("' + prefix + '", "brand", "' + showphones + '", "' + autoload + '")\'>Ricerca per marca</div>' +
				'<div class="type_btn" id="type_categoria" onclick=\'load_brand_category("' + prefix + '", "category", "' + showphones + '", "' + autoload + '")\'>Ricerca per categoria</div>' +
				'</div>';
		}
		else {
			html = "<div id='breadcrumbs'>" + prefix + " | Ricerca per marca</div>";
		}
	}
	else if (what == 'category') {
		if (prefix in  {'Compatibili': '', 'Ricambi': ''}) {
			html = '<div id="breadcrumbs">' + prefix + ' | ' +
				'<div class="type_btn" id="type_marca" onclick=\'load_brand_category("' + prefix + '", "brand", "' + showphones + '", "' + autoload + '")\'>Ricerca per marca</div>' +
				'<div class="type_btn selected" id="type_categoria" onclick=\'load_brand_category("' + prefix + '", "category", "' + showphones + '", "' + autoload + '")\'>Ricerca per categoria</div>' +
				'</div>';
		}
		else {
			html = "<div id='breadcrumbs'>" + prefix + " | Ricerca per categoria</div>";
		}
	}
	else {
		alert("load_brand_category NEEDS either 'brand' or 'category'.")
	}

	$.ajax({
		url: $("#appserver").val(),
		async: false,
		type: 'POST',
		data: {
			tok: (what == 'brand') ? 'ck_lista_marchi_ricambi': 'ck_show_class',
			//tok: (what == 'brand') ? 'ck_lista_marchi_ricambi': 'ck_show_class',
			//service: what == 'brand' ? 'getBrands' : 'getCategories'
			sid: $("#sid").val(),
			macroclasse: $("#macroclasse").val()
		},
		success: function(data) {
			response = jQuery.parseJSON(data);
		},
		error: function() {
			//alert('Impossibile contattare server');
			response = [];
		}
	});

	for (var item in response) {
		var obj = response[item];
		html += "<div class='collapsable collapsed' id='" + obj[0] + "'>";
		html += "<a id='bookmark_" + obj[0] + "' />";
		html += "<div class='collapser'>";


		if (what == 'brand') {
			var mode = showphones ? 'compatible' : 'brand' ;
			html += "<div class='brand' onclick=\"expand('" + mode + "','" + obj[0] + "')\" style=\"background-image: url('/img/foto/marchi/medium/" + obj[0] + ".png')\"></div>";
			//html += "<div class='brand'><img src=/img/foto/marchi/medium/" + obj[0] + ".png></div>";

			if (showphones) {
				html += "<div class='model' style='display: none;'></div>";
			}

			if (obj.length > 2) {
				html += "<div class='banner' onclick=\"expand('" + mode + "','" + obj[0] + "')\" style=\"background-image: url('/img/" + obj[2] + "')\"></div>";
				html += "<div class='sensible overlay' onclick=\"expand('" + mode + "','" + obj[0] + "')\"></div>"
			}
			else {
				html += "<div class='banner' onclick=\"expand('" + mode + "','" + obj[0] + "')\"></div>";
				html += "<div class='sensible' onclick=\"expand('" + mode + "','" + obj[0] + "')\"></div>"
			}
		}
		else {
			html += "<div class='category' onclick=\"expand('category','" + obj[0] + "')\">" + obj[1] + "</div>";
			html += "<div class='sensible' onclick=\"expand('category','" + obj[0] + "')\"></div>"
		}

		html += "</div>"; // collapser

		if (what != 'brand' || !showphones) {
			html += "<div class='filters'></div>";
		}

		html += "<div class='paging'></div>";

		if (what == 'brand' && showphones) {
			html += "<div class='thumbs' style='display:none;'></div>";
 		}

		html += "<div class='results'></div>";
		html += "<div class='paging'></div>";

		html += "</div>"; // collapsable
	}

	$('#rside').html(html);

	if (autoload != undefined) {
		expand(what, autoload);
	}

	if (what == 'brand') {
		$('#type_marca').addClass('selected');
		$('#type_categoria').removeClass('selected');
	}
	else {
		$('#type_marca').removeClass('selected');
		$('#type_categoria').addClass('selected');	
	}
}


// -------------------------------------------------------------------------------------------------
function bbq_pushState(dict) {
	if (hashencrypt) {
		$.bbq.pushState({state: encrypt(jQuery.param.querystring('', dict))}, 2);
	}
	else {
		$.bbq.pushState(dict, 2);
	}
}


// -------------------------------------------------------------------------------------------------
function bbq_params() {
	var p = $.deparam.fragment(true)

	if ('state' in p) {
		return $.deparam.fragment(decrypt(p['state']).slice(1), true);
	}

	if ('cmd' in p) {
		return p
	}

	return {cmd: 'none'};
}


// -------------------------------------------------------------------------------------------------
function init_bbq() {
	$(window).bind("hashchange", function(e) {

		var params = bbq_params();

		if (params['cmd'] == 'expand') {
			// force expansion
			if (params['id'] != '') {
				$('#' + params['id'] + ' .paging').html('');
				$('#' + params['id']).addClass('collapsed');
			}

			bbq_expand(params['what'], params['id']);
		}

		else if (params['cmd'] == 'update_product_list') {
			// expand if needed (but don't collapse otherwise)
			if ($('#'+params['id']).hasClass('collapsed')) {
				bbq_expand(params['what'], params['id']);
			}

			set_selected_model(params['id'], params['barcode']);
			bbq_update_product_list(params['what'], params['id']);
		}
	});
}


// ---------------------------------------------------------------------------
hexvalues = '0123456789ABCDEF';

function hex(value) {
	return hexvalues[Math.floor(value/16)] + hexvalues[value%16];
}


// ---------------------------------------------------------------------------
function encrypt(plaintext) {
	var ascii = Math.floor(Math.random() * 256);
	var encrypted = hex(ascii);

	for (var idx in plaintext) {
		ascii = (plaintext.charCodeAt(idx) + ascii) % 256;
		encrypted += hex(ascii)
	}

	return encrypted;
}


// ---------------------------------------------------------------------------
function dec(h, l) {
	var v = 16 * hexvalues.indexOf(h) + hexvalues.indexOf(l);
	return v;
}


// ---------------------------------------------------------------------------
function decrypt(encrypted) {
	var seed = dec(encrypted[0], encrypted[1]);
	var len = encrypted.length;
	plain = '';

	for (var idx=2; idx<len; idx +=2) {
		var v = dec(encrypted[idx], encrypted[idx+1])
		plain += String.fromCharCode((v - seed + 256) %256)
		seed = v;
	}

	return plain;
}


// -------------------------------------------------------------------------------------------------
function load_telefoni()
{
	$.ajax({
		url: $("#appserver").val(),
		async: false,
		data: {
			tok: 'ck_load_tel_marca',
			sid: $("#sid").val(),
			id_marca: $('#id_marca').val()
		},
		success: function(data) {
			var buf = data;

			pop_telefoni = document.getElementById("id_telefono");
			pop_len = pop_telefoni.length;
			for (i = 0; i < pop_len; i++) {
				pop_telefoni.options[pop_telefoni.length - 1] = null;
			}
			pop_telefoni.options[0] = new Option('', '');
			
			rows = buf.split('***');
			for (i = 0; i < rows.length; i++) {
				rec = rows[i].split('###');
				chiave = rec[0];
				valore = rec[1];
				pop_telefoni.options[pop_telefoni.length] = new Option(valore, chiave);
			}
		}
	});
}


// -------------------------------------------------------------------------------------------------
function news(buf)
{
	init_bbq(); // init jQuery back button handling

	var html = "<div id='breadcrumbs'>Novit&agrave;";
	html += "</div>";
	
	html += "<div class='collapsable collapsed' id='news_result'>";
	html += "<a id='bookmark_news_result' />";
	
	html += "<div class='filters'></div>";
	html += "<div class='paging'></div>";
	html += "<div class='results'></div>";
	html += "<div class='paging'></div>";
	
	$('#rside').html(html);
	
	$('#buffer').val(buf);
	
	expand('news','news_result');
}


// -------------------------------------------------------------------------------------------------
function promo(buf)
{
	var html = "<div id='breadcrumbs'>Promo";
	html += "</div>";
	
	html += "<div class='collapsable collapsed' id='promo_result'>";
	html += "<a id='bookmark_promo_result' />";
	
	html += "<div class='filters'></div>";
	html += "<div class='paging'></div>";
	html += "<div class='results'></div>";
	html += "<div class='paging'></div>";
	
	$('#rside').html(html);
	
	$('#buffer').val(buf);
	
	expand('promo','promo_result');
}


// -------------------------------------------------------------------------------------------------
function consigliati(buf)
{
	init_bbq(); // init jQuery back button handling

	var html = "<div id='breadcrumbs'>Consigliati";
	html += "</div>";
	
	html += "<div class='collapsable collapsed' id='cons_result'>";
	html += "<a id='bookmark_cons_result' />";
	
	html += "<div class='filters'></div>";
	html += "<div class='paging'></div>";
	html += "<div class='results'></div>";
	html += "<div class='paging'></div>";
	
	$('#rside').html(html);

	$('#buffer').val(buf);

	expand('cons','cons_result');
}


// -------------------------------------------------------------------------------------------------
function clean_field(field)
{
	if (field.value in {'ricerca libera': '', 'username': '', 'password': ''}) {
		field.value = '';
	}
}


// -------------------------------------------------------------------------------------------------
function clean_field_pwd(field)
{
	var input = document.getElementById('password');
	var input2 = input.cloneNode(false);
	input2.type = 'password';
	input.parentNode.replaceChild(input2, input);
	document.getElementById('password').value = '';
}


// -------------------------------------------------------------------------------------------------
function upd_item(id_articolo)
{
	$.ajax({
		url: $("#appserver").val(),
		async: false,
		data: {
			tok: 'ck_upd_item',
			sid: $("#sid").val(),
			id_articolo: id_articolo,
			quantita: $("#QTY" + id_articolo).val()
		},
		success: function(data) {
			var response = jQuery.parseJSON(data);
			var cart_value = response[0];
			$('#tot').html('tot &euro; ' + cart_value);
			$('#number').html(cart_value + " &euro;");
			$('#rside').html(response[1]);
		}
	});
}


// -------------------------------------------------------------------------------------------------
function del_item(id_articolo)
{
	if (confirm("Confermi rimozione dell'articolo?")) {
		$.ajax({
			url: $("#appserver").val(),
			async: false,
			data: {
				tok: 'ck_del_item',
				sid: $("#sid").val(),
				id_articolo: id_articolo,
				quantita: $("#QTY" + id_articolo).val()
			},
			success: function(data) {
				var response = jQuery.parseJSON(data);
				var cart_value = response[0];
				$('#tot').html('tot &euro; ' + cart_value);
				$('#number').html(cart_value + " &euro;");
				$('#rside').html(response[1]);
			}
		});
	}
}


// -------------------------------------------------------------------------------------------------
function show_order(id_ordine)
{
	$.ajax({
		url: $("#appserver").val(),
		async: false,
		data: {
			tok: 'ck_show_order',
			sid: $("#sid").val(),
			id_ord_storico: id_ordine
		},
		success: function(data) {
			var buf = data;
			$('#rside').html(buf);
		}
	});
}


// -------------------------------------------------------------------------------------------------
function pwdFocus()
{
	$('#fakepassword').hide();
	$('#password').show();
	$('#password').focus();
}


// -------------------------------------------------------------------------------------------------
function pwdBlur()
{
	if ($('#password').attr('value') == '') {
		$('#password').hide();
		$('#fakepassword').show();
	}
}


// -------------------------------------------------------------------------------------------------
function save_note(id_ordine)
{
	var note = $("textarea#note").val();
	$.ajax({
		url: $("#appserver").val(),
		async: false,
		data: {
			tok: 'ck_save_note',
			sid: $("#sid").val(),
			id_ordine: id_ordine,
			note: note
		},
		success: function(data) {
			var buf = data;
		}
	});
}


// -------------------------------------------------------------------------------------------------
function add_item(pard_js)
{
	$.ajax({
		url: $("#appserver").val(),
		async: false,
		data: {
			tok: 'ck_add_item',
			sid: $("#sid").val(),
			quantita: $("#" + pard_js.quantita).val(),
			id_articolo: escape(pard_js.id_articolo),
			id_cliente: escape(pard_js.id_cliente),
			status: escape(pard_js.status)
		},
		success: function(data) {
			var response = jQuery.parseJSON(data);

			var cart_value = response[0];
			var qty = response[1];

			// update cart's totale
			$('#tot').html('tot &euro; ' + cart_value);
		}
	});
}


// -------------------------------------------------------------------------------------------------
function add_item2(pard_js)
{
	$.ajax({
		url: $("#appserver").val(),
		async: false,
		data: {
			tok: 'ck_add_item2',
			sid: $("#sid").val(),
			quantita: $("#" + pard_js.quantita).val(),
			quantita_oma: $("#" + pard_js.quantita_oma).val(),
			id_articolo: escape(pard_js.id_articolo),
			id_articolo_oma: escape(pard_js.id_articolo_oma),
			id_cliente: escape(pard_js.id_cliente),
			status: escape(pard_js.status)
		},
		success: function(data) {
			var response = jQuery.parseJSON(data);

			var cart_value = response[0];
			var qty = response[1];

			// update cart's totale
			$('#tot').html('tot &euro; ' + cart_value);
		}
	});
}


// -------------------------------------------------------------------------------------------------
function invia_ordine()
{
	var note = $("textarea#note").val();
	$.ajax({
		url: $("#appserver").val(),
		async: false,
		data: {
			tok: 'ck_invia',
			sid: $("#sid").val(),
			id_cliente: $("#id_cliente").val(),
			note: note
		},
		success: function(data) {
			$('#rside').html(data);

			// update cart's totale
			$('#tot').html('tot &euro; 0,00');
		}
	});
}


// -------------------------------------------------------------------------------------------------
function send_request()
{
	if ($("#email").val() &&  $("textarea#richiesta").val()) {
		$.ajax({
			url: $("#appserver").val(),
			async: false,
			data: {
				tok: 'ck_send_request',
				sid: $("#sid").val(),
				id_cliente: $("#id_cliente").val(),
				email: $("#email").val(),
				modello: $("#modello").val(),
				richiesta: $("textarea#richiesta").val()
			},
			success: function(data) {
				alert("La tua richiesta e' stata inviata con successo. Riceverai una risposta quanto prima dal nostro staff.");
				$("#email").val('');
				$("#modello").val('');
				$("#richiesta").val('');
			}
		});
	}
	else {
		alert('Indica il tuo indirizzo email e inserisci un commento');
	}
}


// -------------------------------------------------------------------------------------------------
function check_registrazione()
{
	var flag = 'OK';
	if ($("#nome").val() == '') {
		$("#chk_nome").css('color', 'red');
		flag = 'KO';
	}
	if ($("#cognome").val() == '') {
		$("#chk_cognome").css('color', 'red');
		flag = 'KO';
	}
	if ($("#ragione_sociale").val() == '') {
		$("#chk_ragione_sociale").css('color', 'red');
		flag = 'KO';
	}
	if ($("#localita").val() == '') {
		$("#chk_localita").css('color', 'red');
		flag = 'KO';
	}
	if ($("#provincia").val() == '') {
		$("#chk_provincia").css('color', 'red');
		flag = 'KO';
	}
	if ($("#id_nazione").val() == '') {
		$("#chk_id_nazione").css('color', 'red');
		flag = 'KO';
	}
	if ($("#email").val() == '') {
		$("#chk_email").css('color', 'red');
		flag = 'KO';
	}
	if ($("#telefono").val() == '') {
		$("#chk_telefono").css('color', 'red');
		flag = 'KO';
	}
	if ($("#indirizzo").val() == '') {
		$("#chk_indirizzo").css('color', 'red');
		flag = 'KO';
	}
	if ($("#cap").val() == '') {
		$("#chk_cap").css('color', 'red');
		flag = 'KO';
	}
	if ($("#partita_iva").val() == '') {
		$("#chk_partita_iva").css('color', 'red');
		flag = 'KO';
	}
	if ($("#codice_fiscale").val() == '') {
		$("#chk_codice_fiscale").css('color', 'red');
		flag = 'KO';
	}
	if ($("#attivita").val() == '') {
		$("#chk_attivita").css('color', 'red');
		flag = 'KO';
	}
	if (!$("#condizioni").attr('checked')) {
		$("#chk_condizioni").css('color', 'red');
		flag = 'KO';
	}
	if (!$("#registrazione_si").attr('checked') && !$("#registrazione_no").attr('checked')) {
		$("#chk_registrazione").css('color', 'red');
		flag = 'KO';
	}
	if (!$("#newsletter_si").attr('checked') && !$("#newsletter_no").attr('checked')) {
		$("#chk_newsletter").css('color', 'red');
		flag = 'KO';
	}
	if (flag == 'OK') {
		$("tok").val("ck_registra");
		document.forms.registrazione.submit();
	}
}

