window.onunload = function(){
	if(window.popUp&&!window.popUp.closed) window.popUp.close();
}
function openPopUp(sPath,w,h,t,l,event){
	e = event;
	if(window.popUp&&!window.popUp.closed) window.popUp.close();
	
	l = screen.width/2-w/2;
	t = screen.height/2-h/2;
	
	window.popUp = window.open(sPath,"PopUp","width="+w+",height="+h+",top="+(t||100)+",left="+(l||100)+",scrollbars=1");
	if(e){
		if(typeof(e.stopPropagation)=="undefined")
			e.cancelBubble = true;
		else
			e.stopPropagation();
	}
	return false;
}
function showHideCat(o){
	while((o=o.nextSibling)&&o.nodeType!=1)	;
	if(o.style.display=='none')
		{o.style.display='';o.previousSibling.className="open";}
	else
		{o.style.display='none';o.previousSibling.className="folder";}
	return false;
}

function isEmpty(str){return (str.replace(/\s/g,"").length==0)}
function _mail(str){return str.search(/^([\w\.\-])+@(([\w\-]{2,})+\.)+([a-z0-9]{2,})+$/i)!=-1}

function checkRegFRM(frm){
	var chkIVA = frm.elements["userTypeID"].value.charAt(0)==1;
	var naz = frm.elements["country"];
	if(naz){
		if(naz.type=="select-one")
			naz = (naz.options[naz.selectedIndex].value||"").toUpperCase();
		else
			naz = naz.value;
	}else
		naz = "";
	var sOptional = "|customField1|customField2|customField3|customField4|customField5|customField6|customField7|customField8|fax|"+
					"destinationName|destinationAddress|destinationCity|destinationProvince|destinationPostalCode|destinationPhone|destinationFax|";
	
	for(var i=0,fldName='',reg;i<frm.elements.length;i++){
		if(frm.elements[i].disabled) continue;
		fldName = frm.elements[i].name;
		reg = new RegExp("\\|"+fldName+"\\|");
		if((fldName=="companyCode")&&!chkIVA) continue;
		if( (frm.elements[i].type=="text"||frm.elements[i].type=="password") && sOptional.search(reg)==-1 && isEmpty(frm.elements[i].value) ){
			alert(window.fillField+(window[fldName]?': '+window[fldName]:''));
			frm.elements[i].focus();
			return false;
		}
	}
	if( frm.province && frm.province.selectedIndex==0 ){
		alert(window.fillField+": "+window.province);
		frm.province.focus();
		return false;
	}
	if( frm.country && frm.country.selectedIndex==0 ){
		alert(window.fillField+": "+window.country);
		frm.country.focus();
		return false;
	}
	
	// PARTITA IVA
	if( frm.companyCode && !frm.companyCode.disabled && chkIVA && (naz.search(/^(ITA|I|IT)$/)==0) ){
		if( !ControllaPIVA(frm.companyCode.value) ){
			alert(window.erratedValue+": "+window.companyCode);
			frm.companyCode.focus();
			frm.companyCode.select();
			return false;
		}
	}
	
	// CODICE FISCALE
	if( frm.personCode && !frm.personCode.disabled && (naz.search(/^(ITA|I|IT)$/)==0) ){
		if( !ControllaCF(frm.personCode.value) && !ControllaPIVA(frm.personCode.value) ){
			alert(window.erratedValue+": "+window.personCode);
			frm.personCode.focus();
			frm.personCode.select();
			return false;
		}
	}
	
	if(frm.postalCode.value.search(/^\d{5}$/)==-1&&naz.search(/^(RSM|I|IT)$/)==0){
		alert(window.erratedValue+": "+window.postalCode);
		frm.postalCode.focus();
		frm.postalCode.select();
		return false;
	}
	
	if(!_mail(frm.mail.value))
		{alert(window.erratedValue+": "+window.mail);frm.mail.focus();frm.mail.select();return false;}
	
	if(frm.pwd.value!=frm.rewritePwd.value){
		alert("Controllare di aver digitato correttamente la password!");
		frm.pwd.focus();
		return false;
	}
	
	if(!frm.privacy.checked){
		alert("E' necessario accettare le condizioni del trattamento dati");
		frm.privacy.focus();
		return false;
	}
	
	
	return true;
}


