/*********************************** BROWSER DETECT ***********************************/
function BrowserDetect() {
	var ua = navigator.userAgent.toLowerCase();
	
	// browser engine name
	this.isGecko       = (ua.indexOf('gecko') != -1 && ua.indexOf('safari') == -1);
	this.isAppleWebKit = (ua.indexOf('applewebkit') != -1);
	
	// browser name
	this.isKonqueror   = (ua.indexOf('konqueror') != -1); 
	this.isSafari      = (ua.indexOf('safari') != - 1);
	this.isOmniweb     = (ua.indexOf('omniweb') != - 1);
	this.isOpera       = (ua.indexOf('opera') != -1); 
	this.isIcab        = (ua.indexOf('icab') != -1); 
	this.isAol         = (ua.indexOf('aol') != -1); 
	this.isIE          = (ua.indexOf('msie') != -1 && !this.isOpera && (ua.indexOf('webtv') == -1) ); 
	this.isMozilla     = (this.isGecko && ua.indexOf('gecko/') + 14 == ua.length);
	this.isFirebird    = (ua.indexOf('firebird/') != -1);
	this.isNS          = ( (this.isGecko) ? (ua.indexOf('netscape') != -1) : ( (ua.indexOf('mozilla') != -1) && !this.isOpera && !this.isSafari && (ua.indexOf('spoofer') == -1) && (ua.indexOf('compatible') == -1) && (ua.indexOf('webtv') == -1) && (ua.indexOf('hotjava') == -1) ) );
	
	// spoofing and compatible browsers
	this.isIECompatible = ( (ua.indexOf('msie') != -1) && !this.isIE);
	this.isNSCompatible = ( (ua.indexOf('mozilla') != -1) && !this.isNS && !this.isMozilla);
	
	// rendering engine versions
	this.geckoVersion = ( (this.isGecko) ? ua.substring( (ua.lastIndexOf('gecko/') + 6), (ua.lastIndexOf('gecko/') + 14) ) : -1 );
	this.equivalentMozilla = ( (this.isGecko) ? parseFloat( ua.substring( ua.indexOf('rv:') + 3 ) ) : -1 );
	this.appleWebKitVersion = ( (this.isAppleWebKit) ? parseFloat( ua.substring( ua.indexOf('applewebkit/') + 12) ) : -1 );
	
	// browser version
	this.versionMinor = parseFloat(navigator.appVersion);
	
	// correct version number
	if (this.isGecko && !this.isMozilla) {
		this.versionMinor = parseFloat( ua.substring( ua.indexOf('/', ua.indexOf('gecko/') + 6) + 1 ) );
	}
	else if (this.isMozilla) {
		this.versionMinor = parseFloat( ua.substring( ua.indexOf('rv:') + 3 ) );
	}
	else if (this.isIE && this.versionMinor >= 4) {
		this.versionMinor = parseFloat( ua.substring( ua.indexOf('msie ') + 5 ) );
	}
	else if (this.isKonqueror) {
		this.versionMinor = parseFloat( ua.substring( ua.indexOf('konqueror/') + 10 ) );
	}
	else if (this.isSafari) {
		this.versionMinor = parseFloat( ua.substring( ua.lastIndexOf('safari/') + 7 ) );
	}
	else if (this.isOmniweb) {
		this.versionMinor = parseFloat( ua.substring( ua.lastIndexOf('omniweb/') + 8 ) );
	}
	else if (this.isOpera) {
		this.versionMinor = parseFloat( ua.substring( ua.indexOf('opera') + 6 ) );
	}
	else if (this.isIcab) {
		this.versionMinor = parseFloat( ua.substring( ua.indexOf('icab') + 5 ) );
	}
	
	this.versionMajor = parseInt(this.versionMinor); 
	
	// dom support
	this.isDOM1 = (document.getElementById);
	this.isDOM2Event = (document.addEventListener && document.removeEventListener);
	
	// css compatibility mode
	this.mode = document.compatMode ? document.compatMode : 'BackCompat';
	
	// platform
	this.isWin    = (ua.indexOf('win') != -1);
	this.isWin32  = (this.isWin && ( ua.indexOf('95') != -1 || ua.indexOf('98') != -1 || ua.indexOf('nt') != -1 || ua.indexOf('win32') != -1 || ua.indexOf('32bit') != -1 || ua.indexOf('xp') != -1) );
	this.isMac    = (ua.indexOf('mac') != -1);
	this.isUnix   = (ua.indexOf('unix') != -1 || ua.indexOf('sunos') != -1 || ua.indexOf('bsd') != -1 || ua.indexOf('x11') != -1)
	this.isLinux  = (ua.indexOf('linux') != -1);
	
	// specific browser shortcuts
	this.isNS4x = (this.isNS && this.versionMajor == 4);
	this.isNS40x = (this.isNS4x && this.versionMinor < 4.5);
	this.isNS47x = (this.isNS4x && this.versionMinor >= 4.7);
	this.isNS4up = (this.isNS && this.versionMinor >= 4);
	this.isNS6x = (this.isNS && this.versionMajor == 6);
	this.isNS6up = (this.isNS && this.versionMajor >= 6);
	this.isNS7x = (this.isNS && this.versionMajor == 7);
	this.isNS7up = (this.isNS && this.versionMajor >= 7);
	this.isIE4x = (this.isIE && this.versionMajor == 4);
	this.isIE4up = (this.isIE && this.versionMajor >= 4);
	this.isIE5x = (this.isIE && this.versionMajor == 5);
	this.isIE55 = (this.isIE && this.versionMinor == 5.5);
	this.isIE5up = (this.isIE && this.versionMajor >= 5);
	this.isIE6x = (this.isIE && this.versionMajor == 6);
	this.isIE6up = (this.isIE && this.versionMajor >= 6);
	this.isIE4xMac = (this.isIE4x && this.isMac);
}



