// JavaScript Document

$(document).ready(function(){
	$.ajax({
		type:'POST',
		url:'/webproduct.php?op=menuSearch',
		dataType:'json',
		success: function(msg){
			var arrCat = Array();
			for(i=0;i<msg.length;i++) {
				if(msg[i].titolo && msg[i].titolo!="")
				  arrCat.push(msg[i].titolo);
				}
			$('#search').autocompleteArray(arrCat, {
				width: 320,
				delay:10,
				minChars:1,
				matchSubset:1,
				matchContains:true,
				//cacheLength:10,
				autoFill:true,
				maxItemsToShow:10,
				scroll: true,
				scrollHeight: 300
			});
		}
	});

	/*$("img").lazyload({ 
	    //placeholder : "img/grey.gif",
	    effect : "fadeIn"
	});*/

	$(function() {
		$('#gallery a').lightBox();
		$('#gallery-var a').lightBox();
		$('a.img-click').lightBox();
	});
});

//$('.col_cnt_abs').ready(function(){
//	h_cnt = $('.col_cnt_abs').height();
//	h_block = $('#block-fb').position().top + $('#block-fb').height();
//	var h = 0;
//	h_cnt > h_block ? h = h_cnt : h = h_block;
//	h = h + 20;
//	$('.col_lft').css('height',h.toString()+'px');
//	if(h_cnt < h_block) $('.col_cnt_abs').css('height',h.toString()+'px');
//});


function openCategoria(id,el) {
	$(el).toggleClass('expanded');
	$('#'+id).toggleClass('collapsed');
}

var oldLink = null;
function setActiveStyleSheet(link, title) {
  var i, a, main;
  for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
    if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
      a.disabled = true;
      if(a.getAttribute("title") == title) a.disabled = false;
    }
  }
  if (oldLink) oldLink.style.fontWeight = 'normal';
  oldLink = link;
  link.style.fontWeight = 'bold';
  return false;
}

// This function gets called when the end-user clicks on some date.
function selected(cal, date) {
  cal.sel.value = date; // just update the date in the input field.
  if (cal.dateClicked && (cal.sel.id == "sel1" || cal.sel.id == "sel3"))
    cal.callCloseHandler();
}

function closeHandler(cal) {
  cal.hide();                        // hide the calendar
//  cal.destroy();
  _dynarch_popupCalendar = null;
}

function showCalendar(id, format, showsTime, showsOtherMonths) {
  var el = document.getElementById(id);
  if (_dynarch_popupCalendar != null) {
    // we already have some calendar created
    _dynarch_popupCalendar.hide();                 // so we hide it first.
  } else {
    // first-time call, create the calendar.
    var cal = new Calendar(1, null, selected, closeHandler);
    // uncomment the following line to hide the week numbers
    // cal.weekNumbers = false;
    if (typeof showsTime == "string") {
      cal.showsTime = true;
      cal.time24 = (showsTime == "24");
    }
    if (showsOtherMonths) {
      cal.showsOtherMonths = true;
    }
    _dynarch_popupCalendar = cal;                  // remember it in the global var
    cal.setRange(1900, 2070);        // min/max year allowed.
    cal.create();
  }
  _dynarch_popupCalendar.setDateFormat(format);    // set the specified date format
  _dynarch_popupCalendar.parseDate(el.value);      // try to parse the text in field
  _dynarch_popupCalendar.sel = el;                 // inform it what input field we use

  _dynarch_popupCalendar.showAtElement(el.nextSibling, "Br");        // show the calendar

  return false;
}

var MINUTE = 60 * 1000;
var HOUR = 60 * MINUTE;
var DAY = 24 * HOUR;
var WEEK = 7 * DAY;

function isDisabled(date) {
  var today = new Date();
  return (Math.abs(date.getTime() - today.getTime()) / DAY) > 10;
}

function flatSelected(cal, date) {
  var el = document.getElementById("preview");
  el.innerHTML = date;
}

