// GLOBAL FUNCTION
var region_default=false;
var city_default=false;

function ajaxLoader(url,divDest,fnct){
	this.url=url;
	this.divDest=divDest;
	this.fnct=fnct;	
	this.rObj = false; // XMLHttpRequest Object
	if (window.XMLHttpRequest) // try to create XMLHttpRequest
		this.rObj = new XMLHttpRequest();	
	if (window.ActiveXObject)	// if ActiveXObject use the Microsoft.XMLHTTP
		this.rObj = new ActiveXObject("Microsoft.XMLHTTP");		
	var thisobj=this;	
	this.rObj.open("GET", this.url , true);
	this.rObj.onreadystatechange = function(){
		if (thisobj.rObj.readyState==4) {
			if(thisobj.divDest!=null){
				if(document.getElementById(thisobj.divDest)){
					document.getElementById(thisobj.divDest).style.display='block';
					document.getElementById(thisobj.divDest).innerHTML=thisobj.rObj.responseText;
				}
			}
			if(thisobj.fnct!=null)
				eval(thisobj.fnct)(thisobj.divDest,thisobj.rObj.responseText);
		}		
	};
	this.rObj.send(null); 	
}

function addClassAttribute(elem,styleName){
	if(elem.className.indexOf(styleName)==-1)
		elem.setAttribute('class',elem.className+' '+styleName);
}
function removeClassAttribute(elem,styleName){
	var strclassname=elem.className;
	elem.setAttribute("class",trim(strclassname.replace(styleName,"")));
}

