// JavaScript Document
/**
	CONFIG
*/
	var config = new Array();
		config['ajax'] = new Array();
		config['ajax']['url'] = 'saverioajaxjson.php';
		config['ajax']['error'] = 'Errore nel caricamento dei dati.';
		config['ajax']['loading'] = new Array();
		config['ajax']['loading']['id'] = '#loading';
		config['ajax']['loading']['class'] = 'loading1';
		config['ajax']['loading']['text'] = 'Caricamento in corso...';


function findObj(theObj, theDoc)
{
  var p, i, foundObj;
  
  if(!theDoc) theDoc = document;
  if( (p = theObj.indexOf("?")) > 0 && parent.frames.length)
  {
    theDoc = parent.frames[theObj.substring(p+1)].document;
    theObj = theObj.substring(0,p);
  }
  if(!(foundObj = theDoc[theObj]) && theDoc.all) foundObj = theDoc.all[theObj];
  for (i=0; !foundObj && i < theDoc.forms.length; i++) 
    foundObj = theDoc.forms[i][theObj];
  for(i=0; !foundObj && theDoc.layers && i < theDoc.layers.length; i++) 
    foundObj = findObj(theObj,theDoc.layers[i].document);
  if(!foundObj && document.getElementById) foundObj = document.getElementById(theObj);
  
  return foundObj;
}
function showHideLayers()
{ 
  var i, visStr, obj, args = showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3)
  {
    if ((obj = findObj(args[i])) != null)
    {
      visStr = args[i+2];
      if (obj.style)
      {
        obj = obj.style;
        if(visStr == 'show') visStr = 'block';
        else if(visStr == 'hide') visStr = 'none';
      }
      obj.display = visStr;
    }
  }
}

var idprod=0, idsottprod=0;
function CambiaFoto(ogg, foto, dettagli) {
	var obj;
    if (document.images) {
		document.images[ogg].src=foto;
//		alert(document.images[ogg].src);
	}

	if ((obj = findObj(ogg+'dettagli')) != null) {
		obj.innerHTML = dettagli;
	}

}

function RichiestaInformazioni(idprod, idsottoprod) {
	window.document.location.href='informazioni.php?id='+idprod+'&idvar='+idsottoprod;
}

function openBrWindow(theURL,winName,features) {
  window.open(theURL,winName,features);
}

function Vai(pagina) {
	if (pagina!='') window.document.location.href=pagina;
}
function SelectCategoria(pagina, id) {
	if (pagina!='' && id!='') Vai(pagina+id);
}


function EstraiStringa(tipo, campo, ricerca){
	if (tipo=='prima')
		campo = campo.substring(0, campo.lastIndexOf(ricerca));
	else
		campo = campo.substr(campo.lastIndexOf(ricerca)+1);
	return campo;
}

function is_array(obj) {
   if (obj.constructor.toString().indexOf("Array") == -1)
      return false;
   else
      return true;
}

function validateForm(){ //funzioni richieste: EstraiStringa - is_array
	var i,p,q,nm,test,num,min,max,errors='',args=validateForm.arguments;
	for (i=0; i<(args.length-2); i+=3) {
		nm=args[i];
		val=args[i+1];
		args[i+2];
		test=(is_array(args[i+2])) ? args[i+2][0] : args[i+2];
	    if (val) {
//			nm=val.name;
//			if (nm.indexOf('_')!=-1){
//				nm=(nm.substr(nm.indexOf('_')+1));
//			}
			if ((val=val.value)!="" && val!='undefined') {
				if (test.indexOf('isEmail')!=-1) {
					p=val.indexOf('@');
					if (p<1 || p==(val.length-1)) errors+='- '+nm+' non è una e-mail valida.\n';
				} else if (test.indexOf('codfis')!=-1){
					var codfis = ControllaCF(val);
					if (codfis!='') errors+='- '+nm+': '+codfis+'\n';
				} else if (test.indexOf('piva')!=-1){
					var piva = ControllaPIVA(val);
					if (piva!='') errors+='- '+nm+': '+piva+'\n';
				} else if (test.indexOf('File')!=-1){
//					var ext = test=args[i+3];
					var ext = args[i+2][1];
//					alert(ext);
					var ext2 = ',' + ext + ',';
					var ext_file = EstraiStringa('dopo', val, '.');
					if (ext2.toLowerCase().indexOf(',' + ext_file.toLowerCase() + ',') == -1) errors+='- '+nm+' deve essere un file di tipo ' + ext.toUpperCase().replace(/,/g, ', ') + '.\n';
				} else if (test!='R') {
					num = parseFloat(val);
					if (isNaN(val)) errors+='- '+nm+' non è un numero valido.\n';
					if (test.indexOf('inRange') != -1) {
						p=test.indexOf(':');
						min=test.substring(8,p); max=test.substring(p+1);
						if (num<min || max<num) errors+='- '+nm+' non è un numero tra '+min+' e '+max+'.\n';
					}
				}
			} else if (test.charAt(0) == 'R') errors += '- '+nm+' è obbligatorio.\n';
		}
	}
	if (errors) alert('ATTENZIONE: si sono verificati i seguenti errori:\n'+errors);
  	return (errors == '');
}