function showFlatCalendar() {
  var parent = document.getElementById("display");

  var cal = new Calendar(0, null, flatSelected);

  cal.weekNumbers = false;

  cal.setDisabledHandler(isDisabled);
  cal.setDateFormat("%A, %B %e");

  cal.create(parent);

  cal.show();
}

function check_date(field){

var checkstr = "0123456789";

var DateField = field;

var Datevalue = "";

var DateTemp = "";

var seperator = "/";

var day;

var month;

var year;

var step = 0;

var err = 0;

var i;

   err = 0;

   DateValue = DateField.value;

   /* cancello tutti i dati tranne 0-9 */

   for (i = 0; i < DateValue.length; i++) {

              if (checkstr.indexOf(DateValue.substr(i,1)) >= 0) {

                 DateTemp = DateTemp + DateValue.substr(i,1);

              }

   }

   DateValue = DateTemp;

  /* se l'anno � inserito con 2 valori lo cambio sempre con  20xx */

   if (DateValue.length == 6) {

      DateValue = DateValue.substr(0,4) + '20' + DateValue.substr(4,2); }

   if (DateValue.length != 8) {

      err = 19;}

   /* anno sbagliato 0000 */

   year = DateValue.substr(4,4);

   if (year == 0) {

      err = 20;

   }

   /* validazione del mese*/

   month = DateValue.substr(2,2);

   if ((month < 1) || (month > 12)) {

      err = 21;

   }

   /* validazione del giorno */

   day = DateValue.substr(0,2);

   if (day < 1) {

     err = 22;

   }

   /* Validazione anno / febbraio / gg */

   if ((year % 4 == 0)) {

      step = 1;

   }

   if ((month == 2) && (step == 1) && (day > 29)) {

      err = 23;

   }

   if ((month == 2) && (step != 1) && (day > 28)) {

      err = 24;

   }

   /* validazione dei mesi */

   if ((day > 31) && ((month == "01") || (month == "03") || (month == "05") || (month == "07") || (month == "08") || (month == "10") || (month == "12"))) {

      err = 25;

   }

   if ((day > 30) && ((month == "04") || (month == "06") || (month == "09") || (month == "11"))) {

      err = 26;

   }

   /* se � inserito 00 cancello i dati */

   if ((day == 0) && (month == 0) && (year == 00)) {

      err = 0; day = ""; month = ""; year = ""; seperator = "";

   }

   /* Se non ci sono errori inserisco la data (esempio 13.12.2001) */

   if (err == 0) {

      DateField.value = day + seperator + month + seperator + year;

   }

   /* Messaggio di errore, avviso di data corretta se err diverso da 0 */

   else {

      alert("La data non è corretta.\n\nIl formato consentito è:\n  gg/mm/aaaa\n  - gg/mm/aa\n");

      DateField.select();

              DateField.focus();

   }

}

