/**************************** Common JS Globals vars ****************************/
var jsonRoot;

var gSiteId;
var basePath;
	
var product_type;
var product_brand;
var product_funct;
var product_evidence;

var isListPage = false;

var listProductFilename = 'ricerca-prodotti';
var listResultfileName = 'prodotti';

/**************************** Common JS functions ****************************/
/**
 * PageQuery()
 * 
 * prepara la funzione classe per il parsing della querystring
 * @param q location url
 */
function PageQuery(q) {
	if(q.length > 1) this.q = q.substring(1, q.length);
	else this.q = null;
	this.keyValuePairs = new Array();
	if(q) {
		for(var i=0; i < this.q.split("&").length; i++) {
			this.keyValuePairs[i] = this.q.split("&")[i];
		}
	}
	this.getKeyValuePairs = function() { 
		return this.keyValuePairs; 
	};
	this.getValue = function(s) {
		for(var j=0; j < this.keyValuePairs.length; j++) {
			if(this.keyValuePairs[j].split("=")[0] == s) {
				return this.keyValuePairs[j].split("=")[1];
			}
		}
		return false;
	};

	this.getParameters = function(s) {
		var a = new Array();
		for(var j=0; j < this.keyValuePairs.length; j++) {
			if(this.keyValuePairs[j].split("=")[0] == s) {
				a[a.length] = this.keyValuePairs[j].split("=")[1];
			}
		}
		return a;
	};
	this.getLength = function() { 
		return this.keyValuePairs.length; 
	};
}
/**
 * queryString()
 * 
 * estrae la key dalla querystring
 * @param key
 * @return key value or '' 
 */
function queryString(key){
	var page = new PageQuery(window.location.search);
	if (page.getValue(key) == false) 
		return '';
	else 
		return unescape(page.getValue(key));
}

function queryString(key, querystring) {
	var page = new PageQuery(querystring);
	if (page.getValue(key) == false) 
		return '';
	else 
		return unescape(page.getValue(key));
}
/**
 * ritorna l'array
  */
function queryStringArray(key){
	var page = new PageQuery(window.location.search);
	return (page.getParameters(key));
}
function queryStringArray(key, querystring){
	var page = new PageQuery(querystring);
	return (page.getParameters(key));
}

/**
* getPageSize() by quirksmode.com
*
* @return Array Return an array with page width, height and window width, height
*/
function _getPageSize() {
	var xScroll, yScroll;
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return arrayPageSize;
};
/**
 * getPageScroll() by quirksmode.com
 *
 * @return Array Return an array with x,y page scroll values.
 */
function _getPageScroll() {
	var xScroll, yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}
	arrayPageScroll = new Array(xScroll,yScroll);
	return arrayPageScroll;
};
/**
 * emailCheck()
 * 
 * verifica se e' una email valida
 * @param emailStr email address
 * @return true se la email e' ok altrimenti false
 */
