var http_base='http://www.aclegnagosalus.it/';
//var http_base='http://localhost/aclegnago/';
var dtCh= ".";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function tick() {//google v.2 fix
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)	
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("La data deve essere nel formato gg.mm.aaaa")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Attenzione, mese non valido")
		return false
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Attenzione, giorno non valido")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Attenzione, anno non valido")
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Attenzione, data non valida")
		return false
	}
	return true;
}



function new_championship(sid){
	r=Math.random(10000);
	$('#action_box').load(http_base+'management/champmanager.php',{'action':'add_championship','perform':'read','sid':sid,'r':r});
}

function save_championship(mode,sid){
	year=document.getElementById("anno").value
	desc=document.getElementById("descrizione").value;
	pp=document.getElementById("primapagina").checked;
	if (pp==true) pp=1;
	else pp=0;
	r=Math.random(10000);
	if (mode==1) {
		// salvo nuovo campionato
		$('#action_box').load(http_base+'management/champmanager.php',{'action':'add_championship','sid':sid,'perform':'write','anno':year,'descrizione':desc,'primapagina':pp,'r':r});
	}	else {
			// aggiorno campionato esistente
			idc=document.getElementById("id_campionato").value;
			$('#action_box').load(http_base+'management/champmanager.php',{'action':'modify_championship','sid':sid,'perform':'write','id_campionato':idc,'anno':year,'primapagina':pp,'descrizione':desc,'r':r});
		}
}

function modify_championship(id,sid){
	r=Math.random(10000);
	$('#action_box').load(http_base+'management/champmanager.php',{'action':'modify_championship','perform':'read','id_campionato':id,'sid':sid,'r':r});
}

function new_team(sid){
	r=Math.random(10000);
	$('#action_box').load(http_base+'management/champmanager.php',{'action':'add_team','perform':'read','sid':sid,'r':r});
}

function save_team(mode,sid){
	desc=document.getElementById("descrizione").value;
	idc	= document.getElementById('id_campionato');
	idc	= idc.options[idc.selectedIndex].value;
	act=document.getElementById("attiva").checked;
	if (act==true) act=1;
	else act=0;
	r=Math.random(10000);
	if (mode==1) {
		// salvo nuovo team
		$('#action_box').load(http_base+'management/champmanager.php',{'action':'add_team','sid':sid,'perform':'write','id_campionato':idc,'descrizione':desc,'checked':act,'r':r});
	}	else {
			// aggiorno team esistente
			ids=document.getElementById("id_squadra").value;
			$('#action_box').load(http_base+'management/champmanager.php',{'action':'modify_team','sid':sid,'perform':'write','id_campionato':idc,'id_squadra':ids,'descrizione':desc,'checked':act,'r':r});
		}
}

function arrayIndexOf(array, search) {
	var indice; //contatore
	for (indice in array) {
		if (array[indice] == search)
			return true;
	}	
	return false;
}

