
function openPopUp(page, w, h) { 
	var height = h;
	var width = w;
	
	var str = "height=" + height + ",innerHeight=" + height;
	str += ",width=" + width + ",innerWidth=" + width;
	if (window.screen) {
	    	var ah = screen.availHeight - 30;
	    	var aw = screen.availWidth - 10;
	
	    	var xc = (aw - width) / 2;
	    	var yc = (ah - height) / 2;
	
	    	str += ",left=" + xc + ",screenX=" + xc;
	    	str += ",top=" + yc + ",screenY=" + yc;
	}
  	return window.open(page, "", str+",scrollbars=yes,resizable=yes");
}

function OpenPopup(page, w, h) {
	return openPopUp(page, w, h);
}

function OpenWithPopup(aElement, w, h) {
	if(aElement.href == null) return null;
	else {
		var page = aElement.href;
		//page = page.replace("index.php", "popup.php");
		//if(page.indexOf("popup.php") == -1) page = page.replace("?page", "popup.php?page");
		page = page.substring(page.lastIndexOf("/")+1);
		page = "popup;"+page;

		OpenPopup("http://www.webfantacalcio.it/" + page, w, h);
		return false;
	}
}

function compareDates(d1, d2) {
	if(d1.length != 16) return -2;
	if(d2.length != 16) return -3;
	
	var strd1 = d1.substring(6,10) + d1.substring(3,5) + d1.substring(0,2) + d1.substring(11,13) + d1.substring(14,16);
	var strd2 = d2.substring(6,10) + d2.substring(3,5) + d2.substring(0,2) + d2.substring(11,13) + d2.substring(14,16);

	if(strd1 < strd2) return -1;
	else if(strd1 > strd2) return 1;
	else return 0;
}


function checkInputEuro(inputeuro) {
	var len = inputeuro.value.length;
	var newstr = "";
	var foundpoint = false;
	for(var i=0; i<len; i++) {
		var last = inputeuro.value.charAt(i);
		if(last >= "0" && last <= "9")
			newstr += last;
		else if(last == "," || last == ".") {
			if(!foundpoint)	{
				newstr += ".";
				foundpoint = true;
			}
		}
	}
	inputeuro.value = newstr;
}


function initSearchForm(formid, inputname) {
	var formel = document.getElementById(formid);
	if(formel == null) return;

	//if(formel[inputname].value.length == 0) {
		formel.onsubmit = function() {
			if(formel[inputname].value.length == 0 || formel[inputname].value == "Cerca") {
				formel[inputname].focus();
				return false;
			}
			window.location = this.action + "&" + inputname + "=" + formel[inputname].value;
			return false;
		}
		
		if(formel[inputname].value.length == 0) formel[inputname].value = "Cerca";
		formel[inputname].onfocus = function() {
			if(formel[inputname].value == "Cerca") formel[inputname].value = "";
			this.select();
		}
		formel[inputname].onblur = function() {
			if(formel[inputname].value == "") formel[inputname].value = "Cerca";
		}
	//}
	//else {
		//formel[inputname].onfocus = function() {
		//	this.select();
		//}
	//}
}


function isEmail(str) {
	return (str.search(/^[a-zA-Z0-9][a-zA-Z0-9_\.\-]*@[a-zA-Z0-9]*\.[a-zA-Z]{2}[a-zA-Z]{0,2}$/)==0);
}


function isDate(str) {
	var arr = str.split("/");
	if(arr.length != 3) return false;
	if(isNaN(arr[0])) return false;
	if(arr[0]<1 || arr[0]>31) return false;
	if(isNaN(arr[1])) return false;
	if(arr[1]<1 || arr[1]>12) return false;
	if(isNaN(arr[2])) return false;
	if(arr[2]<1900 || arr[2]>2100) return false;
	return true;
}

function updateDate(form, name) {
	var gg = form[name+"_gg"].value;
	var mm = (form[name+"_mm"].options[form[name+"_mm"].selectedIndex].value);
	var aa = form[name+"_aa"].value;
	
	if(gg.length == 1) gg = "0"+gg;
	if(mm.length == 1) mm = "0"+mm;
	
	form[name].value = gg + "/" + mm + "/" + aa;
}

function isEmptyDate(form, name) {
	if(form[name+"_gg"].value.length == 0) {
		form[name+"_gg"].focus();
		return true;
	}
	if(form[name+"_mm"].selectedIndex == 0) {
		form[name+"_mm"].focus();
		return true;
	}
	if(form[name+"_aa"].value.length == 0) {
		form[name+"_aa"].focus();
		return true;
	}
	return false;
}

function getDateNow(withTime) {
	if(withTime == null) withTime = true;
	
	var now = new Date();
	
	var gg = "" + now.getDate();
	var mm = "" + (now.getMonth()+1);
	var aa = now.getYear();
	
	if(gg.length == 1) gg = "0"+gg;
	if(mm.length == 1) mm = "0"+mm;
	if ((navigator.appName == "Microsoft Internet Explorer") && (anno < 2000)) aa = "19" + aa;
	if (navigator.appName == "Netscape") aa = 1900 + aa;
	
	var hh = "" + now.getHours();
	var minutes = "" + now.getMinutes()
	if(hh.length == 1) hh = "0"+hh;
	if(minutes.length == 1) minutes = "0"+minutes;
	
	var dnow = gg + "/" + mm + "/" + aa;
	if(withTime) dnow += " " + hh + ":" + minutes;
	
	return dnow;
}