function emailCheck (emailStr) {
	/* The following pattern is used to check if the entered e-mail address
	   fits the user@domain format.  It also is used to separate the username
	   from the domain. */
	var emailPat=/^(.+)@(.+)$/
	/* The following string represents the pattern for matching all special
	   characters.  We don't want to allow special characters in the address. 
	   These characters include ( ) < > @ , ; : \ " . [ ]    */
	var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
	/* The following string represents the range of characters allowed in a 
	   username or domainname.  It really states which chars aren't allowed. */
	var validChars="\[^\\s" + specialChars + "\]"
	/* The following pattern applies if the "user" is a quoted string (in
	   which case, there are no rules about which characters are allowed
	   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
	   is a legal e-mail address. */
	var quotedUser="(\"[^\"]*\")"
	/* The following pattern applies for domains that are IP addresses,
	   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
	   e-mail address. NOTE: The square brackets are required. */
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
	/* The following string represents an atom (basically a series of
	   non-special characters.) */
	var atom=validChars + '+'
	/* The following string represents one word in the typical username.
	   For example, in john.doe@somewhere.com, john and doe are words.
	   Basically, a word is either an atom or quoted string. */
	var word="(" + atom + "|" + quotedUser + ")"
	// The following pattern describes the structure of the user
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
	/* The following pattern describes the structure of a normal symbolic
	   domain, as opposed to ipDomainPat, shown above. */
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


	/* Finally, let's start trying to figure out if the supplied address is
	   valid. */

	/* Begin with the coarse pattern to simply break up user@domain into
	   different pieces that are easy to analyze. */
	var matchArray=emailStr.match(emailPat)
	if (matchArray==null) {
	  /* Too many/few @'s or something; basically, this address doesn't
	     even fit the general mould of a valid e-mail address. */
//		alert("Email address seems incorrect (check @ and .'s)")
		return false
	}
	var user=matchArray[1]
	var domain=matchArray[2]

	// See if "user" is valid 
	if (user.match(userPat)==null) {
	    // user is not valid
//	    alert("The username doesn't seem to be valid.")
	    return false
	}

	/* if the e-mail address is at an IP address (as opposed to a symbolic
	   host name) make sure the IP address is valid. */
	var IPArray=domain.match(ipDomainPat)
	if (IPArray!=null) {
	    // this is an IP address
		  for (var i=1;i<=4;i++) {
		    if (IPArray[i]>255) {
//		        alert("Destination IP address is invalid!")
			return false
		    }
	    }
	    return true
	}

	// Domain is symbolic name
	var domainArray=domain.match(domainPat)
	if (domainArray==null) {
//		alert("The domain name doesn't seem to be valid.")
	    return false
	}

	/* domain name seems valid, but now make sure that it ends in a
	   three-letter word (like com, edu, gov) or a two-letter word,
	   representing country (uk, nl), and that there's a hostname preceding 
	   the domain or country. */

	/* Now we need to break up the domain to get a count of how many atoms
	   it consists of. */
	var atomPat=new RegExp(atom,"g")
	var domArr=domain.match(atomPat)
	var len=domArr.length
	if (domArr[domArr.length-1].length<2 || 
	    domArr[domArr.length-1].length>3) {
	   // the address must end in a two letter or three letter word.
	//   alert("The address must end in a three-letter domain, or two letter country.")
	   return false
	}

	// Make sure there's a host name preceding the domain.
	if (len<2) {
	   var errStr="This address is missing a hostname!"
	//   alert(errStr)
	   return false
	}

	// If we've gotten this far, everything's valid!
	return true;
}
	//  End -->

/**
 * validTextObjectField()
 * 
 * verifica se un campo input di testo abbia testo non nullo
 * @param id  DOM id del campo input html che contiene testo da validare
 * @return true se non nullo
 */
function validTextObjectField(id) {
	var obj = document.getElementById(id);
	if (obj.value != "" || obj.value != undefined || obj.value != null) {
		return true;
	}
	return false;
}
/**
 * validTextField()
 * 
 * verifica se un campo input di testo abbia testo non nullo
 * @return true se non nullo
 */
function validTextField(string) {
	string = jQuery.trim(string);
	if (string != "" && string != undefined && string != null) {
		return true;
	}
	return false;
}

/**
 * If the string is a true number, returns true otherwise false
 * @param sText number in string form
 * @return true is a number
 */
function IsNumeric(sText) {
	var ValidChars = "0123456789.";
	var IsNumber=true;
	var Char;
	
	for (i = 0; i < sText.length && IsNumber == true; i++) { 
		Char = sText.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) {
			IsNumber = false;
		}
	}
   return IsNumber;
}

jQuery.fn.checkInArray = function(t) {
	if (this.lenght = 0) return false;
	var arr = this;
	var len = arr.length;
	var resOk = 0;
	for( i = 0; i <len; i++) {
		var item = arr[i];
		var idx = $.inArray( item, t );
		if ( idx != -1) {
			resOk++;
		}
	}
	if ( resOk == len) {
		return true;
	}
	else {
		return false;
	}
}

/*******************************************************************************************************/
var _elencoProdotti = new Array();

/**
 * show product list grouped by type
 */
function showList() {
if ($('#js_List_Product').length > 0){

	$('#js_List_Product').empty();

	_elencoProdotti = new Array();

	var html = getHtml_prodottiP(jsonRoot.prodotti);
	
	$('#js_List_Product').append(html);
	}
}