function control_subscribe()  {
 	if(document.subscribe.privacy.checked == 0) {
	  alert('Manca il consenso al trattamento dei dati personali.');
	  return false;
	}
	if(document.subscribe.cognome.value == "")  {
	  alert('Devi inserire il cognome.');
	  return false;
	}
	if(document.subscribe.ragione.value == "")  {
	  alert('Devi inserire il nickname.');
	  return false;
	}
	if(document.subscribe.iva.value != "")  {
	  if(document.subscribe.cf.value == "") {
	    alert('Attenzione! Se possiedi la partita IVA devi inserire anche il codice fiscale.');
	    return false;	    
	  }
	}
	if(document.subscribe.indirizzo.value == "")  {
	  alert('Devi inserire l\'indirizzo.');
	  return false;
	}
	if(document.subscribe.localita.value == "")  {
	  alert('Devi inserire la localita\'.');
	  return false;
	}
	if(document.subscribe.cap.value == "")  {
	  alert('Devi inserire il CAP.');
	  return false;
	}
	if(document.subscribe.telefono.value == "")  {
	  alert('Devi inserire il telefono di casa.');
	  return false;
	} else if(document.subscribe.telefono.value.length > 20) {
		alert('Il numero massimo di caratteri per il telefono e\' 20.');
		  return false;
	}
	if(document.subscribe.mail.value == "")  {
		  alert('Devi inserire l\'indirizzo e-mail.');
	  return false;
	}
	if(document.subscribe.password.value == "")  {
	  alert('Devi inserire la password.');
	  return false;
	}
	var password;
	password = document.subscribe.password.value;
	if(password.length < 3 || password.length > 8)  {
	  alert('La password deve contenere fra i 3 e gli 8 caratteri.');
	  return false;
	}	
	if(document.subscribe.conf_password.value == "")  {
	  alert('Devi inserire la conferma della password.');
	  return false;
	}
	if($('#captcha').length > 0) {
		$.ajax({
            type: 'POST',
            url: 'webproduct.php',
            data: 'op=check_captcha&captcha=' + $('#captcha').val(),
            dataType: 'json',
            success: function(msg){
                if(msg.success) {
                  document.subscribe.submit();
                  return true; 
                } else {
                  alert('Il codice antispam non corrisponde.');
                  return false;
                }
            }
        });
	}
	return true;
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}


//aggiunte
function wopen(url, name, w, h){
	 w += 32;
	 h += 96;
	 var win = window.open(url,
	  name,
	  'width=' + w + ', height=' + h + ', ' +
	  'location=no, menubar=no, ' +
	  'status=no, toolbar=no, scrollbars=yes, resizable=no');
	 win.resizeTo(w, h);
	 win.focus();
}

function valoreq(q) {
	if (q.value == "") {
		q.value = 0;
	}
}

function validazioneForm(id_nome, /*id_tel,*/ id_email, id_privacy) {
	var nome = document.getElementById(id_nome);
	//var tel = document.getElementById(id_tel);
	var email = document.getElementById(id_email);
	var privacy = document.getElementById(id_privacy); 

	if (nome.value == "") {
		alert("Riempi il campo Nome.");
		nome.focus();
		returnVal = false;
	} else if (echeck(email) == false) {
		email.focus();
		returnVal = false;
	/*} else if (!isnum(tel.value)) {
		alert("Verifica il campo Telefono.");
		tel.focus();
		returnVal = false;*/
	} else if (privacy.checked == "") {
		alert("Accettare la normativa sul trattamento dei dati personali.");
		privacy.focus();
		returnVal = false;
	} else {
		returnVal = true;
    }
}

function isnum(str) {
	if (isNaN(str) || str == "") {
		return false;
	} else {
		return true;
	}
}

function echeck(elem){
	var emailExp = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
	if(elem.value.match(emailExp)){
		return true;
	}else{
		alert("Verificare il campo Email");
		elem.focus();
		return false;
	}
}

function validazioneSearch(id_search) {
	var fieldSearch = document.getElementById(id_search);

	if (fieldSearch.value == "" || fieldSearch.value == "cerca prodotto") {
		alert("Inserisci almeno un termine di Ricerca.");
		fieldSearch.focus();
		returnVal = false;
	} else {
		returnVal = true;
    }
}

function check_Voto() {
	if($('#name').val()=="" || !$('input[name="voto"]:checked').val() || $('#testo').val()=="") {
		alert('Tutti i campi sono obbligatori.');
		return false;
	}
}

function slideTab() {
	if(!$('#scheda_tab').hasClass('selected')) {
		$('#scheda_tab').addClass('selected');
		$('#correlati_tab').toggleClass('selected');
		$('#idTab1').removeClass('hidden').addClass('visible');
		$('#idTab2').removeClass('visible').addClass('hidden');
	} else {
		$('#correlati_tab').addClass('selected');
		$('#scheda_tab').toggleClass('selected');
		$('#idTab2').removeClass('hidden').addClass('visible');
		$('#idTab1').removeClass('visible').addClass('hidden');
	}
}