function ControllaCF(cf){
	var validi, i, s, set1, set2, setpari, setdisp;
    if( cf == '' )  return true;
    cf = cf.toUpperCase();
    if( cf.length != 16 )
		return false;
		/*
        return "La lunghezza del codice fiscale non ?\n"
        +"corretta: il codice fiscale dovrebbe essere lungo\n"
        +"esattamente 16 caratteri.\n";
		*/
    validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    for( i = 0; i < 16; i++ ){
        if( validi.indexOf( cf.charAt(i) ) == -1 )
          return false;
		   /*
		    return "Il codice fiscale contiene un carattere non valido `" +
                cf.charAt(i) +
                "'.\nI caratteri validi sono le lettere e le cifre.\n";
		*/
    }
    set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
    setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
    s = 0;
    for( i = 1; i <= 13; i += 2 )
        s += setpari.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
    for( i = 0; i <= 14; i += 2 )
        s += setdisp.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
    if( s%26 != cf.charCodeAt(15)-'A'.charCodeAt(0) )
       return false;
	   /*
	    return "Il codice fiscale non ? corretto:\n"+
            "il codice di controllo non corrisponde.\n";
		*/
    return true;
}

function ControllaPIVA(pi){
    if( pi == '' )  return true;
    if( pi.length != 11 )
     	return false;
	   /*
	    return "La lunghezza della partita IVA non ?\n" +
            "corretta: la partita IVA dovrebbe essere lunga\n" +
            "esattamente 11 caratteri.\n";
		*/
    validi = "0123456789";
    for( i = 0; i < 11; i++ ){
        if( validi.indexOf( pi.charAt(i) ) == -1 )
           return false;
		   /*
		    return "La partita IVA contiene un carattere non valido `" +
                pi.charAt(i) + "'.\nI caratteri validi sono le cifre.\n";
			*/
    }
    s = 0;
    for( i = 0; i <= 9; i += 2 )
        s += pi.charCodeAt(i) - '0'.charCodeAt(0);
    for( i = 1; i <= 9; i += 2 ){
        c = 2*( pi.charCodeAt(i) - '0'.charCodeAt(0) );
        if( c > 9 )  c = c - 9;
        s += c;
    }
    if( ( 10 - s%10 )%10 != pi.charCodeAt(10) - '0'.charCodeAt(0) )
        return false;
		/*
		return "La partita IVA non ? valida:\n" +
            "il codice di controllo non corrisponde.\n";
		*/
    return true;
}


function expandNode(id){
	var obj = document.getElementById("lnk_"+id);
	obj.innerHTML=obj.innerHTML=="+"?"-":"+";
	obj=document.getElementById("row_"+id);
	obj.style.display=obj.style.display=="none"?"":"none";
	return false;
}
/*
function fDelay(obj){
	var o = document.getElementById("waitLoading");
	var left = screen.width/2-125;
	o.style.left = (left)+"px"
	o.style.display = "block";
	if(obj.form)
		setTimeout("document.forms['"+obj.form.name+"'].submit();",1000);
	else
		setTimeout('location.href="'+obj.href+'"',1000);
	return false;
}
*/
var openUL = null;
var over = false;
function showBlock(el,e){
	e = e||event;
	
	hideflash(); // server per IE
	
	if(e.stopPropagation) e.stopPropagation(); 
	else e.cancelBubble = true;
	
	var currentUL = el.getElementsByTagName("ul")[0];
	if(openUL)
		hideBlock(currentUL);
	
	openUL = currentUL;
	openUL.style.display = "block";
}
function closeBlock(){	
	if(window.timeOutID)
		clearTimeout(window.timeOutID);
	window.timeOutID = setTimeout("hideBlock();",1000);
	window.over = false;
}
function hideBlock(currentUL){
	if(!currentUL){
		if(window.over) return;
		showflash();
	}
	currentUL = currentUL||document.getElementById("root").getElementsByTagName("ul")[0];
	var o = openUL;
	while( o && o.nodeName=="UL" ){
		if(o == currentUL.parentNode.parentNode)
			break
		o.style.display = "none";
		o = o.parentNode.parentNode;
	}
}