function trim(str) {
	var res="";
	if(str){
		if(str.length>0){
			res=ltrim(rtrim(str, "\\s"), "\\s");
		}
	}
	return res;
}
function ltrim(str, chars) {
//	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

function changeCountry(el){
	if(region_default==false)
		region_default=document.getElementById("region_sel").options[0].text;
	if(city_default==false)
		city_default=document.getElementById("city_sel").options[0].text;
	
	document.getElementById("resultsList").innerHTML="";
	
	resetRegion();
	resetCity();
	resetFlag();
	if(el.options[el.selectedIndex].value=="ITALIA"){
		loadRegion();
	}else if(el.selectedIndex!=0){
		loadCity();		
	}
}
function resetFlag(){
	document.getElementById("sposa_check").checked=false;
	document.getElementById("cerimonia_check").checked=false;
	document.getElementById("top_seller_check").checked=false;	
}
function resetRegion(){
	while (document.getElementById("region_sel").options.length>0)
		document.getElementById("region_sel").options[0]=null;
	document.getElementById("region_sel").options[0]=new Option(region_default,0);
	document.getElementById("region_sel").selectedIndex=0;
	document.getElementById("region_sel").disabled=true;
	addClassAttribute(document.getElementById("region_sel"),"disabled");
}
function resetCity(){
	while (document.getElementById("city_sel").options.length>0)
		document.getElementById("city_sel").options[0]=null;
	document.getElementById("city_sel").options[0]=new Option(city_default,0);
	document.getElementById("city_sel").selectedIndex=0;
	document.getElementById("city_sel").disabled=true;
	addClassAttribute(document.getElementById("city_sel"),"disabled");	
}
function changeFlag(el){
	//alert("CHANGE {\nchecked:"+el.checked+"\ncountry index:"+document.getElementById("country_sel").selectedIndex+"\ncountry val:"+document.getElementById("country_sel").options[document.getElementById("country_sel").selectedIndex].value+"\nregion index:"+document.getElementById("region_sel").selectedIndex+"\n}")
	if(document.getElementById("country_sel").selectedIndex==0 || (document.getElementById("country_sel").options[document.getElementById("country_sel").selectedIndex].value=="ITALIA" && document.getElementById("region_sel").selectedIndex==0)){
		el.checked=false;
		return false;
	}else{
		loadResults();
		return true;
	}
}
function changeRegion(el){
	resetCity();	
	loadCity();
	resetFlag();
}

function changeCity(el){
	loadResults();
}

function loadRegion(){
	document.getElementById("region_sel").disabled=false;
	removeClassAttribute(document.getElementById("region_sel"),"disabled");
	var url="/_php/vendorsCityRegion.php?country="+document.getElementById("country_sel").options[document.getElementById("country_sel").selectedIndex].value;
	
	new Ajax.Request(url, {method: 'get',
				onSuccess: function(transport) {
					for(var x in transport.responseJSON.lista){
						if(transport.responseJSON.lista[x].regione!=undefined)
						  document.getElementById("region_sel").options[document.getElementById("region_sel").options.length]=new Option(transport.responseJSON.lista[x].regione,transport.responseJSON.lista[x].regione);
					}
				}
	});
	
}					

function loadCity(){
	document.getElementById("city_sel").disabled=false;
	removeClassAttribute(document.getElementById("city_sel"),"disabled");
	if(document.getElementById("country_sel").options[document.getElementById("country_sel").selectedIndex].value=="ITALIA")
		var url="/_php/vendorsCityRegion.php?region="+document.getElementById("region_sel").options[document.getElementById("region_sel").selectedIndex].value;	
	else	
		var url="/_php/vendorsCityRegion.php?coutryRegion="+document.getElementById("country_sel").options[document.getElementById("country_sel").selectedIndex].value;	

	new Ajax.Request(url, {method: 'get',
				onSuccess: function(transport) {
					for(var x in transport.responseJSON.lista){
						if(transport.responseJSON.lista[x].citta!=undefined)
						  document.getElementById("city_sel").options[document.getElementById("city_sel").options.length]=new Option(transport.responseJSON.lista[x].citta,transport.responseJSON.lista[x].citta);
					}
					loadResults();
				}
	});
	
}

function loadResults(){
	var param="?q=1";
	if(document.getElementById("sposa_check").checked)
		param+="&sposa_check=1";
	if(document.getElementById("cerimonia_check").checked)
		param+="&cerimonia_check=1";
	if(document.getElementById("top_seller_check").checked)
		param+="&top_seller_check=1";
	if(document.getElementById("country_sel").selectedIndex!=0){
		param+="&country_sel="+document.getElementById("country_sel").options[document.getElementById("country_sel").selectedIndex].value;
	}
	if(document.getElementById("region_sel").selectedIndex!=0){
		param+="&region_sel="+document.getElementById("region_sel").options[document.getElementById("region_sel").selectedIndex].value;
	}
	if(document.getElementById("city_sel").selectedIndex!=0){
		param+="&city_sel="+document.getElementById("city_sel").options[document.getElementById("city_sel").selectedIndex].value;
	}
	if(window.location.href.indexOf("/it/")==-1){
		param+="&lang=en";
	}	
	var url="/_php/vendors.php"+param; //?region_sel=campania";
	new ajaxLoader(url,"resultsList","attivaShadowBox");
}

function attivaShadowBox(p1,p2){
	Shadowbox.setup();
}

function apriChiudi(div){
	document.getElementById(div).style.display = (document.getElementById(div).style.display=="none" ? "block" : "none");
}

function myFavAdd(a,b,c,d){
	//jsonOBJ.push({'id':c,'tit':a,'url':b,'img':d});
	myCookie = GetCookie('fav');
	if (myCookie!=null) jsonOBJ  = myCookie.evalJSON();
	add = true;
	for(var k=0;k<jsonOBJ.length;k++){
		if (jsonOBJ[k].id == c) add = false;
	}
	if (add) jsonOBJ.push({'id':c,'tit':a,'url':b,'img':d});
	objStr = Object.toJSON(jsonOBJ);
	expires = new Date();
	expires.setTime(expires.getTime()+(365*24*60*60*1000));
	SetCookie('fav', objStr, expires, '/');
	writeMyFav('myFavCnt',jsonOBJ);
	document.getElementById('showMyOldFav').style.display = 'inline';
}
function showMyOldFav(){
	myCookie = GetCookie('fav');
	if (myCookie!=null) jsonOBJ  = myCookie.evalJSON();
	str = writeMyFav(null,jsonOBJ);
	w = 52*myCookie.length;
	Shadowbox.open({
        content:    '<div id="popup-msg"><div id="popup-msg-cnt">'+str+'</div></div><script language="javascript" type="text/javascript">document.getElementById("myFavScrolledPopup").style.width = "'+w+'px";</script>',
        player:     "html",
        title:      ""/*favTit[currentLang]*/,
        height:     197,
        width:      405
    });
}
function writeMyOldFav(){
	myCookie = GetCookie('fav');
	if (myCookie!=null) jsonOBJ  = myCookie.evalJSON();
	writeMyFav('myFavCnt',jsonOBJ);
}
function writeMyFav(trgt,myFav){
	if (trgt=="myFavCnt") {
		suffix = "";
	} else {
		suffix = "Popup";
	}
	str = "";
	mail = "";
	w = 472;
	if(document.getElementById("favBtn")) {
		document.getElementById("favBtn").style.display = "inline";
		document.getElementById("favBtnDone").style.display = "none";
	}
	if (myFav) {
		w = 52*myFav.length;
		for(var k=0;k<myFav.length;k++){
			if (myFav[k].url && myFav[k].img){
				str+='<div class=\"pref\"><a href="'+unescape(myFav[k].url)+'" title="'+unescape(myFav[k].tit).replace(/\+/g," ")+'"><img alt="'+unescape(myFav[k].tit).replace(/\+/g," ")+'" src="'+unescape(myFav[k].img)+'" /></a><br /><a href="#" onclick="deleteFav('+myFav[k].id+'); return false;"><img alt="delete '+unescape(myFav[k].tit).replace(/\+/g," ")+'" src="/_images/delete.gif" /></a></div>';
				mail+=unescape(myFav[k].tit)+' '+sitePath+myFav[k].url+'\n';
			}
			if(document.getElementById("favBtn")) {
				if(myFav[k].url == window.location.href.replace(sitePath,"")) {
					document.getElementById("favBtnDone").style.display = "inline";
					document.getElementById("favBtn").style.display = "none";
				}
			}
		}
	}
	if (str == "") {
		str = '<div class="favAlt">'+favMess[currentLang]+'</div>';
		w = 472;
	}
	str = "<div class=\"mb5\">"+favTit[currentLang]+"&#160;&#160;&#160;&#160;<img src=\"/_images/icona_preferiti.gif\" alt=\"{fav/txt}\" align=\"absmiddle\" /></div><div id=\"myFav"+suffix+"\"><div id=\"myFavScrolled"+suffix+"\">"+str+"</div></div><div id=\"controller2\"><div class=\"left\"><a href=\"#\" onclick=\"muovi('myFavScrolled"+suffix+"',300); return false;\"><img src=\"/_images/freccia_sx.gif\" alt=\"right icon\" /></a></div><div class=\"right\"><a href=\"#\" onclick=\"muovi('myFavScrolled"+suffix+"',-300); return false;\"><img src=\"/_images/freccia_dx.gif\" alt=\"left icon\" /></a></div><br class=\"myClear\" /></div>";
	if (document.getElementById('pref')) document.getElementById('pref').value = mail;
	if (trgt) {
		document.getElementById(trgt).innerHTML = str;
		document.getElementById("myFavScrolled"+suffix).style.width = w+"px";
	} else {
		return str;
	}
}
function deleteFav(id){
	myCookie = GetCookie('fav');
	if (myCookie!=null) jsonOBJ  = myCookie.evalJSON();
	if (jsonOBJ) {
		for(var k=0;k<jsonOBJ.length;k++){
			if (jsonOBJ[k].id == id){
				jsonOBJ.splice(k,1);
			}
		}
	}
	expires = new Date();
	expires.setTime(expires.getTime()+(365*24*60*60*1000));
	SetCookie('fav', Object.toJSON(jsonOBJ), expires, '/');
	if (document.getElementById('myFavCnt')) writeMyFav('myFavCnt',jsonOBJ);
	if (document.getElementById('popup-msg-cnt')) writeMyFav('popup-msg-cnt',jsonOBJ);
	if (!jsonOBJ.length) document.getElementById('showMyOldFav').style.display = 'none';
}

/* COOKIE  */
function SetCookie(name, value){		
   var argv = SetCookie.arguments;
   var argc = SetCookie.arguments.length;
   var expires = (2 < argc) ? argv[2] : null;
   var path = (3 < argc) ? argv[3] : null;
   var domain = (4 < argc) ? argv[4] : null;
   var secure = (5 < argc) ? argv[5] : false;
   document.cookie = name + "=" + escape (value) + ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +((path == null) ? "" : ("; path=" + path)) +((domain == null) ? "" : ("; domain=" + domain)) + ((secure == true) ? "; secure" : "");
}
function GetCookie(name){
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen){
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg)
			return getCookieVal(j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) 
			break; 
	}
	return null;
}
function getCookieVal(offset){
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) {
		endstr = document.cookie.length;
	}
	return unescape(document.cookie.substring(offset, endstr));
}
function RemoveCookie(name){
	document.cookie = name+"=; path=/";	
}