function showListInEvidenza() {
if ($('#js_List_Product').length > 0){
	$('#js_List_Product').empty();

	_elencoProdotti = new Array();
	var prodotti = search_prodotti_in_evidenza();
	var html = getHtml_prodottiP(prodotti);
	
	$('#js_List_Product').append(html);
	}
}

function showList_filter(tipo, marca, funzioni){
if ($('#js_List_Product').length > 0){
	$('#js_List_Product').empty();
	_elencoProdotti = new Array();
	var html = getHtml_prodotti_filter(tipo, marca, funzioni);	
	$('#js_List_Product').append(html);
	}
}

function showListInEvidenza_filter(tipo, marca, funzioni){
if ($('#js_List_Product').length > 0){
	$('#js_List_Product').empty();
	_elencoProdotti = new Array();
	var html = getHtml_prodottiInEvidenza_filter(tipo, marca, funzioni);	
	$('#js_List_Product').append(html);
	}
}

function getHtml_prodotti_filter(tipo, marca, funzioni) {
	var tipi = jsonRoot.tipo
	var html = '';
	var len = tipi.length; 
	if ((len > 0) || (tipo != 'false')) {
		html += '<ul class="list_Products js_sIFR_List_Products">';
		if (tipo != '') {
			var prodotti;
			prodotti = search_prodotti_by_funzioni_marca_tipo(funzioni, marca, tipo)
			html += getHtml_prodotti(prodotti,true,true);
		}
		else {
			for (var i=0; i<len; i++) {
				var tipoItem = tipi[i];
				var startList = false;
				var endList = false;
				if (i == 0) startList = true;
				if(i == (len-1)) endList = true;
				
				if (tipoItem.hidden) continue;
				
				var prodotti;
				prodotti = search_prodotti_by_funzioni_marca_tipo(funzioni, marca, tipoItem.id)
				html += getHtml_prodotti(prodotti,startList,endList);
			}
		}
		html += '<li class="li_Separator">';
		html += '<a href="#topPage" class="link_BackToTop" title="Torna all\'inizio della pagina">torna al top della pagina</a>';
		html += '</li>';

		html += '</ul>';
	}
	return html;
}

function getHtml_prodottiInEvidenza_filter(tipo, marca, funzioni) {
	var tipi = jsonRoot.tipo
	var html = '';
	var len = tipi.length; 
	if ((len > 0) || (tipo != 'false')) {
		html += '<ul class="list_Products js_sIFR_List_Products">';
		if (tipo != '') {
			var prodotti;
			var result = [];
			prodotti = search_prodotti_by_funzioni_marca_tipo(funzioni, marca, tipo)
			for (var i=0, len=prodotti.length; i<len; i++) {
				var prodotto = prodotti[i];
				if(prodotto.evidence == 'true') {
					result[result.length] = prodotto;
				}
			}
			html += getHtml_prodotti(result,true,true);
		}
		else {
			for (var i=0; i<len; i++) {
				var tipoItem = tipi[i];
				var startList = false;
				var endList = false;
				if (i == 0) startList = true;
				if(i == (len-1)) endList = true;
				
				if (tipoItem.hidden) continue;
				
				var prodotti;
				var result = [];
				prodotti = search_prodotti_by_funzioni_marca_tipo(funzioni, marca, tipoItem.id)
				for (var i=0, len=prodotti.length; i<len; i++) {
					var prodotto = prodotti[i];
					if(prodotto.evidence == 'true') {
						result[result.length] = prodotto;
					}
				}
				html += getHtml_prodotti(prodotti,startList,endList);
			}
		}
		html += '<li class="li_Separator">';
		html += '<a href="#topPage" class="link_BackToTop" title="Torna all\'inizio della pagina">torna al top della pagina</a>';
		html += '</li>';

		html += '</ul>';
	}
	return html;
}

function getHtml_prodottiTipo(tipi) {
	var html = '';
	var len = tipi.length; 
	if (len > 0) {
		html += '<ul class="list_Products js_sIFR_List_Products">';
		
		for (var i=0; i<len; i++) {
			var tipo = tipi[i];
			var startList = false;
			var endList = false;
			if (i == 0) startList = true;
			if(i == (len-1)) endList = true;
			
			if (tipo.hidden) continue;
			
			var prodotti = search_prodotti_by_tipo(tipo.id);
			html += getHtml_prodotti(prodotti,startList,endList);
		}
		html += '<li class="li_Separator">';
		html += '<a href="#topPage" class="link_BackToTop" title="Torna all\'inizio della pagina">torna al top della pagina</a>';
		html += '</li>';

		html += '</ul>';
	}
	return html;
}

