 $(document).ready(function() {

     // LEGENDA
     if ($.cookie('show_legenda')=='true') $('#legenda div').show();
     $('#legenda a').bind('click', function() {
         if($('#legenda div').css('display') == 'none') {
             $.cookie('show_legenda', 'true');
             $('#legenda div').show();
         }
         else {
             $.cookie('show_legenda', 'false');
             $('#legenda div').hide();
         }
         return false;
     });

     // SUBMIT
     $('a.submit').bind('click', function() {
        $(this).parents('form:eq(0)').submit();
        return false;
    });
    $('.form-ar').bind('keypress', function(e) {
        if (e.which==13) {
            $(this).parents('form:eq(0)').submit();
        }
    });

     // SUBMENU
     $('.submenu_act').bind('click', function() {
         $('#' + $(this).attr('rel')).toggle();
     });

     // CALCOLO PREVENTIVO
     $('.txt-prevent').bind('blur', function() {
         if (!isInt($(this).val())) $(this).val(0);
         var somma = 0;
         $('.txt-prevent').each(function() {
             var qta = $(this).val();
             var prezzo = $(this).attr('rel');
             somma += parseInt(qta) * parseFloat(prezzo);
         });
         $('#somma').val(somma.toFixed(2));
     }).bind('focus', function() {
         $(this).select();
     });

     // CALENDARIO
     $.datepicker.setDefaults($.extend({
         showMonthAfterYear: false,
         dateFormat: 'dd/mm/yy',
         showOn: 'button',
         buttonImage: 'images/catalogo/bott-scegli.gif',
         buttonImageOnly: true,
         duration: ''
     }, $.datepicker.regional['']));
     $("#datada").datepicker($.datepicker.regional['it']);
     $("#dataa").datepicker($.datepicker.regional['it']);

     // POPUP FOTO
     $('.link_foto').fancybox({
         overlayShow: false
     });
     if ($('#link-sostituito').length>0) {
         $('#link-sostituito').fancybox({
             overlayShow: false,
             frameWidth: 320,
             frameHeight: 80
         });
         $('#link-sostituito').click();
     }

     // VALIDAZIONI

     // ricerca marca modello
     $('form[name=r1]').submit(function() {
         if ($('select[name=idv]', this).length==0) {
             alert('Attenzione!\nCompletare la selezione del veicolo.')
            return false;
         }
        return true;
     });

     // ricerca per articolo
     $('form[name=r2]').submit(function() {
        if ($.trim( $('input[name=codice]', this).val() ) == '') {
            alert('Attenzione!\nCodice ricercato non valido.')
            return false;
        }
        return true;
     });
 });

 function show_popup(img_src) {
    var posy = document.documentElement.scrollTop;
    posy = posy + 50;
    var posx = 50;
    //var posx = (screen.width/2) - (popupImage.width/2);
    
    document.getElementById("div_foto").style.top = posy+"px";
    document.getElementById("div_foto").style.left = posx+"px";
    
    document.getElementById("img_popup").src=img_src;
    document.getElementById("div_foto").style.visibility="visible";
    
    document.getElementById("div_foto").style.left = posx+"px";
}

function hide_popup() {
	document.getElementById("div_foto").style.visibility="hidden";
	document.getElementById("img_popup").src="";
}

function ResetScrollPosition() {
	if (document.getElementById("ScrollX")!=null) {
		var hidx, hidy;
		hidx = document.getElementById("ScrollX");
		hidy = document.getElementById("ScrollY");
		if (typeof hidx != 'undefined' && typeof hidy != 'undefined') {
			window.scrollTo(hidx.value, hidy.value);
		}
	}
}
    
function setPval(val) {
	if (val=="")
		p_val = 0;
	else
		p_val = val;
}

function calcola(input, prezzo) {
	n_val = input.value;
	
	if (n_val>p_val)
		somma_val = somma_val+((n_val-p_val)*prezzo);
	if (n_val<p_val)
		somma_val = somma_val-((p_val-n_val)*prezzo);
	
	document.getElementById("somma").value = somma_val.toFixed(2);
}


function isInt(x) {
    var y=parseInt(x);
    if (isNaN(y)) return false;
    return x==y && x.toString()==y.toString();
} 
function controllaQta() {
    var qta = document.getElementById("carrello_qta").value;
    if (isInt(qta) && qta!="0") {
        return true;
    }
    else {
        alert("La quantita' deve essere maggiore di 0");
        return false;
    }
}