/* END COOKIE  */

function sbSetup(div,cnt){
	Shadowbox.setup();
}
function muovi(div,w){
	//larghezzaContenitore = $(div).ancestors()[0].getWidth();
	if ($(div).positionedOffset()[0]+w<=0 && $(div).positionedOffset()[0]+w>-$(div).getWidth()) {
		new Effect.Move(div, { x: w, y: 0, mode: 'relative' });
	}
}
function setScroll() {
	if (document.getElementById('scroller')) {
		catItem = $$(".cat");
		for (i=0; i<catItem.length; i++) {
			if(window.location.href == catItem[i].href) {
				document.getElementById('scrolled').style.left = (-Math.floor(i/2)*300)+"px";
				//muovi("scrolled", -Math.floor(i/3)*480);
			}
		}
		document.getElementById('scrolled').style.display = "block";
	}
}


function urlEncode(plaintext){
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";
	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	}
	return encoded;
}

function setSession(name,value,callback){
	if (name == 'lang') {
		currentLang = value;
	}
	if(xmlRequestObjectSetSess){		
		if(callback==""){
			xmlRequestObjectSetSess.onreadystatechange = setSessionComplite;
		}else{
		 	xmlRequestObjectSetSess.onreadystatechange = eval(callback);
		}	
		xmlRequestObjectSetSess.open("GET", "/_php/sessionSet.php?"+name+"="+value , true);
		xmlRequestObjectSetSess.send(null);
		ajaxComplite=false;
	}	
}
function getSession(name,fnc){
	if(xmlRequestObject){
		function_get_session_complete=fnc;
		xmlRequestObject.open("GET", "/_php/sessionGet.php?name="+name, true);
		xmlRequestObject.onreadystatechange = getSessionComplite;
		xmlRequestObject.send(null);
	}	
}