/*********************************** POPUP CHE SI APRE AL CENTRO DELLO SCHERMO ***********************************/
function openWin(url, name, w, h, options){
	var browser = new BrowserDetect();
	if(browser.isSafari){
		w = w + 10;
		h = h + 5;
	}
	
	var centerwidth=Math.floor((screen.width/2)-(w/2));
	var centerheight= Math.floor((screen.height/2)-(h/2));
	
	if(options!='') options = ',' + options;
	popz = window.open(dUrl + url, name, 'width=' + w + ',height=' + h + ',top=' + centerheight + ',left=' + centerwidth + options)
	popz.focus();
}


/*********************************** TRIM as PHP ***********************************/
function trim(s){ 
	s = s.replace(/^\s*/,'').replace(/\s*$/, ''); 
	return s; 
}


function makeAlertFocus(msg, field){
	alert(msg);
	if(field.focus) field.focus();
	return false;
}


/*********************************** RICAVA L'ESTENSIONE DI UN FILE ***********************************/
function findExtension(filePath){
	filePath = trim(filePath.substring(filePath.lastIndexOf(".")+1));
	
	return filePath;
}


/*********************************** LINK INSERITO DA VISUAL EDITOR PER APRIRE UN IMMAGINE ***********************************/
function openImg(id, name, w, h){
	var browser = new BrowserDetect();
	if(browser.isSafari){
		w = w + 10;
		h = h + 5;
	}
	s = 'no';
	
	if(parseInt(w) > 1000){
		w = 1000;
		s = 'yes';
	}
	
	if(parseInt(h) > 750){
		h = 750;
		s = 'yes';
	}
	
	openWin("/popupImg.php?idM="+id, "img"+name, w, h, 'scrollbars=' + s)
}

/*********************************** LINK INSERITI DA VISUAL EDITOR ***********************************/
function goToLink(qString){
	add = '';
	if(typeof(isPreview) != 'undefined' && trim(isPreview)!='')
		add = '&isPreview=' + isPreview;
	
	location.href = dUrl + "/index.php?sid=" + sid + "&" + qString + add;
}

function goToPopup(qString, name){
	add = '';
	if(typeof(isPreview) != 'undefined' && trim(isPreview)!='')
		add = '&isPreview=' + isPreview;
	
	openWin("/popup.php?sid=" + sid + "&" + qString + add, name, 600, 610, 'scrollbars=yes')
}



/*********************************** FLASH ***********************************/
function documentWrite(code) { document.write(code) }


/*********************************** HOVER ***********************************/
$(document).ready(function() {
	$('.over').each(function() {
		//Preload Images
		this.n = new Image()
		this.h = new Image()
		this.n.src = this.src
		this.h.src = this.src.replace(/\.([^\.]*)$/,"_over.$1")
	})
	$('.over').hover(
		function() { this.src = this.h.src },
		function() { this.src = this.n.src }
	)
})