function save_day(mode,sid){
	a_home=		new Array();	
	a_visitors=	new Array();
	a_gol_home=	new Array();
	a_gol_visitors=new Array();
	a_stato= 	new Array();
	a_note= 	new Array();
	i=0;
	while ((h=document.getElementById("home["+i+"]"))!=null) {
		v=document.getElementById("visitors["+i+"]");
		// i casi sono molteplici
		// generalmente entrambe le squadre devono avere id diverso da -1, altrimenti la riga è considerata vuota e viene saltata
		if ((h.value!=-1)||(v.value!=-1)) {			
			// se una squadra non gioca con nessuna altra squadra (quindi solo uno tra home e visitors è -1) si può presumere che tale squadra abbia turno di riposo
			
			// se entrambe le squadre hanno lo stesso id, c'è un errore (squadra che gioca contro se stessa)
			if (h.value==v.value){
				alert('attenzione, una squadra non può giocare contro se stessa');
				return;
			}
			
			// se una squadra è già stata utilizzata, non può venir inserita nuovamente
			
			if (h.value!=-1) {
				// controllo home tra gli home
				hh=arrayIndexOf(a_home,h.value);
				// controllo home tra i visitors
				hv=arrayIndexOf(a_visitors,h.value);
			}	else {
					hh=false;
					hv=false;
				}
			if (v.value!=-1) {
				// controllo visitors tra i visitors
				vv=arrayIndexOf(a_visitors,v.value);
				// controllo i visitors tra gli home
				vh=arrayIndexOf(a_home,v.value);
			}	else {
					vv=false;
					vh=false;
				}
			if (hh|hv|vh|vv) {
				alert ('attenzione, una squadra è stata utilizzata più volte nella stessa giornata');
				return;
			}
			a_home.push(h.value);
			a_visitors.push(v.value);
			if (mode==2) {
				//sono in modifica
				gh=document.getElementById("gol_home["+i+"]");
				gv=document.getElementById("gol_visitors["+i+"]");
				st=document.getElementById("stato["+i+"]");
				nt=document.getElementById("note["+i+"]");
				if (gh.value=='') gh.value=0;
				if (gv.value=='') gv.value=0;
				a_gol_home.push(gh.value);
				a_gol_visitors.push(gv.value);
				a_stato.push(st.value);
				a_note.push(nt.value);
			}
		}
		i++;
	}
	// ho le righe,mi ricavo i dati rimanenti ed invio
	a_data_a	= document.getElementById("data_a").value;
	a_ora_a		= document.getElementById("ora_a").value;
	if (!isDate(a_data_a)){
		alert ("data di andata non valida");
		return;
	}
	if (mode==1){
		//solo se nuovo inserimento
		a_data_r	= document.getElementById("data_r").value;
		a_ora_r		= document.getElementById("ora_r").value;
		if (!isDate(a_data_r)){
			alert ("data di ritorno non valida");
			return;
		}
	} else idg			=document.getElementById("id_giornata").value;
	
	idc = document.getElementById('id_campionato');
	idc	= idc.options[idc.selectedIndex].value;
	if (mode==1) $('#action_box').load(http_base+"management/champmanager.php",{'sid':sid,"home[]":a_home,"visitors[]":a_visitors,"action":"add_day",'perform':'write','data_a':a_data_a,'data_r':a_data_r,'ora_a':a_ora_a,'ora_r':a_ora_r,'id_campionato':idc});
	else $('#action_box').load(http_base+"management/champmanager.php",{'sid':sid,"gol_home[]":a_gol_home,"gol_visitors[]":a_gol_visitors,"stato[]":a_stato,"note[]":a_note,"home[]":a_home,"visitors[]":a_visitors,"action":"modify_day",'perform':'write','data_a':a_data_a,'ora_a':a_ora_a,'id_campionato':idc,"id_giornata":idg});
}

function modify_day(id,sid){
	r=Math.random(10000);
	$('#action_box').load(http_base+'management/champmanager.php',{'sid':sid,'action':'modify_day','perform':'read','id_giornata':id,'r':r});
}

function modify_team(id,sid){
	r=Math.random(10000);
	$('#action_box').load(http_base+'management/champmanager.php',{'sid':sid,'action':'modify_team','perform':'read','id_squadra':id,'r':r});
}

function abort_operation(sid){
	r=Math.random(10000);
	$('#action_box').load(http_base+'management/champmanager.php',{'sid':sid,'action':'null','r':r});
}

function new_day(sid){
	r=Math.random(10000);
	$('#action_box').load(http_base+'management/champmanager.php',{'sid':sid,'action':'add_day','perform':'read','r':r});
}

function list_championship(sid){
	r=Math.random(10000);
	$('#action_box').load(http_base+'management/champmanager.php',{'sid':sid,'action':'list_championship','r':r});
}

function change_champ(){
	r=Math.random(10000);
	idc = document.getElementById('champ_selector');
	idc	= idc.options[idc.selectedIndex].value;
	$('#news_block').load(http_base+'contents.php',{'sezione':'classifica','id_campionato':idc,'r':r});
}

function change_team(){
	r=Math.random(10000);
	idt = document.getElementById('team_selector');
	idt	= idt.options[idt.selectedIndex].value;
	$('#news_block').load(http_base+'contents.php',{'sezione':'giocatori','stagione':idt,'r':r});
}

