/* _____________________________ ON ERROR ____________________________________________ */
function silenzia()  {return true}
// window.onerror=silenzia;
/* ___________________________________________________________________________________ */

function URLDecode (encodedString) {
  var output = encodedString;
  var binVal, thisString;
  var myregexp = /(%[^%]{2})/;
  while ((match = myregexp.exec(output)) != null
             && match.length > 1
             && match[1] != '') {
    binVal = parseInt(match[1].substr(1),16);
    thisString = String.fromCharCode(binVal);
    output = output.replace(match[1], thisString);
  }
  return output;
}

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]
};

function isIE(){
	return($.browser.msie);
}

function getNomeBrowser(){
	var tipo="";
	var contatore=0;
	$.each($.browser, function(i, val){
		contatore++;
		if(contatore==1){
			tipo=i;
		}
	});
	return(tipo);
}

function objFromId(id_elemento) {
	return ($("#id_elemento"));
}

function getFlashObj(idObj){
	var obj=(isIE())? eval("window."+idObj) : eval("window.document."+idObj);
	return(obj);
}

function debJsObj(oggetto, testoDeb, livelloObj){
	if(oggetto.length>0){
		for(var prop in oggetto){
			if(oggetto[prop] && (oggetto[prop].toString()=="[object]" || oggetto[prop].toString()=="[object Text]")){
				testoDeb+="["+prop+"] Object:<br />";
				testoDeb+=debJsObj(oggetto[prop], testoDeb, (livelloObj+1));
			} else {
				for(i=0;i<livelloObj;i++){
					testoDeb+="> ";
				}
				testoDeb+="["+prop+"]="+ oggetto[prop]+"<br />";
			}
		}
	}
	return(testoDeb);
}

/////////////// FUNZIONE PER RIMUOVERE ELEMENTI DA UN ARRAY
Array.remove = function(array, from, to) {
  var rest = array.slice((to || from) + 1 || array.length);
  array.length = from < 0 ? array.length + from : from;
  return array.push.apply(array, rest);
};

/////////////// FUNZIONE IN_ARRAY
function in_array(needle, haystack, argStrict) {
    var key = '', strict = !!argStrict;
    if (strict) {
        for (key in haystack) {
            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (haystack[key] == needle) {
                return true;
            }
        }
    }
    return false;
}

// FUNZIONE USATA PER IL SORT ARRAY RANDOM
function randOrd(){
	return (Math.round(Math.random())-0.5);
}

/////////////// FUNZIONE PER CAPITALIZE
String.prototype.capitalize = function(){ //v1.0
    return this.replace(/\w+/g, function(a){
        return a.charAt(0).toUpperCase() + a.substr(1).toLowerCase();
    });
};

function strReplace(arrFind,arrRepl,str){
	for (var i=0; i<arrFind.length; i++){ 
		str = str.replace(arrFind[i], arrRepl[i]); 
	} 
	return str;
}

//////////////////////////////// STAMPA DI UN BLOCCO DI UNA PAGINA
function stampa(idBlock) {
	var testo = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\"><html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />";
	testo += "<link href=\"css/stili.css\" rel=\"stylesheet\" type=\"text/css\" />"; 
	testo += "</head><body><div style=\"height:10px;\"></div><div id=\"coldx\" class=\"floatLeft\" style=\"width:745px;\">";
	testo += $("#"+idBlock).html();
	testo += "</div></body></html>";
	var ident_finestra = window.open("","finestra_stampa","height=700,width=800,top=5,left=5,scrollbars=yes");
	ident_finestra.document.open();
	ident_finestra.document.write(testo);
	ident_finestra.print();
	ident_finestra.document.close();
}

function linkblank(src){
	window.open(src,'','toolbar=yes,location=yes,status=yes,menubar=yes,scrollbars=yes,resizable=yes');
}

function popupImg(src, sito){
	TopUp.display(src, {
		// width:700,
		// height:586,
		// effect:'appear', // 'transform', 'appear' (alias is 'fade'), 'switch' (alias is 'clip')
		layout:'dashboard', // 'quicklook','dashboard'
		shaded:1,
		noGroup:1,
		ondisplay: function(){
			/*
			$(".te_close_link").css("background","url(img/"+sito+"/bottoni/x_pop.gif) left top no-repeat");
			$(".te_close_link").css("background-position","4px 0");
			$(".te_close_link").css("right","7px");
			$(".te_close_link").css("top","9px");
			*/
		},
		onclose: function(){
			// $(".te_close_link").show();
		}
	});
	return(false);
}