function getSubmitButton(form) {
	var buttonsubmit = { disabled: false };
	$("input", form).each(function() {
		if($(this).attr("type") == "submit") buttonsubmit = this;
	});
	return buttonsubmit;
}


function DisableSubmitButton(form) {
	getSubmitButton(form).disabled = true;
}

function EnableSubmitButton(form) {
	getSubmitButton(form).disabled = false;
}

function GetFileExtension(str) {
	return str.substr(str.length - 3).toLowerCase();
}


function checkLoginForm(form) {
	if(form.username.value.length == 0) {
		$(form.username).css("background", "#CF24B4");
		setTimeout(function() {
			$(form.username).css("background", "");
			setTimeout(function() {
				$(form.username).css("background", "#CF24B4");
				setTimeout(function() {
					$(form.username).css("background", "");
					form.username.focus();
				}, 100);
			}, 100);
		}, 100);
		return false;
	}
	if(form.password.value.length == 0) {
		$(form.password).css("background", "#CF24B4");
		setTimeout(function() {
			$(form.password).css("background", "");
			setTimeout(function() {
				$(form.password).css("background", "#CF24B4");
				setTimeout(function() {
					$(form.password).css("background", "");
					form.password.focus();
				}, 100);
			}, 100);
		}, 100);
		return false;
	}
	DisableSubmitButton(form);
	return true;
}

function TogglePanel(a, panid, withSlide) {
	if(withSlide == null) withSlide = true;
	else withSlide = false;
	
	if(withSlide) $("#"+panid).slideToggle("fast");
	else $("#"+panid).toggle();
	$(a).toggleClass('clicked');
	$(a).parent().toggleClass('clicked');
	$(a).blur();
}

function SelectGetValue(select) {
	return select.options[select.selectedIndex].value;
}

function SelectSetValue(select, value) {
	for(var i=0; i<select.options.length; i++)
		select.options[i].selected = (select.options[i].value == value);
}




var _OpenSubMenuInAction = false;
var _OpenSubMenuTimer = null;
function OpenSubMenu(aEl) {
	$(".open-sub-elements", aEl).show();
	//_OpenSubMenuTimer == null;
	//$(".open-sub-elements", aEl).slideDown();
	/*$("a", aEl).each(function(i) {
		if(i==0) {
			$(this).addClass("active");
		}
	});*/
}
function CloseSubMenu(aEl) {
	//_OpenSubMenuTimer = setTimeout(function() {
	//	if(_OpenSubMenuTimer == null) return;
		$(".open-sub-elements", aEl).hide();
	//}, 1000);
	
	/*$("a", aEl).each(function(i) {
		if(i==0) {
			$(this).removeClass("active");
		}
	});*/
}




function AddToFriend(id, aElem) {
	if(confirm("Vuoi aggiungere l'utente ai tuoi amici?")) {
		if(aElem != null) $(aElem).html("In corso...");
		$.get("add-to-friend;id="+id, function(data) {
			if(data == "ok") {
				if(aElem != null) $(aElem).slideUp();
				if(aElem != null) $(".e-amico", $(aElem).parent().parent().parent()).html("Tuo amico");
				if(aElem == null) alert("L'utente e' stato aggiunto ai tuoi amici!");
			}
			else alert("Errore: Impossibile aggiungere l'utente ai tuoi amici.");
		});
	}
}

function DelFriend(id, aElem) {
	if(confirm("Vuoi davvero rimuovere l'utente dai tuoi amici?")) {
		if(aElem != null) $(aElem).html("In corso...");
		$.get("add-to-friend;remove&id="+id, function(data) {
			if(data == "ok") {
				if(aElem != null) $(aElem).parent().parent().slideUp();
				if(aElem == null) alert("L'utente e' stato rimosso dai tuoi amici!");
			}
			else alert("Errore: Impossibile rimuovere l'utente dai tuoi amici.");
		});
	}
}


function checkNuoveNotifiche() {
	var lastNNot = parseInt($("#num-notifiche").html());
	
	$.get("index.php?page=gestione-notifiche&check=true", function(data) {
		if(!isNaN(data)) {
			var nNot = parseInt(data);
			$("#num-notifiche").html("" + nNot);
			if(nNot > 0) $("#num-notifiche").parent().removeClass("gray");
			else $("#num-notifiche").parent().addClass("gray");
			//lastNNot == 0 && 
			if(nNot > lastNNot) new Baloon("Hai una nuova notifica", '<a href="gestione-notifiche;">Leggi notifiche &raquo;</a>');
			if(nNot > 0) {
				var pair = false;
				var _countEv = 0;
				var _evidenzia = function() {
					if(!pair) $("#num-notifiche").parent().parent().fadeTo("slow", 0.4);
					else $("#num-notifiche").parent().parent().fadeTo("slow", 1);
					pair = !pair;
					_countEv++;
					if(_countEv < 100) setTimeout(_evidenzia, 600);
				}
				
				setTimeout(_evidenzia, 600);
			}
		}
	});
}