function ControllaCF(cf)
{
	var validi, i, s, set1, set2, setpari, setdisp;
	if( cf == '' )  return '';
	cf = cf.toUpperCase();
	if( cf.length != 16 )
		return "deve errere lungo 16 caratteri.";
	validi = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	for( i = 0; i < 16; i++ ){
		if( validi.indexOf( cf.charAt(i) ) == -1 )
			return "sono accettate solo lettere e cifre. Il carattere '" + cf.charAt(i) + "' non è valido.";
	}
	set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
	setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
	s = 0;
	for( i = 1; i <= 13; i += 2 )
		s += setpari.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
	for( i = 0; i <= 14; i += 2 )
		s += setdisp.indexOf( set2.charAt( set1.indexOf( cf.charAt(i) )));
	if( s%26 != cf.charCodeAt(15)-'A'.charCodeAt(0) )
		return "non è valido. Il codice di controllo non corrisponde.";
	return "";
}
function ControllaPIVA(pi)
{
	if( pi == '' )  return '';
	if( pi.length != 11 )
		return "deve contenere 11 caratteri numerici.";
	validi = "0123456789";
	for( i = 0; i < 11; i++ ){
		if( validi.indexOf( pi.charAt(i) ) == -1 )
			return "sono accettate solo caratteri numerici. '" + pi.charAt(i) + "' non è un carattere valido.";
	}
	s = 0;
	for( i = 0; i <= 9; i += 2 )
		s += pi.charCodeAt(i) - '0'.charCodeAt(0);
	for( i = 1; i <= 9; i += 2 ){
		c = 2*( pi.charCodeAt(i) - '0'.charCodeAt(0) );
		if( c > 9 )  c = c - 9;
		s += c;
	}
	if( ( 10 - s%10 )%10 != pi.charCodeAt(10) - '0'.charCodeAt(0) )
		return "non è valida. Il codice di controllo non corrisponde.";
	return '';
}

function SelezionaCheckBox(formattuale, checkVal, reg){
	re = new RegExp(reg);
//	alert(reg + ' _ ' + re);
	for(i = 0; i < formattuale.elements.length; i++){
		elm = formattuale.elements[i];
		if (elm.type == 'checkbox'){
			if (re.test(elm.id))
				elm.checked = checkVal;
		}
	}
}


function getNotUndefined(theValue, theType, theDefinedValue){
	var boolValueUndefined = ( typeof(theValue)!='undefined' && theValue!='undefined' );
  switch (theType) {
    case "string":
      theValue = ( boolValueUndefined ) ? $theValue : theDefinedValue;
      break;
    case "number":
      theValue = ( boolValueUndefined && !isNaN(theValue) ) ? parseInt(theValue) : theDefinedValue;
      break;
  }
  return theValue;
}


var loading_id = config['ajax']['loading']['id'];


jQuery(document).ready(function(){
	jQuery("#loading").hide();
});