/*********************************** LOGIN ***********************************/
function controlLogin(f) {
   	if (trim(f.username.value)=="") return makeAlertFocus("[ Inserire Username ]", f.username);
    
   	if (trim(f.pwd.value)=="") return makeAlertFocus("[ Inserire Password ]", f.pwd);
	
	return true;
}


/*********************************** CAMBIO PASSWORD ***********************************/
function controlChangePwd(f) {
   	if (trim(f.new_pwd.value)=="") return makeAlertFocus("[ Inserire 'Nuova Password' ]", f.new_pwd);
    if (trim(f.confirm_pwd.value)=="") return makeAlertFocus("[ Inserire 'Conferma Password' ]", f.confirm_pwd);
	
	//nuova e conferma password devono essere uguali
	if (trim(f.new_pwd.value) != trim(f.confirm_pwd.value)) return makeAlertFocus("[ I campi 'Nuova Password' e 'Conferma Password' non sono uguali. Si prega di ricontrollare ]", f.confirm_pwd);
  	
	//la nuova password NON deve essere uguale alla username
	if (trim(f.new_pwd.value) == trim(f.username.value)) return makeAlertFocus("[ La nuova password NON può essere uguale alla username ]", f.new_pwd);
	
	//La password deve essere minimo 8 caratteri e deve contentere almeno 1 carattere maiuscolo, 1 carattere minuscolo e 1 carattere numerico
	rePwd = /^(?=.{8,})(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).*$/;
	if(!rePwd.test(f.new_pwd.value)) return makeAlertFocus("[ La password deve essere minimo 8 caratteri e deve contentere almeno 1 carattere maiuscolo, 1 carattere minuscolo e 1 carattere numerico ]", f.new_pwd);
	
    return true;
}


/*********************************** REGISTRAZIONE ***********************************/
function controlReg(f){
	fieldRequired = new Array('nome', 'societa', 'email');
	labelRequired = new Array('Nome e cognome', 'Società', 'E-mail');
	
	for(i=0; i<fieldRequired.length;i++){
		if (trim(eval('f.' + fieldRequired[i] + '.value')) == "") return makeAlertFocus("[ Il campo " + labelRequired[i] + " è obbligatorio ]", eval('f.' + fieldRequired[i]));
	}
	
	// Controllo la mail
	var reEmail = /^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*[.][a-z]{2,4}$/i;
	isEmail = reEmail.test(f.email.value);
	if(!isEmail) return makeAlertFocus("[ La email inserita non è valida ]", f.email);
	
	if (trim(f.captcha.value)=="") return makeAlertFocus("[ Inserire codice di sicurezza ]", f.captcha);
			
	return true;
}


/*********************************** FORM DI CONTATTO ***********************************/
function controlContactForm(f){
	fieldRequired = new Array('nome', 'societa', 'email', 'message');
	labelRequired = new Array('Nome e cognome', 'Società', 'E-mail', 'Messaggio');
	
	for(i=0; i<fieldRequired.length;i++){
		if (trim(eval('f.' + fieldRequired[i] + '.value')) == "") return makeAlertFocus("[ Il campo " + labelRequired[i] + " è obbligatorio ]", eval('f.' + fieldRequired[i]));
	}
	
	// Controllo la mail
	var reEmail = /^[0-9a-z]([-_.]?[0-9a-z])*@[0-9a-z]([-.]?[0-9a-z])*[.][a-z]{2,4}$/i;
	isEmail = reEmail.test(f.email.value);
	if(!isEmail) return makeAlertFocus("[ La email inserita non è valida ]", f.email);
	
	if (trim(f.captcha.value)=="") return makeAlertFocus("[ Inserire codice di sicurezza ]", f.captcha);
	
	return true;
}


/*********************************** SEGNALA A UN AMICO ***********************************/
function checkSendToFriendForm(f){
	re = /^.+\@.+\..+$/;
	
	if(trim(f.your_name.value)=='') return makeAlertFocus("[ Il campo 'Il tuo nome' è obbligatorio ]", f.your_name);
	
	if(trim(f.your_email.value)=='') return makeAlertFocus("[ Il campo 'La tua e-mail' è obbligatorio ]", f.your_email);
	if(!re.test(f.your_email.value))  return makeAlertFocus("[ Il formato del campo 'La tua e-mail' è errato.\\nDeve essere del tipo: nome@dominio.xxx ]", f.your_email);
	
	if(trim(f.friend_email.value)=='') return makeAlertFocus("[ Il campo 'E-mail del tuo amico' è obbligatorio ]", f.friend_email);
	if(!re.test(f.friend_email.value))  return makeAlertFocus("[ Il formato del campo 'E-mail del tuo amico' è errato.\\nDeve essere del tipo: nome@dominio.xxx ]", f.friend_email);
	
	return true;
}