function checkNuoviMessaggi() {
	var lastNNot = parseInt($("#num-posta").html());
	
	$.get("index.php?page=gestione-messaggi-privati&check=true", function(data) {
		if(!isNaN(data)) {
			var nNot = parseInt(data);
			$("#num-posta").html("" + nNot);
			if(nNot > 0) $("#num-posta").parent().removeClass("gray");
			else $("#num-posta").parent().addClass("gray");
			//lastNNot == 0 && 
			if(nNot > lastNNot) new Baloon("Hai una nuovo messaggio privato", '<a href="gestione-messaggi-privati;">I tuoi messaggi privati &raquo;</a>');
			if(nNot > 0) {
				var pair = false;
				var _countEv = 0;
				var _evidenzia = function() {
					if(!pair) $("#num-posta").parent().parent().fadeTo("slow", 0.4);
					else $("#num-posta").parent().parent().fadeTo("slow", 1);
					pair = !pair;
					_countEv++;
					if(_countEv < 100) setTimeout(_evidenzia, 600);
				}
				
				setTimeout(_evidenzia, 600);
			}
		}
	});
}

function CountdownOneSecond(temporimanente) {
	if(temporimanente == "Scaduta") return temporimanente;
	if(temporimanente.charAt(temporimanente.length-1) != "s") return temporimanente;
	
	temporimanente = temporimanente.replace(/g/, "");
	temporimanente = temporimanente.replace(/h/, "");
	temporimanente = temporimanente.replace(/m/, "");
	temporimanente = temporimanente.replace(/s/, "");
	
	var t = temporimanente.split(" ");
	var giorni = ore = minuti = secondi = 0;
	if(t.length == 1) secondi = parseInt(t[0]);
	else if(t.length == 2) {
		minuti = parseInt(t[0]);
		secondi = parseInt(t[1]);
	}
	else if(t.length == 3) {
		ore = parseInt(t[0]);
		minuti = parseInt(t[1]);
		secondi = parseInt(t[2]);
	}
	else if(t.length == 4) {
		giorni = parseInt(t[0]);
		ore = parseInt(t[1]);
		minuti = parseInt(t[2]);
		secondi = parseInt(t[3]);
	}
	
	secondi--;
	if(secondi < 0) {
		secondi = 59;
		minuti--;
		if(minuti < 0) {
			minuti = 59;
			ore--;
			if(ore < 0) {
				ore = 23;
				giorni--;
				if(giorni < 0) return "Scaduta";
			}
		}
	}
	
	var nuovotempo = "";
	if(giorni > 0) nuovotempo += giorni + "g ";
	if(giorni > 0 || ore > 0) nuovotempo += ore + "h ";
	if(giorni > 0 || ore > 0 || minuti > 0) nuovotempo += minuti + "m ";
	nuovotempo += secondi + "s";
	
	return nuovotempo;
}

function AggiornaCountdown() {
	setInterval(function() {
		$(".countdown").each(function(i) {
			$(this).html(CountdownOneSecond($(this).html()));
		});
	}, 1000);
}



function InitAutoGrow(elems) {
	if($(elems).size() == 0) return;
	
	$(elems).autogrow({
		minHeight: 0,
		lineHeight: 16,
		maxHeight: 250
	});

	var SCRIVI_MESSAGGIO = "Scrivi qui il tuo messaggio...";
	$(elems).each(function() {
		this.value = SCRIVI_MESSAGGIO;
		this.onfocus = function() {
			if(this.value == SCRIVI_MESSAGGIO) this.value = "";
			$(this).css("color", "black");
			$(".autogrow-submit", $(this).parent()).slideDown("fast");
		}
		this.onblur = function() {
			if(this.value == "") {
				this.value = SCRIVI_MESSAGGIO;
				$(this).css("color", "gray");
				$(".autogrow-submit", $(this).parent()).slideUp("fast");
			}
		}
	});
}


function EliminaMessaggioBachecha(lega, message, entryElement) {
	$.get("lega-dettagli;id=" + lega + "&del-bacheca=ok&message=" + message, function(data) {});
	if(entryElement != null) $(entryElement).slideUp();
}

function BachecaLegaAddMessage(corpo) {
	
}


function BachecaLegaAddMessageSubmit(input) {
	//var corpo = $(".autogrow", $(this).parent().parent())[0].value;
	//BachecaLegaAddMessage(corpo);
}


$(function(){
	$("div.info, div.warning, div.error").corner("round 10px");
	$("div.home-box").corner("round 10px");
	$("div.home-box h3").corner("top");
	setInterval(function() {
		checkNuoveNotifiche();
	}, 30000);
	setInterval(function() {
		checkNuoviMessaggi();
	}, 45000);	
	checkNuoveNotifiche();
	checkNuoviMessaggi();
	AggiornaCountdown();


	InitAutoGrow("textarea.autogrow");
});