function popVideo(srcVideo, sito){
	TopUp.display(srcVideo, {
		width:853,
		height:505,
		type:'flash',
		layout:'dashboard', // 'quicklook','dashboard'
		resizable:0,
		shaded:1,
		noGroup:1,
		ondisplay: function(){
			/*
			$(".te_close_link").css("background","url(img/"+sito+"/bottoni/x_pop.gif) left top no-repeat");
			$(".te_close_link").css("background-position","4px 0");
			$(".te_close_link").css("right","-17px");
			$(".te_close_link").css("top","9px");
			*/
		},
		onclose: function(){
			// $(".te_close_link").show();
		}
	});
	return(false);
} 

function getQueryString(idFormPost) {
	var qstr = "";
	var form = objFromId(idFormPost);
	for (keyVar in form) {
		if(form[keyVar] && form[keyVar].value!=undefined){
			qstr = qstr + keyVar + '=' + escape(form[keyVar].value) + "&";  // NOTE: no '?' before querystring
		}
	}
    return qstr;
}

function strpos(haystack, needle, offset){
    var i = (haystack+'').indexOf(needle, (offset ? offset : 0));
    return i === -1 ? false : i;
}

function strrpos(haystack, needle, offset) {
    var i = -1;
    if (offset) {
        i = (haystack + '').slice(offset).lastIndexOf(needle); // strrpos' offset indicates starting point of range till end,
        // while lastIndexOf's optional 2nd argument indicates ending point of range from the beginning
        if (i !== -1) {
            i += offset;
        }
    } else {
        i = (haystack + '').lastIndexOf(needle);
    }
    return i >= 0 ? i : false;
}

var timeoutLoading=null;
function stopImgLoading(){
	clearTimeout("timeoutLoading");
}
function startImgLoading(id){
	id=(id>8)?1:id;
	$("#imgLoading").attr("src","img/loading/"+id+".png");
	timeoutLoading=setTimeout(function(){
			startImgLoading(id+1);
		},1000
	);
}

function loading(stato){
	return(false);
	/* ------------------ DISATTIVATO ------------------- */
	if(stato==1){
		startImgLoading(1);
		$("#loading").show(0);
	} else {
		stopImgLoading();
		$("#loading").hide(0);
	}
}

function vai(url){
	location.href=url;
}

function rand(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function randNum(){
	var data = new Date();
	data=data.getYear()+data.getMonth()+data.getDate()+data.getHours()+data.getMinutes()+data.getSeconds()+data.getMilliseconds();
	return(data);
}

function unixTime(){
	var foo = new Date; // Generic JS date object
	var unixtime_ms = foo.getTime(); // Returns milliseconds since the epoch
	// var unixtime = parseInt(unixtime_ms / 1000);
	var unixtime = parseInt(unixtime_ms);
	return(unixtime);
}

function getViewportSize() { 
	var size = [0, 0]; 
	if (typeof window.innerWidth != "undefined") { 
		size = [window.innerWidth, window.innerHeight];
	} 
	else if (typeof document.documentElement != "undefined" && typeof document.documentElement.clientWidth != "undefined" && document.documentElement.clientWidth != 0) {
		size = [document.documentElement.clientWidth, document.documentElement.clientHeight]; 
	}
	else {
		size = [document.getElementsByTagName("body")[0].clientWidth, document.getElementsByTagName("body")[0].clientHeight]; 
	}
	return size;
}

function testRegExp(stringa, espressione){
	var espressione = new RegExp(espressione);
	return espressione.test(stringa);
}

function zoomImg(url){
	tb_show('', url);
	return(false);
}

function showAddress(address,titolo,idDiv) {
  // document.getElementById('daddr').value=address;
  if (GBrowserIsCompatible()) {
	geocoder = new GClientGeocoder();
  }

  if (geocoder) {
	geocoder.getLatLng(
	  address,
	  function(point) {
		if (!point) {
		  alert(address + " non trovato");
		} else {
		/*zoom*/

			coordinate = point;

			map = new GMap2(document.getElementById(idDiv));
			
			/*mappa - satellite - ibrida */
			map.addControl(new GMapTypeControl());
			
			/*controller con barra vert*/
			// map.addControl(new GSmallMapControl());
			map.addControl(new GLargeMapControl());
			
			/*zoom box, in basso a dx*/
			map.addControl(new GOverviewMapControl(),
			
			new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(9, 9)));
			
			/*COORDINATE DI PARTENZA DELLA MAPPA*/
			map.setCenter(point, 15);
			// map.setCenter(point, 12);
			var marker = new GMarker(point);
			map.addOverlay(marker);
			if(titolo){
				marker.openInfoWindowHtml(titolo+"&nbsp;&nbsp;&nbsp;&nbsp;");
			} else {
				marker.openInfoWindowHtml(address+"&nbsp;&nbsp;&nbsp;&nbsp;");
			}
		}
	  }
	);
  }
}