function getHtml_prodottiP(prodotti) {
	var html = '';
	var len = prodotti.length; 
	if (len > 0) {
		html += '<ul class="list_Products js_sIFR_List_Products">';
		
		html += getHtml_prodotti(prodotti,true,true);
		
		html += '<li class="li_Separator">';
		html += '<a href="#topPage" class="link_BackToTop" title="Torna all\'inizio della pagina">torna al top della pagina</a>';
		html += '</li>';

		html += '</ul>';
	}
	return html;
}

/**
 * get html for product
  */
 function getHtml_prodotti(prodotti, start, end) {
	var html = '';
	var len = prodotti.length; 
	if (len > 0) {
		for (var i = 0; i<len; i++) {
			var prodotto = prodotti[i];

			if (prodotto.hidden) continue;
			
			var css_List = '';
			if ((i == 0) && start) {
				css_List = 'class="li_First"';
			}
			else if ((i == (len - 1)) && end) {
				css_List = 'class="li_Last"';
			}
			
			html += '<li id="' + prodotto.id + '" '+ css_List +'>';
			
			if (prodotto.promo == 'PromoImgDefault')
			{
	
			html += '<div class="ico_Promo"><img src="../res/imgs/ico_Promo_small_Alpha.png" alt="Promo" title="Promo"/></div>'
			}else if(prodotto.promo == 'PromoImgUpload'){
			html += '<div class="ico_Promo"><img src="'+prodotto.imgPromozione+'" alt="Promo" title="Promo"/></div>'
			}else if (prodotto.status == 'nuovo') {
				html += '<div class="ico_Novita">Novit&agrave;</div>'
			}
			html += '<div class="box_Img">';
			html += '<a href="'+ prodotto.url +'" title="'+ prodotto.title +'">';
			html += '<img src="'+ prodotto.image +'" alt="'+ prodotto.title +'" />';
			html += '</a>';
			html += '</div>';
			html += '<div class="box_Description">';
			html += '<h2 class="tit_Title">';
			html += '<span><a href="'+ prodotto.url +'" title="'+ prodotto.title +'">';
			html += prodotto.title;
			html += '</a></span>';
			html += '</h2>';
			html += '<div class="txt_Paragraph">';
			html += prodotto.description;
			html += '</div>';
			html += '<a href="'+ prodotto.url +'" class="link_Dettaglio" title="Vai alla scheda del prodotto">dettaglio</a><br />';
			html += '<div class="box_Check">';
			//html += '<div id="uniform-" class="checker"><span>';
			var strBase = 'prodotto_';
			var stPos = strBase.length;
			html += '<input onclick="confronta()" type="checkbox" class="js_ChkProdotto" id="chk_' + prodotto.id + '" name="chk_' + prodotto.id + '" value="' + prodotto.id.substr(stPos) +'" />';
			//html += '</span></div>';
			html += '</div>';
			html += '<label class="js_confronta" for="chk_' + prodotto.id + '" id="chk_' + prodotto.id.substr(stPos)+ '">confronta</label>';
			html += '</div>';
			html += '</li>';
		}
		
		
	}
	return html;
}



function getHtmlListMarchi(tipo) {
	var html = '';
	
	html += '<option value="">Tutto</option>';
	var result = [];
	var marchi = jsonRoot.marca;
	for (var i=0, len=marchi.length; i<len; i++) {
		var marca = marchi[i];
		var idx = $.inArray( tipo, marca.tipo );
		if (idx != -1) {
			result[result.length] = marca;
		}
	}
	var len = result.length; 
	if (len > 0) {
		for (var i = 0; i<len; i++) {
			var marca = result[i];
			if (marca.hidden) continue;
			html += '<option value="'+ marca.id +'">'+ marca.title +'</option>';
		}
	}
	return html;
}