function getFlashObj(movie){
	if(window.document[movie]){
		return window.document[movie];
	}
	if(navigator.appName.indexOf("Microsoft Internet")==-1){
		if (document.embeds && document.embeds[movie])
			return document.embeds[movie]; 
		else
			return document.getElementById(movie);
	}
}

function setDimensions(_name) {
	var movieObj = getFlashObj(_name);
	if(movieObj){
		var width = movieObj.TGetProperty("/", 8);
		var height = movieObj.TGetProperty("/", 9);
		movieObj.setAttribute("width",width);
		movieObj.setAttribute("height",height);
	}
}

var arrFlashObj = [];
window.onload = function(){
	for(var i=0;i<arrFlashObj.length;i++)
		setDimensions(arrFlashObj[i]);
}

function addLoadEvent(func){
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
    	window.onload = func;
	} else {
		window.onload = function(){
			oldonload();
			func();
		}
	}
}

function showDLElements(hrefObj,groupName){
	if(!hrefObj){
		var div = document.getElementById("groupBoxWithTab") || document.getElementById("sheetDetailsBoxes");
		hrefObj = div.getElementsByTagName("a")[0];
	}
	var dt = hrefObj.parentNode;
	var dl = dt.parentNode;
	var dts = dl.getElementsByTagName("dt");
	for(var i=0; i<dts.length; i++){
		if( dts[i]==dt ){
			if(i>0)
				dts[i-1].className = "tab_prevSibling";
			
			if( i==(dts.length-1) )
				dt.className = "tab_on2";
			else
				dt.className = "tab_on";
		}else{
			if( i==(dts.length-1) )
				dts[i].className = "tab_off2";
			else
				dts[i].className = "tab_off";
		}
	}
	
	var dd = dl.getElementsByTagName("dd");
	for(var i=0; i<dd.length; i++)
		dd[i].style.display = "none";
	var o = dt;
	while( o && (o=o.nextSibling) ){
		if(o.nodeType==3) continue;
		if(o.nodeName.toLowerCase()=="dd")
			o.style.display = "block";
		else
			break;
	}
}

var timerSolvingBox = null;
function startBoxSolving(parentID,element,opacType,opacIndex){
	opacType = opacType||"+";
	opacIndex = opacIndex>>0||0;
	if(opacIndex>100){
		clearTimeout(timerSolvingBox);
		setTimeout("startBoxSolving('"+parentID+"',document.getElementById('"+element.id+"'),'-',100);",3000);
		return;
	}else if(opacIndex<0){
		element.style.display = "none";
		element = get_nextsibling(element);
		opacType = '+';
		opacIndex = 0;
	}
	var first = document.getElementById(parentID).getElementsByTagName("li")[0];
	if( !element )
		element = first;
	element.style.display = "block";
	changeOpac(opacIndex,element.id);
	eval("opacIndex = opacIndex "+opacType+" 10;");
	timerSolvingBox = setTimeout("startBoxSolving('"+parentID+"',document.getElementById('"+element.id+"'),'"+opacType+"',"+opacIndex+");",100);
}

function get_nextsibling(o){
	var x = o.nextSibling;
	while ( x && x.nodeType!=1 )
  		x = x.nextSibling;
	return x;
}

function changeOpac(opacity, id) {
	var object = document.getElementById(id);
	if(!object) return;
	object = object.style; 
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}

function startNewsSolving(){
	return startBoxSolving("oneNewsBox");
}

function emptyField(o){
	o.value = "";
	o.onblur = function(){
					if( this.value == "")
						this.value = this.defaultValue;
				}
}

function ajaxRequestComplete(XMLHttpRequest, textStatus){
	if(textStatus=="success"){
		var oResponse = $( document.createElement("div") ).append(XMLHttpRequest.responseText);
		oResponse.children().each( function(){
			if(this.id){
				var o = $("#"+this.id);
				if(o){
					o.empty();
					var sHtml = $(this).html();
					if(sHtml)
						o.html(sHtml);
					//o.replaceWith( $(this) );
				}
			}
		});
	}
}