function setSessionComplite(){
	if (xmlRequestObjectSetSess.readyState==4) {
		ajaxComplite=true;
	}
}

function getSessionComplite(){
	if (xmlRequestObject.readyState==4) {
		if (xmlRequestObject.responseText.indexOf('invalid') == -1){
			var node = xmlRequestObject.responseXML.documentElement;
			var items = node.getElementsByTagName('session');
			if(items[0].firstChild){
				sessionVal=items[0].firstChild.data;
			}else{
				sessionVal="";
			}
			eval(function_get_session_complete)(sessionVal);
		}
	}
}

function popupwindow(LarghezzaCont,AltezzaCont,Pagina,nome,scrol,stat) {
	var lsBrowser = navigator.appName;
	var navInfo = navigator.userAgent;
	if (scrol == "yes") {
		if (navInfo == "Mac" && lsBrowser.indexOf("Microsoft") >= 0) {
				aw = 0;
		} else {
		aw = 17;
		}		
	} else {
	aw = 0;
	}		
    var iMyWidth;
    var iMyHeight;
    var LarghezzaPagina;
    var AltezzaPagina;
    LarghezzaPagina = screen.availWidth;
    AltezzaPagina = screen.availHeight;
    LarghezzaCont=LarghezzaCont.toUpperCase()
    AltezzaCont=AltezzaCont.toUpperCase()
				
    if (LarghezzaCont == "FULL") {
            LarghezzaWindow = screen.availWidth;
        } else {
            LarghezzaWindow = parseInt(LarghezzaCont) + aw;
        }
    if (AltezzaCont == "FULL") {
            AltezzaWindow = screen.availHeight;
        } else {
            AltezzaWindow = AltezzaCont;
        }
    iMyWidth = (LarghezzaPagina/2) - (LarghezzaWindow/2);
    iMyHeight = (AltezzaPagina/2) - (AltezzaWindow/2);
    win = window.open(Pagina,nome,"height=" + AltezzaWindow + ",width="	+ LarghezzaWindow 
	+ ",menubar=0,resizable=yes,scrollbars=" + scrol + ",status=" + stat + ",titlebar=0,toolbar=0,left="
	+ iMyWidth + ",top=" + iMyHeight + ",screenX=" + iMyWidth + ",screenY=" + iMyHeight + "");
    win.focus();
}
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