function filterBy(type, field, value) {
	var records = jsonRoot[type];
	for (var i=0, len=records.length; i<len; i++) {
		var record = records[i];
		if (value.length == 0) {
			record.hidden = false;		
		}
		else {
			var prop = record[field];
			var found = (typeof prop == "string" && prop == value) || (jQuery.isArray(prop) && jQuery.inArray(value, prop) != -1);
			record.hidden = !found;
		}
	}

	//showList();
}

function search_prodotti_by_tipo(tipo) {
	var result = [];
	var prodotti = jsonRoot.prodotti;
	for (var i=0, len=prodotti.length; i<len; i++) {
		var prodotto = prodotti[i];
		var idx = $.inArray( tipo, prodotto.tipo );
		if (idx != -1) {
			result[result.length] = prodotto;
		}
	}
	return result;
}

function search_prodotti_in_evidenza_by_tipo(tipo) {
	var result = [];
	var prodotti = jsonRoot.prodotti;
	for (var i=0, len=prodotti.length; i<len; i++) {
		var prodotto = prodotti[i];
		var idx = $.inArray( tipo, prodotto.tipo );
		if (idx != -1) {
			if(prodotto.evidence == 'true') {
				result[result.length] = prodotto;
			}
		}
	}
	return result;
}

function search_prodotti_in_evidenza() {
	var result = [];
	var prodotti = jsonRoot.prodotti;
	for (var i=0, len=prodotti.length; i<len; i++) {
		var prodotto = prodotti[i];
		if(prodotto.evidence == 'true') {
			result[result.length] = prodotto;
		}
	}
	return result;
}

function search_prodotti_by_marca_tipo(marca, tipo) {
	var result = [];
	var prodotti = jsonRoot.prodotti;
	for (var i=0, len=prodotti.length; i<len; i++) {
		var prodotto = prodotti[i];
		var idx = $.inArray( tipo, prodotto.tipo );
		var id2x = $.inArray( marca, prodotto.marca );
		if ((idx != -1) && (id2x != -1)) {
			result[result.length] = prodotto;
		}
	}
	return result;
}

function search_prodotti_by_funzioni_tipo(funzioni, tipo) {
	var result = [];
	var prodotti = jsonRoot.prodotti;
	for (var i=0, len=prodotti.length; i<len; i++) {
		var prodotto = prodotti[i];
		var idx = $.inArray( tipo, prodotto.tipo );
		var id2x = $.inArray( funzioni, prodotto.funzioni );
		if ((idx != -1) && (id2x != -1)) {
			result[result.length] = prodotto;
		}
	}
	return result;
}

function search_prodotti_by_funzioni_marca_tipo(funzioni, marca, tipo) {
	var result = [];
	var prodotti = jsonRoot.prodotti;
	for (var i=0, len=prodotti.length; i<len; i++) {
		var prodotto = prodotti[i];
		var idx = $.inArray( tipo, prodotto.tipo );
		var id2x = $.inArray( marca, prodotto.marca );
		
		if ( (tipo != '') && (marca != '') && (funzioni.length > 0)) { 
			var ex = $(funzioni).checkInArray(prodotto.funzioni);
			if ((idx != -1) && (id2x != -1) && (ex)) {
				result[result.length] = prodotto;
			}
		}
		else if ( (tipo != '') && (marca != '') && (funzioni.length == 0)) { 
			if ((idx != -1) && (id2x != -1) ) {
				result[result.length] = prodotto;
			}
		}
		else if ( (tipo != '') && (marca == '') && (funzioni.length > 0)) { 
			var ex = $(funzioni).checkInArray(prodotto.funzioni);
			if ((idx != -1) && (ex)) {
				result[result.length] = prodotto;
			}
		}
		else if ( (tipo != '') && (marca == '') && (funzioni.length == 0)) { 
			if (idx != -1) {
				result[result.length] = prodotto;
			}
		}
	}
	return result;
}

function getTypeByProductId(id) {
	var result = [];
	var prodotti = jsonRoot.prodotti;
	
	var tipi = jsonRoot.tipi;
	var tipo = '';
	
	for (var i=0, len=prodotti.length; i<len; i++) {
		var prodotto = prodotti[i];
		if (prodotto.id == id) {
			tipo = prodotto.tipo;
		}
	}
	
	return tipo;
}