function show_prompt(codred, prezzo, qtainord, note) {
    show_prompt(codred, prezzo, qtainord, note, -1);
}
function show_prompt(codred, prezzo, qtainord, note, idart) {
    url = window.location.href;
    arr = url.split("&").join(",");
    document.getElementById("carrello_pagina").value=arr;
    document.getElementById("carrello_qta").value=qtainord;
    document.getElementById("carrello_note").value=note;
    document.getElementById("carrello_ask").innerHTML="<div>"+codred+"</div>";
    if(qtainord>0) {
        document.getElementById("avvisoord").innerHTML="<strong><font size=\"2\">L'articolo e' gia' in ordine.</font></strong><br />Vuoi modificare la quantita'?";
    }
    else {
        document.getElementById("avvisoord").innerHTML="Quanti pezzi vuoi aggiungere?";
        document.getElementById("carrello_qta").value='1';
    }
    document.getElementById("carrello_idart").value=idart;
    
    var w="300";
    var h="250";
    
    var objdiv = document.getElementById("div_form").style;
    
    xc=Math.round((document.body.clientWidth/2)-(w/2))
    yc=Math.round(document.documentElement.scrollTop+((document.documentElement.clientHeight/2)-(h/2)))

    objdiv.left = xc + "px"
    objdiv.top = yc + "px";
    document.getElementById("div_form").style.visibility="visible";
    document.getElementById("carrello_codred").value=codred;
    document.getElementById("carrello_prezzo").value=prezzo;
    document.getElementById("carrello_qta").focus();
    document.getElementById("carrello_qta").select();
}

function hide_prompt() {
	document.getElementById("div_form").style.visibility="hidden";
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
	var daconvertire = selObj.options[selObj.selectedIndex].value;
	eval(targ+".location=daconvertire");
	if (restore) selObj.selectedIndex=0;
}
function MM_jumpMenu2(targ,selObj,restore){ //v3.0
	var scrollx = document.documentElement.scrollLeft;
	var scrolly = document.documentElement.scrollTop;

	var daconvertire = selObj.options[selObj.selectedIndex].value+"&ScrollX="+scrollx+"&ScrollY="+scrolly;
	eval(targ+".location=daconvertire");
	if (restore) selObj.selectedIndex=0;
}


function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function checkform( form1 ) {
	var testo="Attenzione : \n";
	var ch=true;
	
        if (form1.name=="mod") {
            if (form1.mod.value == "%" && form1.cat.value == "%") {
		testo += "Selezionare una marca\n e un modello oppure una categoria!\n";
		ch=false;	 
		}
            }
                
        if (form1.name=="ord") {
                if (form1.qta.value=="" || form1.qta.value=="0" || form1.codice.value=="") {
                    testo += "Valori non validi";
                    ch=false;
                }
            }
            
        if (form1.name=="r2") {
		if (form1.codice.value=="") {
			testo += "Inserire almeno una parte del codice.";
			ch=false;
		}
	}
        
        if (form1.name=="r1") {
            //if (form1.mod.value!='%' && (form1.cil.value=="" || form1.anno.value=="" || form1.motore.value=="")) {
            if (form1.mod.value=='%' && form1.cat.value=="%") {
                testo += "Completa la selezione del veicolo.";
                ch=false;
            }
            else if (form1.cat.value=='%' && (form1.mod.value=='%' || form1.cil.value=='%' || 
                     form1.anno.value=='%' || form1.m.value=='%')) {
                testo += "Completa la selezione del veicolo.";
                ch=false;
            }
        }
        
	if(!ch) {
            alert(testo);
            return false;
	}
        return true;
}

// Disable "Enter" key in Form script- By Nurul Fadilah(nurul@REMOVETHISvolmedia.com)
// This notice must stay intact for use
// Visit http://www.dynamicdrive.com/ for full source code
function handleEnter (field, event) {
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	if (keyCode == 13) {
		var i;
		for (i = 0; i < field.form.elements.length; i++)
			if (field == field.form.elements[i])
				break;
		i = (i + 1) % field.form.elements.length;
		field.form.elements[i].focus();
		return false;
	} 
	else
	return true;
}

function editQta(id, qta, codred, note) {
  url = window.location.href;
  arr = url.split("&").join(",");
  document.getElementById("editqta_pagina").value=arr;
  document.getElementById("editqta_qta").value=qta;
  document.getElementById("editqta_ask").innerHTML="<div>"+codred+"</div>";
  document.getElementById("editqta_note").value=note;
  var w="300";
  var h="250";

  var objdiv = document.getElementById("div_form").style;

  xc=Math.round((document.body.clientWidth/2)-(w/2))
  yc=Math.round(document.documentElement.scrollTop+((document.documentElement.clientHeight/2)-(h/2)))

  objdiv.left = xc + "px"
  objdiv.top = yc + "px";

  document.getElementById("div_form").style.visibility="visible";
  document.getElementById("editqta_codred").value=codred;
  document.getElementById("editqta_note").value=note;
  document.getElementById("editqta_id").value=id;
  document.getElementById("editqta_qta").focus();
  document.getElementById("editqta_qta").select();
}