function is_auth(sessionVal){
//	
	if(sessionVal==1){
		if(window.location.href.indexOf("/en/")!=-1){
			$("rivenditori").innerHTML="<ul><li>Welcome <span id=\"user_name_field\">&nbsp;</span></li><li> | <a href=\"/it/area-riservata/\">RETAILERS AREA</a></li><li> | <a href=\"/_php/logact.php?act=logout\">LOGOUT</a></li></ul>";
		}else{
			$("rivenditori").innerHTML="<ul><li>Benvenuto <span id=\"user_name_field\">&nbsp;</span></li><li> | <a href=\"/it/area-riservata/\">AREA RIVENDITORI</a></li><li> | <a href=\"/_php/logact.php?act=logout\">ESCI</a></li></ul>";
		}
		getSession("user_name","fillUpUserName");
	}else{
		if(window.location.href.indexOf("failed_auth")!=-1){
			if(window.location.href.indexOf("/en/")!=-1){
				new Insertion.Before($("formLogin"), "<strong style=\"color:#F00;\">incorrect login</strong>");			
			}else{
				new Insertion.Before($("formLogin"), "<strong style=\"color:#F00;\">dati errati</strong>");
			}
			apriChiudi('boxLogin');
		}
	}
}
function fillUpUserName(sessionVal){
	$("user_name_field").innerHTML=sessionVal;
}
 





window.onload = onLoad;


function onLoad() {
	
	//MM_preloadImages('/_images/testa_flv_f2.gif','/_images/testa_switch_f2.gif');
	setSession('lang',currentLang,"");
	if (document.getElementById('myFavCnt')) writeMyOldFav();
	caricaFlashAvvio();
	setScroll();
	//verifico la sessione
	getSession("user_auth","is_auth");
	
}
/* document.observe("dom:loaded", function() {
	setSession('lang',currentLang,"");
	if (document.getElementById('myFavCnt')) writeMyOldFav();
	caricaFlashAvvio();
	setScroll();
										
	var myCookie = GetCookie('fav');
	if (myCookie!=null) jsonOBJ  = myCookie.evalJSON();
	if (jsonOBJ.length) document.getElementById('showMyOldFav').style.display = 'block';
});
*/