/*******************************************************************************************************/
function frmDlgSearch() {
	var retVal = false;
	var dataStr = '?'
	var product_type = $('#frm_SearchProductType input#t').val();
	var product_brand = $('#frm_SearchProductType select#m').val();
	if (product_type != '') {
		dataStr += 't='+product_type;
	}
	if (product_brand != '') {
		dataStr +='&m='+product_brand;
	}
	var product_funct = new Array();
	$('#frm_SearchProductType input[name=f]:checked').each(function() {
		product_funct.push($(this).val());
		dataStr +='&f=' +$(this).val();
	});
	
	if (isListPage) {
		retval = false;
	}
	else {
		$('#dlgSearch').fadeOut('slow', function() {
			$('select').show();
			$.uniform.update();
			$('#dlgSearch').empty();
			location.href = listProductFilename + dataStr;
		}).css({'z-index': 1});	
		retval = true;
	}
	
	if (jsonRoot == undefined) {
		$.getJSON(basePath + 'include/json/prodotti.json', 
			function(data) { 
				jsonRoot = data; 
				
				showList_filter(product_type, product_brand, product_funct); 
				$("#js_List_Product input:checkbox").uniform({checkboxClass: 'checker'}); 
			} 
		);
	}
	else {
		showList_filter(product_type, product_brand, product_funct); 
		$("#js_List_Product input:checkbox").uniform({checkboxClass: 'checker'}); 
	}
	return retVal;
}
/*******************************************************************************************************/
function showDialogSearch(tipo) {
	
	$('select').hide();	
	$('#dlgSearch').load('include/dlgSearch_' + tipo+'.html',
		{},
		function() {			
			$('#dlgSearchButtonClose').click(function() {
				$('#dlgSearch').fadeOut('slow', function() {
					$('select').show();
					$.uniform.update();
					$('#dlgSearch').empty();
				}).css({'z-index': 1});	
				
			});
			$("#dlgSearch select, #dlgSearch input:checkbox").uniform({checkboxClass: 'checker'}); 
			$('#dlgSearch').fadeIn('slow').css({'z-index': 999});
		}
	);
	// end load();
}
/*******************************************************************************************************/
function OpenDialogOverlay(title, message) {
	$('#js_DialogTitle').text(title);
	$('#js_DialogText').html(message);
	$('#js_DialogOverlay').overlay({
		mask: {
			color: '#000000',
			loadSpeed: 200,
			opacity: 0.7
		},
		// disable this for modal dialog-type of overlays
		closeOnClick: false
	});	
	$('#js_DialogOverlay').overlay().load();
}
/*******************************************************************************************************/
function OpenDialogFOverlay(title, message) {
	$('#js_DialogFTitle').text(title);
	$('#js_DialogFText').html(message);
	$('#js_DialogFOverlay').overlay({
		mask: {
			color: '#000000',
			loadSpeed: 200,
			opacity: 0.7
		},
		// disable this for modal dialog-type of overlays
		closeOnClick: false
	});	
	$('#js_DialogFOverlay').overlay().load();
}
/*******************************************************************************************************/
function updateTitleList(code) {
	switch (code) {
		case 2:
			$('#js_TitleList').text('Lista Cellulari.');
			 updateBreadCrumb('Cellulari'); 
			break;
		case 3: 
			$('#js_TitleList').text('Lista PC.');
			updateBreadCrumb('PC');
			break;
		case 4:
			$('#js_TitleList').text('Lista Chiavette Internet.');
			updateBreadCrumb('Chiavette');
			break;
		default:
			updateBreadCrumb('');
			break;
	}
	return;
}
/*******************************************************************************************************/
function updateBreadCrumb(label) {
	if ( breadObj == undefined || breadObj ==  null) {
		return false;
	}
	var outStr = "";
	var len = breadObj.link.length;
	if (label == undefined || label == '') {
		for (var i = 0; i < len; i++) {
			var title = breadObj.link[i].title;
			if ( i == (len-1) ) {
				outStr += '<span>'+title+'</span>';
			}
			else {
				outStr += '<a href="' + breadObj.link[i].url + '" title="'+ title +'">'+ title +'</a>.';
			}
		}
	}
	else {
		for (var i = 0; i < len; i++) {
			var title = breadObj.link[i].title;
			outStr += '<a href="' + breadObj.link[i].url + '" title="'+ title +'">'+ title +'</a>.';
		}
		outStr += '<span>'+label+'</span>';
	}
	$('.box_Breadcrumb').html(outStr);
}
/*******************************************************************************************************/
// per form nascosto lista prodotti
function submitCompare() {
	var arrChecked = $('input.js_ChkProdotto[type=checkbox]:checked');
	var len = arrChecked.length;
	var prevtype;
	
	clearVars();
	if (len > 3) {
		alert("Puoi selezionare fino a 3 prodotti per il confronto.");
		return false;
	} 
	else if (len == 0) { 
		return false;
	}
	
	for ( var i = 0; i < len; i++) {
		var item = arrChecked[i];
		var value = item.value;
		$('input#id' + (i+1)).val(value);
		var type = getTypeByProductId('prodotto_' + value);
		if ( prevtype != null || prevtype != undefined) {
			if ( type[0] == prevtype[0]) {
				// nothing
			}
			else {
				alert("Non si possono confrontare tipologie diverse di prodotti");
				return false;
			}
		}
		prevtype = type;
	}
	//$('form#js_LstCompare').submit();
	document.forms["js_LstCompare"].submit();
}
function clearVars() {
	$('#id1').val('');
	$('#id2').val('');
	$('#id3').val('');
}