function contaCharsTxtArea(maxchar){
	testo=$("#messaggio").val();
	caratteri=testo.length;
	if (caratteri > maxchar){
		$("#messaggio").val(testo.substr(0, maxchar));
	}
}

/* ----------------- INIZIO FUNZIONI DI CARRELLO ----------------------- */

var inviabile=true;

function bloccaNum(nomeModulo, nomeCampo, minVal, maxVal) { // IMPONE AL CAMPO DI ACCETTARE SOLO NUMERI
	oggetto=document.getElementById(nomeModulo);
	var textObj = eval("oggetto."+nomeCampo);
	textObj.onkeyup = function () {
		valoreIniz=textObj.value;
		valoreFin="";
		valoreLenght=valoreIniz.length;
		for (i=0; i<valoreLenght; i++){
			if(!isNaN(valoreIniz.charAt(i))){
				valoreFin+=valoreIniz.charAt(i);
			} else {
			}
		}
		if(valoreFin<minVal){
			valoreFin=minVal;
		}
		if(valoreFin>maxVal){
			valoreFin=maxVal;
		}		
		textObj.value=valoreFin;
	}
}

selectLists = document.getElementsByTagName('select');
function visAllSelect(stato){
	for (var counter=0; counter<selectLists.length; counter++){
		selectLists[counter].style.visibility=(stato==0)?'hidden':'visible';
	}
}

/* ----------------- FINE FUNZIONI DI CARRELLO ----------------------- */

function logout(){
	$.get("background.php", {
		  	act: "logout",
			time: unixTime()
		}, function(data){
			document.location.reload();
	});
	return(false);
}

function logoutAdmin(){
	$.get("background.php", {
		  	act: "logoutAdmin",
			time: unixTime()
		}, function(data){
			document.location.reload();
	});
	return(false);
}

function contrLoginAdmin(){
	insHTML("alertForm", "");
	$.post("background.php",{
			user: $("#user").val(),
			password: $("#password").val(),

			act: "loginAdmin",
			time: unixTime()
		}, function(data){
			if(data=="ok"){
				vai("admin.php");
				return(false);				
			} else {
				insHTML("alertForm", "Autenticazione fallita");
				return(false);				
			}
		});
	return(false);
}

function resizeCnCol(){
	if($('#contProductRange').length>0){
		var totalHeight=Math.max($(window).height(),$(document).height());
		totalHeight=totalHeight-227;
		totalHeight=($.browser.msie)?(totalHeight-3):totalHeight;
		totalHeight=($.browser.mozilla)?(totalHeight+1):totalHeight;
		$('#contProductRange').css('min-height',totalHeight+'px');
	}
	if($('.contNews').length>0){
		var totalHeight=Math.max($(window).height(),$(document).height());
		totalHeight=totalHeight-256;
		totalHeight=($.browser.msie)?(totalHeight-4):totalHeight;
		totalHeight=($.browser.mozilla)?(totalHeight+0):totalHeight;
		$('.contNews').css('min-height',totalHeight+'px');

		
	}
	
}

function funzioniResize(area){
	if(false){
	}else if(area=="home"){
		resizeBackgroundHome();
	}else if(true){
		resizeBackground();
	}
	resizeCnCol();
}

function setSfHeader(){
	if($(document).scrollTop()>0){
		$("#headerInt").addClass("scrolled");
	} else {
		$("#headerInt").removeClass("scrolled");
	}
}

function setBottomFooterIpad(){
	if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
		var totalHeight=$(document).scrollTop()+$(window).height(); // Math.max($(window).height(),$(document).height());
		var marginFooter=totalHeight-34;
		$("#changeRegion, #changeRegionOpen").css("top",marginFooter+"px");
	}
}

function funzioniScroll(area){
	setBottomFooterIpad();

	if(false){
	}else if(area=="home"){

	}else if(area!="gallery"){
		setSfHeader();
	}

}

function attivaIntervalIE(act){
	if(isIE()){
		if(act==1){
			intervalIE=setInterval(function(){ funzioniResize(); },500);
		} else {
			clearInterval(intervalIE);	
		}
	}
}