function ajaxRequest(el){
	var data = [];
	var href = el.href || el.action;
	var sQS = "";
	if( href ){
		var href = href.split("?");
		if( href.length>1 ){
			sQS = href[1].split("#");
			sQS = sQS[0];
		}
	}
	if( el.nodeName.toUpperCase()=="FORM" ){
		for( var i=0; i<el.elements.length; i++ ){
			data.push(el[i].name+"="+escape(el[i].value));
		}
		// in caso di form in get invio in QS
		if(el.method != "post"){
			sQS = data.join("&");
			data = [];
		}
	}
	
	$.ajax({
			type: "POST",
			url: "ajaxRequests.asp?"+sQS,
			complete: ajaxRequestComplete,
			data:data.join("&")
			//success
			});
}

var resultFadeOut = null;
var fadeOutTimer = 0;
function startQuickSearch(obj){
	if( obj.value && obj.value.length>2 ){
		// dati per la ricerca
		// viene fatta la chiamata e automaticamente viene sostituito il DIV coi risultati in pagina
		ajaxRequest( obj.form );
		if( fadeOutTimer<=0 ){
			$("#brandFormBox select").hide();
			$("#ricercheRisultati").fadeIn("slow");
			$("#ricercheRisultati").mouseover(function(){fadeOutTimer=0});
			$("#ricercheRisultati").mouseout(function(event){
												if( $(event.target).is('#ricercheRisultati') ){
													fadeOutTimer=-1
												}
											}
											);
			resultFadeOut = setInterval( "setRisultatiShow();",1 );
		}
	}else
		fadeOutTimer = 0;
		
}
function setRisultatiShow(){
	if( fadeOutTimer==-1 || fadeOutTimer>500 ){
		setRisultatiHide();
	}else{
		var obj = $("#cmdString");
		var left = $(obj).offset( ).left + 2;
		var top = $(obj).offset( ).top + $(obj).outerHeight();
		$("#ricercheRisultati").css("top",top).css("left",left);
		fadeOutTimer++;
	}
}
function setRisultatiHide(){
	clearInterval( resultFadeOut );
	$("#ricercheRisultati").fadeOut("slow");
	$("#brandFormBox select").show();
	resultFadeOut = null;
	fadeOutTimer = 0;
}

function hideflash(){
	/* hide all flash in the page */
	flash = document.getElementsByTagName('object');
	for (var i = 0; i < flash.length; i++)
		flash[i].style.visibility = 'hidden';
}
function showflash(){
	/* show all flash in the page */
	flash = document.getElementsByTagName('object');
	for (var i = 0; i < flash.length; i++)
		flash[i].style.visibility = 'visible';
}

function showHideDescription(oSelect){
	var els = oSelect.options;
	for(var i=0,desc,status;i<els.length;i++){
		desc = document.getElementById(oSelect.name+"Desc_"+els[i].value);
		if(desc){
			status = i==oSelect.selectedIndex?'':'none';
			desc.style.display = status;
		}
	}
}

function checkPaymentForm(frm){
	if( isEmpty( frm.ePaymentAmount.value ) ){
		alert("Attenzione\nČ necessario inserire tutte le informazioni.\nCompilare campo");
		frm.ePaymentAmount.focus();
		return false;
	}
	if( frm.ePaymentType.options[frm.ePaymentType.selectedIndex].value==0 ){
		alert("Attenzione\nČ necessario inserire tutte le informazioni.\nCompilare campo");
		frm.ePaymentType.focus();
		return false;
	}
}

function checkCustomForm(frm){
	if(frm){
		var els = frm.elements;
		for(var i=0;i<els.length;i++){
			if( els[i].name && els[i].name.search(/^\*/)!=-1 && isEmpty(els[i].value) ){
				alert("Attenzione\nCompilare campo");
				els[i].focus();
				return false;
			}
		}
	}
	return true;
}

function resizeIframe(objID,h){
	var helpFrame = $("#" + objID);
	helpFrame.height(h+35);
	return h;
}