function confronta(){
	$('.lbl_Confronta').removeClass("lbl_Confronta");
	$('.lbl_Confronta').html("confronta");
	var arrChecked = $('input.js_ChkProdotto[type=checkbox]:checked');
	var len = arrChecked.length;
	if (len > 3) {
	alert("Puoi selezionare fino a 3 prodotti per il confronto.");
			$('.lbl_Confronta').removeClass("lbl_Confronta");
			return false;
	} 
	else if (len > 1) { 
		for ( var i = 0; i < len; i++) {
		var item = arrChecked[i];
		var value = item.value;
		$('#chk_'+value).addClass("lbl_Confronta");
		$('.lbl_Confronta').html("<a href='#' onclick='submitCompare()'>confronta</a>")
		}
	}
	else {
	$('.lbl_Confronta').removeClass("lbl_Confronta");
	}
	
} 	
/*******************************************************************************************************/
function setBoxOverlay() {
	$(".box_Sidebar a[rel]").overlay({
		mask: '#000000',
	//	effect: 'apple',
		onBeforeLoad: function() {
			// grab wrapper element inside content
			var wrap = this.getOverlay().find(".contentWrap");
			// load the page specified in the trigger
			wrap.load(this.getTrigger().attr("href"));
		},
		onLoad: function() {
			//initSifr();
		},
		onClose: function () {
			var wrap = this.getOverlay().find(".contentWrap");
			wrap.empty();
		}
	});
}
/*******************************************************************************************************/
// configuratore
// noda id div spalla dx: js_BoxConfiguratore

// reset configuratore
function resetConfig() {
	$.ajax({
		type: "GET",
		url: "/configuratore/reset.jsp",
		success: function(xml) {
			$('#js_BoxConfiguratore').load('/configuratore/configuratore.jsp', function() {
				setBoxOverlay();
			});
		},
		error: function() {
			return false;
		},
		dataType: "xml"
	});
}

// set prodotto
function setProdotto(idProdotto) {
	var dataString = '';
	dataString += 'sito=' + gSiteId;
	dataString += '&prodotto=' + idProdotto;

	$.ajax({
		type: "POST",
		url: "/configuratore/setconfiguratore.jsp",
		data: dataString,
		success: function(xml) {
			$(xml).find('info').each(function() {
				//$('#resultinfo').html("Inserimento ok");
			});
			$(xml).find('error').each(function() {
				var err = $(this).text();
				//$('#resultinfo').html("Errore: " + err);
				//alert(err);
				OpenDialogFOverlay('Configuratore', '<br/>' + err);
				return false;
			});
			$('#js_BoxConfiguratore').load('/configuratore/configuratore.jsp', function() {
				setBoxOverlay();
			});
		},
		error: function() {
			return false;
		},
		dataType: "xml"
	});
}

