// javascript.js
$(document).ready(init);

function init() {
	
	// jqueryslidemenu
	if (jqueryslidemenu) {
		var arrowimages={down:['downarrowclass', path_http_img+'pixel.gif', 10], right:['rightarrowclass', path_http_img+'pixel.gif']}
		//build menu with ID="slidemenuAdmin" on page:
		jqueryslidemenu.buildmenu("slidemenuAdmin", arrowimages);
		jqueryslidemenu.buildmenu("divTop", arrowimages);
	}

	// prettyPhoto
	$("a[rel^='prettyPhoto']").prettyPhoto();

	// classe autocompleteoff
	$(function() {
		$('.autocompleteOff').attr('autocomplete', 'off');
	});

	// controllo data
	var oggi = new Date();
	var gg = oggi.getDate();
	var mm = oggi.getMonth();

	// eventi form //

	// invio contatti
	$("#formInfo").submit(function (e) {
		
		e.preventDefault(); //blocca l'evento di default
		$('#privacy_ok').val(($(this).find('[name=privacy]').attr('checked')?1:0));
		var parametri = setQueryString('formInfo', ''); 
		aggiornamentoAjax('invioContattiSito', parametri);
		
	});
	
	$("#fNL").submit(function (e) {
		
		e.preventDefault(); //blocca l'evento di default
		var parametri = setQueryString('fNL', ''); 
		aggiornamentoAjax('iscrizioneNL', parametri);
		
	});
	
	// jquery smooth scroll
	$(function(){
		$('a[href*=#]').click(function() {
			if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
				var $target = $(this.hash);
				$target = $target.length && $target || $('[name=' + this.hash.slice(1) +']');
				if ($target.length) {
					var targetOffset = $target.offset().top;
					$('html,body').animate({scrollTop: targetOffset}, 1500);
					return false;
				}
			}
		});
	});

	// plugin facebook
	(function(d, s, id) {
		var js, fjs = d.getElementsByTagName(s)[0];
		if (d.getElementById(id)) {return;}
		js = d.createElement(s); js.id = id;
		js.src = "//connect.facebook.net/it_IT/all.js#xfbml=1";
		fjs.parentNode.insertBefore(js, fjs);
	}(document, 'script', 'facebook-jssdk'));
	
	if (mappa) initialize();

	// ie
	if(jQuery.browser.msie && jQuery.browser.version < 8){
		$(function() {
			$(document).pngFix(); 
		});
		
		DD_roundies.addRule("div.rounded", "10px");
		DD_roundies.addRule("a.roundedLi, 7px");
		DD_roundies.addRule("a.round, 5px");
		DD_roundies.addRule("div.roundTR, 0 10px 0 0");
		DD_roundies.addRule("div.roundTL, 10px 0 0 0");
		DD_roundies.addRule("span.voceBread, 5px");
		DD_roundies.addRule("span.pageSelected, 5px");
		DD_roundies.addRule("div.elencoPagine a, 5px");
		
	} else {
	
		//jquery.corner
		$("div.rounded").corner("10px");
		$("a.roundedLi").corner("7px");
		$("a.round").corner("5px");
		$("div.roundTR").corner("10px tr");
		$("div.roundTL").corner("10px tl");
		$("span.voceBread").corner("5px");
		$("span.pageSelected").corner("5px");
		$("div.elencoPagine a").corner("5px");

	}
	if ($("#flashHome").get() != '') {
		var flashvars = {};
		var params = {
		  wmode: "transparent",
		  quality: "high",
		  allowScriptAccess: "always"
		};
		swfobject.embedSWF(path_http+"flash/banner_gennaio2012.swf", "flashHome", "840", "195", "9.0.0", path_http+"flash/expressInstall.swf", flashvars, params);
	}

} // end func init

function setImg(src,w,h,title,srcz,wz,hz) {

	$("#copertina").attr('src', src);
	$("#copertina").attr('width', w);
	$("#copertina").attr('height', h);
	$("a.linkFoto").attr('href',srcz);

} // end func setImg


function sendActionForm(e) {
	aggiornamentoAjax($(e).attr('action'), $(e).serialize());
	return false;
} // end func sendActionForm