function AjaxRequestJson(parametri, url){// ------- funzioni necessarie: getNotUndefined

	url = getNotUndefined(url, config['ajax']['url']);

//	jQuery("#ajax").text(parametri);

	jQuery.ajax({
		type: "POST",
		cache: "none",
		url: url,
		data: parametri,
		dataType: "json",

		beforeSend: function() {
			if (loading_id != config['ajax']['loading']['id']) jQuery(loading_id).animate({height:'hide', opacity: 'hide'}, 'fast');
			jQuery(loading_id).html( config['ajax']['loading']['text'] ).animate({height:'show', opacity: 'show'}, 'fast');
		},
		success: function(json){
			jQuery(loading_id).animate({height:'hide', opacity: 'hide'}, 'fast');
// 			alert(json);
			for(var id in json){
// 				alert(json[id]);
				jQuery(id).html(json[id]);
			}
			if (loading_id != config['ajax']['loading']['id']) jQuery(loading_id).animate({height:'show', opacity: 'show'}, 'fast');
			config['ajax']['loading']['id'] = loading_id;
		},
		error: function(){
			if (loading_id != config['ajax']['loading']['id']) jQuery(loading_id).animate({height:'show', opacity: 'show'}, 'fast');
			config['ajax']['loading']['id'] = loading_id;
			alert(config['ajax']['error']);
		}
	});
}
function ActionArticoloCarrello(params){ // ,idform1 [, idform2, ...] ------- funzioni necessarie: getNotUndefined
	var parametri='', args = ActionArticoloCarrello.arguments;
	var fun_config = new Array();
	fun_config['tipo']			= getNotUndefined(params['tipo'],		'listadesiderio');
	fun_config['idcarrello']	= getNotUndefined(params['idcarrello'],	'#listadesiderio');
	fun_config['todo']			= getNotUndefined(params['todo'],		'add');

	for (i=1; i<(args.length); i++){
		var serial1 = jQuery('input',jQuery(args[i])).serialize();
//		alert(serial1);
		parametri += "richiesta[" + fun_config['idcarrello'] + "][" + fun_config['todo'] + "][]="+escape(serial1);
	}
	return {parametri: parametri};
}
function ArticoloCarrello(params){ // ------- funzioni necessarie: getNotUndefined
	var fun_config = new Array();
	fun_config['page']			= 'carrello.php';
	fun_config['tipo']			= getNotUndefined(params['tipo'],		'listadesiderio');
	fun_config['idcarrello']	= getNotUndefined(params['idcarrello'],	'#listadesiderio');
	fun_config['esito']			= getNotUndefined(params['esito'],	'print');
	fun_config['parametri']		= getNotUndefined(params['parametri'],	'');
	
	var ajRequest = '', i=0;
	for (var key in fun_config){
		if (fun_config[key]!=''){
			if (i++>0) ajRequest += "&";
			if(key=='parametri'){
				ajRequest += fun_config[key];
			} else {
				ajRequest += "richiesta[" + fun_config['idcarrello'] + "][" + key + "]=" + fun_config[key];
			}
		}
	}
	AjaxRequestJson(ajRequest, config['ajax']['url']);
}

function CreateRequestAjax(fun_config){
	var i = 0, ajRequest = '', args = CreateRequestAjax.arguments;
	for (var key in fun_config){
		if (fun_config[key]!=''){
			if (i++>0) ajRequest += "&";
			if(key=='parametri'){
				ajRequest += fun_config[key];
			} else {
				ajRequest += "richiesta[" + fun_config['idhtml'] + "][" + key + "]=" + fun_config[key];
			}
		}
	}
	if (args.length>1){
		for (i=1; i<(args.length); i++){
			if (args[i]['valore']!=''){
				ajRequest += "&richiesta[" + fun_config['idhtml'] + "][" + args[i]['chiave'] + "]=" + args[i]['valore'];
			}
		}
	}
	return ajRequest;
}
function SerializeRequestAjax(){
	var serial1 = '', serialNow = '', args = SerializeRequestAjax.arguments;
	for (i=0; i<(args.length); i++){
		serialNow = jQuery('input, select, textarea',jQuery(args[i])).serialize();
		if (i>0 && serialNow!='') serialNow = '&' + serialNow;
		serial1 += serialNow;
	}
	return escape(serial1);
}
/*
jQuery("#carrello").click(function(){
	ArticoloCarrello({tipo: "carrello", idcarrello: "#test"});
});
jQuery("#listadesiderio").click(function(){
	ArticoloCarrello({tipo: "listadesiderio", idcarrello: "#test"});
});
*/



/* FINESTRA MODALE */
function modalOpen1 (dialog) {
	dialog.overlay.fadeIn('slow', function () {
		dialog.container.fadeIn('slow', function () {
			dialog.data.hide().slideDown('slow');	 
		});
	});
}
function modalClose1 (dialog) {
	dialog.data.fadeOut('slow', function () {
		dialog.container.hide('slow', function () {
			dialog.overlay.slideUp('slow', function () {
				$.modal.close();
			});
		});
	});
}
function modalShow1 (dialog) {
	$('input.animate').one('click', function () {
		dialog.data.slideUp('slow', function () {
			dialog.data.slideDown('slow');
		});
	});
}
/* FINESTRA MODALE */