function list_teams(sid){
	r=Math.random(10000);
	$('#action_box').load(http_base+'management/champmanager.php',{'sid':sid,'action':'list_teams','r':r});
}

function list_inactive_teams(sid){
	r=Math.random(10000);
	$('#action_box').load(http_base+'management/champmanager.php',{'sid':sid,'action':'list_inactive_teams','r':r});
}

function list_days(sid){
	r=Math.random(10000);
	$('#action_box').load(http_base+'management/champmanager.php',{'sid':sid,'action':'list_days','r':r});
}

function refilter_list_days(sid){
	r=Math.random(10000);
	idc = document.getElementById('id_campionato');
	idc	= idc.options[idc.selectedIndex].value;
	$('#action_box').load(http_base+'management/champmanager.php',{'sid':sid,'action':'list_days','id_campionato':idc,'r':r});
}

function new_penalty(sid){
	r=Math.random(10000);
	$('#action_box').load(http_base+'management/champmanager.php',{'sid':sid,'action':'add_penalty','perform':'read','r':r});
}

function list_penalty(sid){
	r=Math.random(10000);
	$('#action_box').load(http_base+'management/champmanager.php',{'sid':sid,'action':'list_penalty','r':r});
}

function modify_penalty(id,sid){
	r=Math.random(10000);
	$('#action_box').load(http_base+'management/champmanager.php',{'sid':sid,'action':'modify_penalty','perform':'read','id_penalty':id,'r':r});
}

function delete_penalty(id,sid){
	if (confirm('attenzione, cancellare la penalizzazione?')){
		r=Math.random(10000);
		$('#action_box').load(http_base+'management/champmanager.php',{'sid':sid,'action':'delete_penalty','id_penalty':id,'r':r});
	}
}

function save_penalty(mode,sid){
	idc = document.getElementById('id_campionato');
	idc	= idc.options[idc.selectedIndex].value;
	ids = document.getElementById('id_squadra');
	ids	= ids.options[ids.selectedIndex].value;
	v   = document.getElementById("valore").value;
	n   = document.getElementById("note").value;
	if (v==''){
		alert("attenzione, valore penalizzazione non inserito");
		return;
	}
	if (ids==-1){
		alert("attenzione, squadra non selezionata");
		return;
	}
	r=Math.random(10000);
	if (mode==1) {
		// salvo nuovo penalty
		$('#action_box').load(http_base+'management/champmanager.php',{'sid':sid,'action':'add_penalty','perform':'write','id_campionato':idc,'id_squadra':ids,'valore':v,'note':n,'r':r});
	}	else {
			// aggiorno team esistente
			idp=document.getElementById("id_penalty").value;
			$('#action_box').load(http_base+'management/champmanager.php',{'sid':sid,'action':'modify_penalty','perform':'write','id_penalty':idp,'id_campionato':idc,'id_squadra':ids,'valore':v,'note':n,'r':r});
		}
}

function my_tiny_init(){
tinyMCE.init({
		// General options
		entity_encoding : "numeric",
		mode : "textareas",
		theme : "advanced",
		plugins : "pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,wordcount,advlist,autosave",

		// Theme options
		theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
		theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
		theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
		theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak,restoredraft",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resizing : true,
		
		font_size_style_values : "8px,10px,12px,14px,18px",

		// Example content CSS (should be your site CSS)
		content_css : "css/content.css",

		// Drop lists for link/image/media/template dialogs
		template_external_list_url : "lists/template_list.js",
		external_link_list_url : "lists/link_list.js",
		external_image_list_url : "lists/image_list.js",
		media_external_list_url : "lists/media_list.js",

		// Style formats
		style_formats : [
			{title : 'Bold text', inline : 'b'},
			{title : 'Red text', inline : 'span', styles : {color : '#ff0000'}},
			{title : 'Red header', block : 'h1', styles : {color : '#ff0000'}},
			{title : 'Example 1', inline : 'span', classes : 'example1'},
			{title : 'Example 2', inline : 'span', classes : 'example2'},
			{title : 'Table styles'},
			{title : 'Table row 1', selector : 'tr', classes : 'tablerow1'}
		],

		// Replace values for the template plugin
		template_replace_values : {
			username : "Some User",
			staffid : "991234"
		}
	});
}