function initialize() {
	//var latlng = new google.maps.LatLng(44.168992533190895, 12.28222757437129);
	iconSize = new google.maps.Size(30, 29);
	icon = new google.maps.MarkerImage(path_http_img+'pointMap.png', iconSize);
	shadow = new google.maps.MarkerImage(path_http_img+'pointMapShadow.png', new google.maps.Size(30, 29), new google.maps.Point(0, 0), new google.maps.Point(14, 33));

	var myOptions = {
	  zoom: 15,
	  center: latlng,
	  mapTypeId: google.maps.MapTypeId.ROADMAP
	};
		
	var map = new google.maps.Map(document.getElementById("gMap"),
		myOptions);
	
	var marker = new google.maps.Marker({
		position: latlng,
		title: clicca_per_recapiti,
		map: map,
		icon: icon, 
		shadow: shadow
	});

	var infowindow = new google.maps.InfoWindow();
	google.maps.event.addListener(marker, 'click', function() { infowindow.setContent(document.getElementById('InfoWindowTxt').innerHTML);
		infowindow.open(map, marker); });

	directionsDisplay = new google.maps.DirectionsRenderer();
	directionsDisplay.setMap(map);
	directionsDisplay.setPanel(document.getElementById("directionsPanel"));

} // end func initialize

// Ajax con jquery
function aggiornamentoAjax(azione,parametri) {

	$.ajax({ 
		url: urlAjax,
		data: parametri+'&action='+azione,
		type: 'GET',
		cache: false,
		dataType: "json",
		success: function(response) {

			var esito = response.esito;
			var msg = response.msg;

			switch (azione) {

				case "setStato":

					if (esito == 1) {

						$.each(response.dati, function(i,item){
							if (item) {

								var img = $('#stato' + item.id + ' img');

								img.attr('alt', item.imgAlt);
								img.attr('title', item.imgTitle);
								img.removeClass(item.imgNoClass);
								img.addClass(item.imgClass);

								$('#valore_stato_'+item.id).val(item.stato);

							}
						});

					}

					if (msg != '') alert(msg);

				break; // end setStato

				case "setRicerca":

					if (esito == 1) {

						$.each(response.dati, function(i,item){
							if (item) {

								var img = $('#ricerca' + item.id + ' img');

								img.attr('alt', item.imgAlt);
								img.attr('title', item.imgTitle);
								img.removeClass(item.imgNoClass);
								img.addClass(item.imgClass);

								$('#valore_ricerca_'+item.id).val(item.ricerca);

							}
						});

					}

					if (msg != '') alert(msg);

				break; // end setRicerca

				case "setMenu":

					if (esito == 1) {

						$.each(response.dati, function(i,item){
							if (item) {

								var img = $('#menu' + item.id + ' img');

								img.attr('alt', item.imgAlt);
								img.attr('title', item.imgTitle);
								img.removeClass(item.imgNoClass);
								img.addClass(item.imgClass);

								$('#valore_menu_'+item.id).val(item.menu);

							}
						});

					}

					if (msg != '') alert(msg);

				break; // end setMenu

				case "setInEvidenza":

					if (esito == 1) {

						$.each(response.dati, function(i,item){
							if (item) {

								var img = $('#in_evidenza' + item.id + ' img');

								img.attr('alt', item.imgAlt);
								img.attr('title', item.imgTitle);
								img.removeClass(item.imgNoClass);
								img.addClass(item.imgClass);

								$('#valore_in_evidenza_'+item.id).val(item.menu);

							}
						});

					}

					if (msg != '') alert(msg);

				break; // end setInEvidenza

				case "registrazione":
				case "recPsw":
					if (msg != '') alert(msg);

					if (esito == '1') {
						$.prettyPhoto.close();
						//if (azione == 'xxx') window.location.reload();
					}

				break;
				
				case "addOpz":
				case "delOpz":
					if (msg != '') alert(msg);

					if (esito == '1') {
						window.location.reload();
					}

				break; // end addOpz - delOpz
				
				case "setConf":
				case "delConf":
				case "setVal":
				case "delVal":
				case "setImp":
				case "delImp":
				case "setSTO":
				case "delSTO":
				case "setArea":
				case "delArea":
				case "setTar":
				case "delTar":
					if (msg != '') alert(msg);

					if (esito == '1') {
						window.location.reload();
					}

				break; // end setConf - delConf - setVal - delVal - setImp - delImp - setSTO - delSTO - setArea - delArea - setTar - delTar
				
				case "setPrezzo":

					if (esito == 1) {

						$.each(response.dati, function(i,item){
							if (item) {

								var pr = $('#prezzo_prodotto');
								pr.attr('value', item.prezzo_prodotto);
								setPrezzoFinale(item.prezzo_prodotto,$('#sconto').attr('value'));
							}
						});

					}

					if (msg != '') alert(msg);

				break; // end setPrezzo
				
				case "addCart":
					// aggiorna box carrello
					if (msg != '') alert(msg);
					aggiornamentoAjax('updCart','');
				break; // end addCart
				
				case "updCart":
					if (esito == 1) {

						$.each(response.dati, function(i,item){
							if (item) {

								$('#divLinkCheckout').css('display', (item.link_checkout?'block':'none'));
								$('#divContCart').html(item.txt);
								
								var img = $('#imgCart');

								img.attr('alt', item.txt);
								img.attr('title', item.txt);
								img.removeClass('cartFull');
								img.removeClass('cartEmpty');
								img.addClass(item.imgClass);

							}
						});

					}
				break; // end updCart
				
				case "invioContattiSito":

					if (esito == 0) $('#sec_img_contatti').attr('src', path_http_lib+'securimage/securimage_show.php?sid=' + Math.random());
					if (msg != '') alert(msg);

				break; // end invioContattiSito

				default:

					if (msg != '') alert(msg);

			} // end switch azione

		} 
		});

} // end func aggiornamentoAjax