// set prodotto modalita
function setProdottoModalita(idProdotto, idModalita) {
	var dataString = '';
	dataString += 'sito=' + gSiteId;
	dataString += '&prodotto=' + idProdotto;
	dataString += '&modalita=' + idModalita;

	$.ajax({
		type: "POST",
		url: "/configuratore/setconfiguratore.jsp",
		data: dataString,
		success: function(xml) {
			$(xml).find('info').each(function() {
				//$('#resultinfo').html("Inserimento ok");
			});
			$(xml).find('error').each(function() {
				var err = $(this).text();
				//$('#resultinfo').html("Errore: " + err);
				//alert(err);
				OpenDialogFOverlay('Configuratore', '<br/>' + err);
				return false;
			});
			$('#js_BoxConfiguratore').load('/configuratore/configuratore.jsp', function() {
				setBoxOverlay();
			});
		},
		error: function() {
			return false;
		},
		dataType: "xml"
	});
}

// set tariffa
function setTariffa(idTariffa) {
	var dataString = '';
	dataString += 'sito=' + gSiteId;
	dataString += '&tariffa=' + idTariffa;

	$.ajax({
		type: "POST",
		url: "/configuratore/setconfiguratore.jsp",
		data: dataString,
		success: function(xml) {
			$(xml).find('info').each(function() {
				//$('#resultinfo').html("Inserimento ok");
			});
			$(xml).find('error').each(function() {
				var err = $(this).text();
				//$('#resultinfo').html("Errore: " + err);
				//alert(err);
				OpenDialogFOverlay('Configuratore', '<br/>' + err);
				return false;
			});
			$('#js_BoxConfiguratore').load('/configuratore/configuratore.jsp', function() {
				setBoxOverlay();
			});
		},
		error: function() {
			return false;
		},
		dataType: "xml"
	});
}

//set prodotto modalita
function setProdottoModalitaTariffa(idProdotto, idModalita, idTariffa) {
	var dataString = '';
	dataString += 'sito=' + gSiteId;
	dataString += '&prodotto=' + idProdotto;
	dataString += '&modalita=' + idModalita;
	dataString += '&tariffa=' + idTariffa;

	$.ajax({
		type: "POST",
		url: "/configuratore/setconfiguratore.jsp",
		data: dataString,
		success: function(xml) {
			$(xml).find('info').each(function() {
				//$('#resultinfo').html("Inserimento ok");
			});
			$(xml).find('error').each(function() {
				var err = $(this).text();
				//$('#resultinfo').html("Errore: " + err);
				//alert(err);
				OpenDialogFOverlay('Configuratore', '<br/>' + err);
				return false;
			});
			$('#js_BoxConfiguratore').load('/configuratore/configuratore.jsp', function() {
				setBoxOverlay();
			});
		},
		error: function() {
			return false;
		},
		dataType: "xml"
	});
}

// set opzione
function setOpzione(idOpzione) {
	var dataString = '';
	dataString += 'sito=' + gSiteId;
	dataString += '&opzione=' + idOpzione;

	$.ajax({
		type: "POST",
		url: "/configuratore/setconfiguratore.jsp",
		data: dataString,
		success: function(xml) {
			$(xml).find('info').each(function() {
				//$('#resultinfo').html("Inserimento ok");
			});
			$(xml).find('error').each(function() {
				var err = $(this).text();
				//$('#resultinfo').html("Errore: " + err);alert("Errore: " + err);
				//alert(err);
				OpenDialogFOverlay('Configuratore', '<br/>' + err);
				return false;
			});
			$('#js_BoxConfiguratore').load('/configuratore/configuratore.jsp', function() {
				setBoxOverlay();
			});
		},
		error: function() {
			return false;
		},
		dataType: "xml"
	});
}

/**
 * LoadScript per caricare un script js e lanciarlo innell'onload  - per popup da aprire all'onload senza essere bloccatid al blocker dei browser 
 */
function loadScript(url, callback){
	var script = document.createElement("script");
	script.type = "text/javascript";
	if (script.readyState){  //IE
		script.onreadystatechange = function(){
			if (script.readyState == "loaded" || script.readyState == "complete"){
				script.onreadystatechange = null;
				callback();
			}
		};
	} else {  //Others
		script.onload = function(){
			callback();
		};
	}
	script.src = url;
	document.body.appendChild(script);
}

/*******************************************************************************************************/