function get_news_list(sid){
	r=Math.random(10000);
	$('#action_box').load(http_base+'management/champmanager.php',{'sid':sid,'action':'list_news','r':r});
}

function get_news(id_news,sid){
	r=Math.random(10000);
	$('#action_box').load(http_base+'management/champmanager.php',{'id_news':id_news,'sid':sid,'action':'get_news','r':r},function(){my_tiny_init()});
}

function add_news(sid){
	r=Math.random(10000);
	$('#action_box').load(http_base+'management/champmanager.php',{'sid':sid,'action':'add_news','r':r},function(){my_tiny_init()});
}

function read_news(id){
	r=Math.random(10000);
	$('#news_block').load(http_base+'contents.php',{'sezione':'home','start':id,'r':r},function(){$('html, body').animate({scrollTop:0}, 'slow');});
}

function view_gallery(sid){
	r=Math.random(10000);
	$('#action_box').load(http_base+'management/champmanager.php',{'sid':sid,'action':'view_gallery','r':r});
}

function update_img_des(img_name,sid){
	r=Math.random(10000);
	desc=document.getElementById(img_name).value;
	$.post(http_base+'management/champmanager.php',{'name':img_name,'sid':sid,'action':'update_img_description','desc':desc,'r':r},function(data){alert(data)});
}

function delete_image(name,id){
	r=Math.random(10000);
	$('#action_box').load(http_base+'management/champmanager.php',{'img_name':name,'sid':id,'action':'delete_image','r':r});
}

function save_news(id_news,sid){
	r=Math.random(10000);
	//ta=document.getElementById("news").value;
	ta=tinyMCE.activeEditor.getContent();
	$('#action_box').load(http_base+'management/champmanager.php',{'id_news':id_news,'sid':sid,'action':'save_news','news':ta,'r':r},function(){alert("dati salvati")});
}

gal_active=false;
function get_sections(id){
	r=Math.random(10000);
	if (id=='gallery') {
		gal_active=true;
		do_the_gallery(0);
	}
	else {
		if (gal_active){
			gal_active=false;
			$('#sp1').load('sponsor.php',function(){$('#sp1').animate({"height":"325px"},500);});
		}
		if (id=='sponsor') $('#news_block').load(http_base+'sponsor.php',{'normal_view':1,'r':r});
		else $('#news_block').load(http_base+'contents.php',{'sezione':id,'r':r});
	}
}

function go_to_img(path,desc){
	gal_active=true;
	do_the_gallery_direct(0,path,desc);
}

function only_digits(e){
var keynum;

	if (window.event) {
		keynum = e.keyCode
	}
	else if (e.which) {
		keynum = e.which
	}
	if ((keynum==9) || (keynum==8) || ((keynum>=48) && (keynum<=57)))
		e.returnValue=true;
	else e.returnValue=false;
}

function update_year(){
	$('#anno_plus').val((parseInt($('#anno').val())+1));
}

function get_img(path,desc){
	$.get('load_desc.php',{'mypath':desc},function(data){
		$('#news_block').html('<div style="width:100%;text-align:center">'+data+'<img src="'+path+'" alt="" /></div>');
	});
}

function do_the_gallery(step){
	if (step==0) $('#sp1').load('gallery.php',{'buildup':1},function(){do_the_gallery(1);});
	else {
		//$('#gallery_box').css('left',g_w_pos);
		//$('#gallery_box').css('display','block');
		r=Math.random(10000);
		$('#sp1').animate({"height":"80px"},500);
		$.get('gallery.php',{"counter":1,"r":r},function(data){$('#real_gallery').css('width',(91*data)+'px');});
		$('#real_gallery').load('gallery.php',{"counter":0,"r":r},function(){gallery_manager('init')});
		$('#news_block').html('<p style="color:#fcff03;font-weight:bold">Clicca sulle immagini piccole per visualizzare le foto.<br/> Clicca sulle frecce laterali per scorrere le immagini presenti nella galleria fotografica</p>');
	}
}