function setQueryString(formName,id) {

	var querystring = '';
	var modulo = document.forms[formName];
	
	switch (formName) {
		
		case "formTblDiz":
			var querystring = 'id='+id+'&precarica='+(modulo.elements['precarica['+id+']'].checked?'1':'0');
			var numeroLingue = lingue.length;

			for (var i=0; i<numeroLingue; i++) {
				querystring += '&'+lingue[i]+"="+encodeURIComponent(modulo.elements['txt['+id+']['+lingue[i]+']'].value);
			}
		break; // end formTblDiz
		
		case "formTblOpz":
			var querystring = 'id='+id+'&tabella='+modulo.tabella.value+'&campo='+modulo.campo.value+'&id_sup='+modulo.id_sup.value;
			if (modulo.tabella.value == 'ecom_media') querystring += '&ordinamento='+modulo.elements['ordinamento['+id+']'].value;
			var numeroLingue = lingue.length;

			for (var i=0; i<numeroLingue; i++) {
				if (modulo.campo.value == 'codice') querystring += '&'+lingue[i]+"="+encodeURIComponent(modulo.elements['txt2['+id+']['+lingue[i]+']'].value); else querystring += '&'+lingue[i]+"="+encodeURIComponent(modulo.elements['txt['+id+']['+lingue[i]+']'].value);
			}
		break; // end formTblOpz
		
		case "formTblConf":
			var querystring = 'id='+id+'&nome='+modulo.elements['nome['+id+']'].value+'&valore='+modulo.elements['valore['+id+']'].value;
		break; // end formTblConf
		
		case "formTblVal":
			var querystring = 'id='+id+'&simbolo='+modulo.elements['simbolo['+id+']'].value+'&tasso_cambio='+modulo.elements['tasso_cambio['+id+']'].value+'&tabella='+modulo.tabella.value;
			var numeroLingue = lingue.length;

			for (var i=0; i<numeroLingue; i++) {
				querystring += '&'+lingue[i]+"="+encodeURIComponent(modulo.elements['nome['+id+']['+lingue[i]+']'].value);
			}
		break; // end formTblVal
		
		case "formTblImp":
			var querystring = 'id='+id+'&aliquota='+modulo.elements['aliquota['+id+']'].value+'&tabella='+modulo.tabella.value;
			var numeroLingue = lingue.length;

			for (var i=0; i<numeroLingue; i++) {
				querystring += '&'+lingue[i]+"="+encodeURIComponent(modulo.elements['nome['+id+']['+lingue[i]+']'].value);
			}
		break; // end formTblImp
		
		case "formTblStati":
			var querystring = 'id='+id+'&ordinamento='+modulo.elements['ordinamento['+id+']'].value+'&tabella='+modulo.tabella.value;
			var numeroLingue = lingue.length;

			for (var i=0; i<numeroLingue; i++) {
				querystring += '&'+lingue[i]+"="+encodeURIComponent(modulo.elements['nome['+id+']['+lingue[i]+']'].value);
			}
		break; // end formTblStati

		case "formTblAree":
			var querystring = 'id='+id+'&tipo_area='+modulo.elements['tipo_area['+id+']'].value+'&tabella='+modulo.tabella.value;
			var numeroLingue = lingue.length;

			for (var i=0; i<numeroLingue; i++) {
				querystring += '&'+lingue[i]+"="+encodeURIComponent(modulo.elements['nome['+id+']['+lingue[i]+']'].value);
			}
		break; // end formTblAree
		
		case "formTblTariffe":
			var querystring = 'id='+id+'&tabella='+modulo.tabella.value+'&id_modalita_spedizione='+modulo.id_modalita_spedizione.value+'&id_area='+modulo.elements['id_area_'+id].value+'&peso_da='+modulo.elements['peso_da_'+id].value+'&peso_a='+modulo.elements['peso_a_'+id].value+'&volume_da='+modulo.elements['volume_da_'+id].value+'&volume_a='+modulo.elements['volume_a_'+id].value+'&totale_ordine_da='+modulo.elements['totale_ordine_da_'+id].value+'&totale_ordine_a='+modulo.elements['totale_ordine_a_'+id].value+'&importo_netto='+modulo.elements['importo_netto_'+id].value+'&id_imposta='+modulo.elements['id_imposta_'+id].value;
			//alert(querystring);
		break; // end formTblTariffe
		default:
			var numberElement = modulo.elements.length;

			for(var i=0; i<numberElement; i++) {
				if (modulo.elements[i].value != 'undefined') querystring += (querystring!=''?'&':'')+modulo.elements[i].name+"="+encodeURIComponent(modulo.elements[i].value);
			}
	}

	return querystring;

} // end func setQueryString