function openChangeRegion(stato){
	if(stato==1){
		$("#changeRegionOpen").stop().fadeIn();
		$("#changeRegion").stop().fadeOut();
		setBottomFooterIpad();
			/*
		$("#changeRegionOpen").after(
			$("<div/>").attr("id","newsBG").html("&nbsp;").width($(window).width()).height($(window).height()).css(
				{opacity:0,"backgroundColor":"#000000",
				position:"fixed","top":0,"left":0,"z-index":1000})
			);
			*/
			
		$("#newsBG").click(function(e){
		  openChangeRegion(0);
  		});
			
			// $("#newsBG").animate({opacity:0.5},500);
	} else {
		$("#changeRegionOpen").stop().fadeOut();
		$("#changeRegion").stop().fadeIn();
		$('#newsBG').stop().animate({opacity:0},500,function(){$("#newsBG").remove();});
		setBottomFooterIpad();
	}
	return(false);
}

function attivaChangeRegion(){
	// $("#changeRegion, #changeRegion a").bind("click", function(){
	$("#changeRegion #linkOpen").unbind("click");
	$("#changeRegion #linkOpen").bind("click", function(){
		return(openChangeRegion(1));
	});
	
}

var timerCS=null;
function attivaComingSoon(){
	return(false);
	$(".comingsoon").bind("click", function(){ return(false); });
	$(".comingsoon").bind("mouseover", function(){
		clearTimeout(timerCS);
		$("#comingsoon").hide(0);
		offsetDiv=$(this).offset();
		vOffset=offsetDiv.top;
		oOffset=offsetDiv.left;
		itemW=$(this).width();
		itemH=$(this).height();
		vOffset=vOffset+parseInt((itemH)/2,10)+10;
		oOffset=oOffset-71+parseInt((itemW)/2,10);
		$("#comingsoon").animate({
			top: vOffset,
			left: oOffset
		}, 0);
		$("#comingsoon").show(0);
		timerCS=setTimeout(function(){ $("#comingsoon").hide(0); },2000);
		return(false);	
	});
}

function funzioniOnLoad(area){
	BrowserDetect.init();
	if(isIE() && $.browser.version>6){ // !IE6
		
	} else { // IE6
		ie6custom();
	}
	fixPng();

	setBottomFooterIpad();

	attivaScrollBars();

	attivaIntervalIE(1);
	// $('.slideScroll').touchScroll();

	funzioniResize(area);

	

	if(false){
	} else if(area=="home"){
	  openChangeRegion(1);
		//setActiveBoxHome();
	} else if(true){
		$("#imgBackgroundHome").bind("load",function(){ funzioniResize(area); });	
	}
	
	$("#menuServices .change_region, #menuSubHeader .change_region").unbind("click"); $("#menuServices .change_region, #menuSubHeader .change_region").bind("click", function(){ openRegions(); return(false); })
	
	try{
		if($('input[name="query"]').length > 0 && HVA){
		  $('input[name="query"]').parent().submit(function(e){
			window.location = HVA.baseUrl+"/search/#!/query:"+$("#query").val();
			return false;
		  });
		}
	}catch(err){
		
	}
  
  // make left column content flow under menu. really crappy hack for simple css issues ;)
  if($("#menuSxH").length>0){
	  var menuSinistra = $("#menuSxH");
	  var mHeight = menuSinistra.outerHeight();
	  var mTotal = mHeight + parseInt(menuSinistra.css("marginTop").replace(/[a-z]/g,"")) + 10;
  }

  $("#contColSxDn").hide().css({marginTop:mTotal}).delay(100).fadeIn();
	
	
	// process hover menu
	loadMotoMenu();
	
	// attivaChangeRegion();
	attivaComingSoon();
	
}

function caricaChangeRegion(urlPag){
	$("#changeRegion a:contains('Change Region')").remove();
	if($("#changeRegion").length>0){
		$.get(urlPag, {
				time: unixTime()
			}, function(data){
				// alert(data);
				$("#changeRegion").html(data);
				attivaChangeRegion();
		});
	}
}

function loadMotoMenu(){
  
  var selectorMain = $("ul.subMain li");
  
  selectorMain.hover(function(e){
    $(this).children("ul").show();
  },function(e){
    $(this).children("ul").hide();
  });
  
  var selector = $("ul.subCat li");
  
  selector.hover(function(e){
    $(this).children("ul").show();
  },function(e){
    $(this).children("ul").hide();
  });
  
  var mainMenu = $("ul.subMain").parent();
  
  //$("ul.subMain").show();
  //selector.children("ul").show();
  
  mainMenu.addClass("showing");
  /*mainMenu.hover(function(e){
    $(this).children("ul.subMain").show().animate({opacity:1},200);
  },function(e){
    $(this).children("ul.subMain").animate({opacity:0},300,function(){$(this).children("ul.subMain").hide();});
  });*/
  mainMenu.hover(function(e){
    $(this).children("ul.subMain").show();
  },function(e){
    $(this).children("ul.subMain").hide();
  });
  
}