function do_the_gallery_direct(step,path,desc){
	if (step==0) $('#sp1').load('gallery.php',{'buildup':1},function(){do_the_gallery_direct(1,path,desc);});
	else {
		//$('#gallery_box').css('left',g_w_pos);
		//$('#gallery_box').css('display','block');
		r=Math.random(10000);
		$('#sp1').animate({"height":"80px"},500);
		$.get('gallery.php',{"counter":1,"r":r},function(data){$('#real_gallery').css('width',(91*data)+'px');});
		$('#real_gallery').load('gallery.php',{"counter":0,"r":r},function(){gallery_manager('init')});
		get_img(path,desc);
	}
}

gallery_block=1;
actual_block=1;
function gallery_manager(action){

	switch (action){
		case 'init':
			h=$('#real_gallery').attr('scrollWidth');
			gallery_block=Math.floor(h/910);
			if (h%910!=0) gallery_block++;
			actual_block=1;
			$('#real_gallery').css("left","20px");
			break;
		case 'scroll_left':
			if (actual_block>1) {
				$('#real_gallery').animate({"left" : "+=910px", "top" : "+=0px"},500);
				actual_block--;
			} else $('#real_gallery').animate({"left" : "+=10px", "top" : "+=0px"},200,function(){$('#real_gallery').animate({"left" : "-=10px", "top" : "+=0px"},200);});
			break;
		case 'scroll_right':
			if (actual_block<gallery_block) {
				$('#real_gallery').animate({"left" : "-=910px", "top" : "+=0px"},500);
				actual_block++;
			} else $('#real_gallery').animate({"left" : "-=10px", "top" : "+=0px"},200,function(){$('#real_gallery').animate({"left" : "+=10px", "top" : "+=0px"},200);});
			break;
	}
}


function initialize_gmaps() {      
	  if (GBrowserIsCompatible()) {
	    var map = new GMap2(document.getElementById("smap")); 
		//map.enableScrollWheelZoom();
		map.addControl(new GLargeMapControl());	
		var blueIcon = new GIcon(G_DEFAULT_ICON);
		blueIcon.image = http_base+"template/gmaps_acl.png";
		blueIcon.iconSize = new GSize(22, 32);
		//blueIcon.shadowSize = new GSize(51, 58);
		markerOptions = { icon:blueIcon };
		center=new GLatLng(45.186166,11.300855);
		map.setCenter(center, 13);
		var marker = new GMarker(center,markerOptions);
		var marker2 = new GMarker (new GLatLng(45.197855,11.29225),markerOptions);
		var marker3 = new GMarker (new GLatLng(45.191391,11.309352),markerOptions);
		GEvent.addListener(marker, "mouseover",
			function() {
				marker.openInfoWindowHtml('<img src="template/stadium.png"><br/>Stadio Comunale Mario Sandrini');
			}
		);
		GEvent.addListener(marker, "mouseout",
			function() {
				marker.closeInfoWindow();
			}
		);
		GEvent.addListener(marker2, "mouseover",
			function() {
				marker2.openInfoWindowHtml('<img src="template/stadium.png"><br/>Stadio Comunale di Terranegra, Via Arnaldo Fusinato 4');
			}
		);
		GEvent.addListener(marker2, "mouseout",
			function() {
				marker2.closeInfoWindow();
			}
		);
		GEvent.addListener(marker3, "mouseover",
			function() {
				marker3.openInfoWindowHtml('<img src="template/storia.png"><br/>FC Legnago Salus SSD, Via Matteotti 18A');
			}
		);
		GEvent.addListener(marker3, "mouseout",
			function() {
				marker3.closeInfoWindow();
			}
		);
		map.addOverlay(marker);
		map.addOverlay(marker2);
		map.addOverlay(marker3);		
		map.setMapType(G_HYBRID_MAP);
	  }	
	}