function selezionaTutti(nomeForm, nome) {

	var no_selezionato = 0;

	// primo ciclo per verificare se c'è almeno un check non selezionato
	for (var i = 0; i < document.forms[nomeForm].length; i++) {
		if (document.forms[nomeForm].elements[i].type=='checkbox' && document.forms[nomeForm].elements[i].name.indexOf(nome)==0){

			if (!document.forms[nomeForm].elements[i].checked) { no_selezionato = 1; break; }
		}
	}

	// secondo ciclo per selezionare/deselezionare tutti
	for (var i = 0; i < document.forms[nomeForm].length; i++) {
		if (document.forms[nomeForm].elements[i].type=='checkbox' && document.forms[nomeForm].elements[i].name.indexOf(nome)==0){

			if (no_selezionato==1) document.forms[nomeForm].elements[i].checked = true; else document.forms[nomeForm].elements[i].checked = false;
		}
	}
} // end func selezionaTutti

function seleziona_ckeck(what,id,selezionato) {

	// pagine, canali, sezioni
	switch (what) {

		case "pagine": // tutte le pagine

			for (var i in arrayPagine) document.getElementById('p'+i).checked = selezionato;

		break;

		case "canali": // tutte le pagine del canale

			for (var i in arrayCanali[id]) document.getElementById('p'+i).checked = selezionato;

		break;

		case "sezioni": // tutte le pagine della sezione

			for (var i in arraySezioni[id]) document.getElementById('p'+i).checked = selezionato;

		break;

	} // end switch

} // end func seleziona_ckeck

function deseleziona_check(id_sezione, id_canale, selezionato) {

	if (!selezionato) {
		if (id_sezione>0) document.getElementById('pagine_sezione'+id_sezione).checked = selezionato;
		if (id_canale>0) document.getElementById('sezioni_canale'+id_canale).checked = selezionato;
		document.getElementById('tutte_pagine').checked = selezionato;
	}

} // end func deseleziona_check

function loadMyFuncModule(stufftoeval) { 
	var dj_global = this; // global scope reference 
	if (window.execScript) {

		/*String.prototype.trim = function() {
			a = this.replace(/^\s+/, '');
			return a.replace(/\s+$/, '');
		};*/
		jQuery.trim(stufftoeval);
		window.execScript(stufftoeval.trim()); 
		return null; // execScript doesn’t return anything 
	} 
	return dj_global.eval ? dj_global.eval(stufftoeval) : eval(stufftoeval);
}

function imposeMaxLength(element, maxLength) {

	console.log(element.value.length);
	if(element.value.length > maxLength) {
		var text = $(element).val().substr(0, maxLength);
		$(element).val(text); 
	}

} //end func imposeMaxLength