/*********************************** SETTARE/LEGGERE COOKIE ***********************************/
function setCookie(name, value, expdays) {   //memorizza il cookie
	var now = new Date();
	var exp = new Date(now.getTime() + (1000*60*60*24*expdays));
	document.cookie = name + "=" + escape(value) + ";" + "expires=" + exp.toGMTString() + ";" + "path=/";
}

function getCookie(name) {    //restituisce il cookie
	var cname = name + "=";
	var dc = document.cookie;
	if (dc.length > 0) {
	    var start = dc.indexOf(cname);
	    if (start != -1) {
	        start += cname.length;
	        var stop = dc.indexOf(";", start);
	        if (stop == -1) stop = dc.length;
	        return unescape(dc.substring(start,stop));
	    }
	}
	return null;
}

function changeStylesheet(){
	if(getCookie("stylesheetAGORA") == "agora") templateChange("agoraBIG");
		else  templateChange("agora");
}


/*********************************** CAMBIA FONT SIZE ***********************************/
function stylesheetSet(variation){
	if(!document.styleSheets){
		var ss = getAllSheets() //Opera
	}else{
		var ss = document.styleSheets; //Dom
	}
	
	if( !ss.length ) { 
		alert( 'Il tuo browser non è abilitato a cambiare i fogli di stile CSS' );
	}else{
		var l = document.getElementById("css_qxn"); 
        l.href = "/css/style.php?variationSIZE=" + variation;
	}
}

function stylesheetChange(variation){
	var max_var = 3;
	var min_var = -2;
	
	//controllo browser
	if(!document.styleSheets){
		var ss = getAllSheets() //Opera
	}else{
		var ss = document.styleSheets; //Dom
	}
	
	if( !ss.length ) { 
		alert( 'Il tuo browser non è abilitato a cambiare i fogli di stile CSS' );
	}else{
		if(actual_css_variation+variation <= max_var && actual_css_variation+variation >= min_var){
			css = "/css/style.php?variationSIZE=" + (actual_css_variation+variation);
			var l = document.getElementById("css_qxn"); 
        	l.href = css;
			setCookie("cssQXN", (actual_css_variation+variation), 365);
			actual_css_variation = actual_css_variation+variation;
		}
	}
}

function stylesheetReset(){
	//controllo browser
	if(!document.styleSheets){
		var ss = getAllSheets() //Opera
	}else{
		var ss = document.styleSheets; //Dom
	}
	
	if( !ss.length ) { 
		alert( 'Il tuo browser non è abilitato a cambiare i fogli di stile CSS' );
	}else{
		css = "/css/style.php?variationSIZE=0";
		var l = document.getElementById("css_qxn"); 
       	l.href = css;
		setCookie("cssQXN", 0, 365);
		actual_css_variation = 0;
	}
}

// Funzione per Opera
function getAllSheets(){
	if( document.getElementsByTagName ) {
		var Lt = document.getElementsByTagName('LINK');
		var St = document.getElementsByTagName('STYLE');
	} else {
		// browser minori - restituisce array vuoto
		return []; 
	}
	//per tutti i tag link ...
	for( var x = 0, os = []; Lt[x]; x++ ) {
		//controlla l'attributo rel per vedere se contiene 'style'
		if( Lt[x].rel ) {
			var rel = Lt[x].rel;
		} else if( Lt[x].getAttribute ) {
			var rel = Lt[x].getAttribute('rel');
		} else {
			var rel = '';
		}
		if(typeof(rel)=='string'&&rel.toLowerCase().indexOf('style')+1){
			//riempe la variabile os con i stylesheets linkati
			os[os.length] = Lt[x];
		}
	}
	//include anche tutti i tags style e restituisce l'array
	for( var x = 0; St[x]; x++ ) {
		os[os.length] = St[x];
	}
	return os;
}