function moveOnMax(field,nextFieldID){

	if(field.value.length >= field.maxLength){
		document.getElementById(nextFieldID).focus();
	}

} // end func moveOnMax

function confrontaDate() {

	var today = new Date();
	var inizio = new Date(document.forms['formInsUpd'].elements['validadal[Y]'].value, (document.forms['formInsUpd'].elements['validadal[m]'].value - 1), document.forms['formInsUpd'].elements['validadal[d]'].value);
	var fine = new Date(document.forms['formInsUpd'].elements['validaal[Y]'].value, (document.forms['formInsUpd'].elements['validaal[m]'].value - 1), document.forms['formInsUpd'].elements['validaal[d]'].value);
	var id = document.forms['formInsUpd'].elements['id_prodotto'].value;
	//alert('oggi: '+today.getTime()+'\nvinizio: '+inizio.getTime()+'\nfine: '+fine.getTime());

	// verifica che inizio sia maggiore di oggi
	// solo in fase di inserimento
	if (fine.getTime()<=today.getTime() && id == '') return false;

	// verifica che fine sia maggiore o uguale a inizio
	if (fine.getTime()<fine.getTime()) return false;

	return true;

} // end func confrontaDate

function setPrezzoFinale(val_prezzo, val_sconto) {

	var sconto = new Number(val_sconto);
	var prezzo = new Number(val_prezzo);
	//alert(prezzo+' '+sconto);
	if (sconto > 0 && prezzo > 0) $('#prezzo_scontato_lordo').attr('value',prezzo - prezzo/100*sconto);

} // end func setPrezzoFinale

/*
Original:  Phil Webb (phil@philwebb.com)
Web Site:  http://www.philwebb.com
This script and many more are available free online at
The JavaScript Source!! http://javascript.internet.com
*/
function move(fbox, tbox, campoHidden) {

	var arrFbox = new Array();
	var arrTbox = new Array();
	var arrLookup = new Array();
	var i;
	for (i = 0; i < tbox.options.length; i++) {
		arrLookup[tbox.options[i].text] = tbox.options[i].value;
		arrTbox[i] = tbox.options[i].text;
	}

	var fLength = 0;
	var tLength = arrTbox.length;
	for(i = 0; i < fbox.options.length; i++) {
		arrLookup[fbox.options[i].text] = fbox.options[i].value;
		if (fbox.options[i].selected && fbox.options[i].value != "") {
			arrTbox[tLength] = fbox.options[i].text;
			tLength++;
		} else {
			arrFbox[fLength] = fbox.options[i].text;
			fLength++;
		}
	}
	
	arrFbox.sort();
	arrTbox.sort();
	fbox.length = 0;
	tbox.length = 0;
	var c;
	for(c = 0; c < arrFbox.length; c++) {
		var no = new Option();
		no.value = arrLookup[arrFbox[c]];
		no.text = arrFbox[c];
		fbox[c] = no;
	}
	campoHidden.value = '';
	for(c = 0; c < arrTbox.length; c++) {
		var no = new Option();
		no.value = arrLookup[arrTbox[c]];
		no.text = arrTbox[c];
		tbox[c] = no;
		campoHidden.value += ','+arrLookup[arrTbox[c]];;
	}
	campoHidden.value = campoHidden.value.substring(1);
} // end func move

function checkValidita(valore) {

	switch (valore) {
	
		case "gruppo":
			document.getElementById('id_utente').value='';
			document.getElementById('id_utente').disabled=true;
			//document.getElementById('id_tipo').value='';
			document.getElementById('id_tipo').disabled=false;
		break; // end gruppo
		
		case "utente":
			//document.getElementById('id_utente').value='';
			document.getElementById('id_utente').disabled=false;
			document.getElementById('id_tipo').value='';
			document.getElementById('id_tipo').disabled=true;
		break; // end utente
		
		default: // all
			document.getElementById('id_utente').value='';
			document.getElementById('id_utente').disabled=true;
			document.getElementById('id_tipo').value='';
			document.getElementById('id_tipo').disabled=true;
	
	}

} // end func checkValidita


function setPrezzo() {

	var ali = arrayAliquote[document.getElementById('id_imposta').value];
	var netto = new Number(document.getElementById('pnb_intero').value+'.'+document.getElementById('pnb_decimali').value);
	//alert(netto);
	var lordo = netto + netto/100*ali;
	document.getElementById('prezzo_lordo').value = lordo;//.replace('.',',');

} // end func setPrezzo


















