////////////////////////////////////////////////////////////////////////////////////////////////

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 YY_checkform() { //v4.71
//copyright (c)1998,2002 Yaromat.com
  var a=YY_checkform.arguments,oo=true,v='',s='',err=false,r,o,at,o1,t,i,j,ma,rx,cd,cm,cy,dte,at;
  for (i=1; i<a.length;i=i+4){
    if (a[i+1].charAt(0)=='#'){r=true; a[i+1]=a[i+1].substring(1);}else{r=false}
    o=MM_findObj(a[i].replace(/\[\d+\]/ig,""));
    o1=MM_findObj(a[i+1].replace(/\[\d+\]/ig,""));
    v=o.value;t=a[i+2];
    if (o.type=='text'||o.type=='password'||o.type=='hidden'){
      if (r&&v.length==0){err=true}
      if (v.length>0)
      if (t==1){ //fromto
        ma=a[i+1].split('_');if(isNaN(v)||v<ma[0]/1||v > ma[1]/1){err=true}
      } else if (t==2){
        rx=new RegExp("^[\\w\.=-]+@[\\w\\.-]+\\.[a-zA-Z]{2,4}$");if(!rx.test(v))err=true;
      } else if (t==3){ // date
        ma=a[i+1].split("#");at=v.match(ma[0]);
        if(at){
          cd=(at[ma[1]])?at[ma[1]]:1;cm=at[ma[2]]-1;cy=at[ma[3]];
          dte=new Date(cy,cm,cd);
          if(dte.getFullYear()!=cy||dte.getDate()!=cd||dte.getMonth()!=cm){err=true};
        }else{err=true}
      } else if (t==4){ // time
        ma=a[i+1].split("#");at=v.match(ma[0]);if(!at){err=true}
      } else if (t==5){ // check this 2
            if(o1.length)o1=o1[a[i+1].replace(/(.*\[)|(\].*)/ig,"")];
            if(!o1.checked){err=true}
      } else if (t==6){ // the same
            if(v!=MM_findObj(a[i+1]).value){err=true}
      }
    } else
    if (!o.type&&o.length>0&&o[0].type=='radio'){
          at = a[i].match(/(.*)\[(\d+)\].*/i);
          o2=(o.length>1)?o[at[2]]:o;
      if (t==1&&o2&&o2.checked&&o1&&o1.value.length/1==0){err=true}
      if (t==2){
        oo=false;
        for(j=0;j<o.length;j++){oo=oo||o[j].checked}
        if(!oo){s+='* '+a[i+3]+'\n'}
      }
    } else if (o.type=='checkbox'){
      if((t==1&&o.checked==false)||(t==2&&o.checked&&o1&&o1.value.length/1==0)){err=true}
    } else if (o.type=='select-one'||o.type=='select-multiple'){
      if(t==1&&o.selectedIndex/1==0){err=true}
    }else if (o.type=='textarea'){
      if(v.length<a[i+1]){err=true}
    }
    if (err){s+='- '+a[i+3]+'\n'; err=false}
  }
	var lingua ='ita';
	
	if (window.document.forms['newsletter']) {
		lingua = window.document.forms['newsletter'].lingua.value;
		
	}
	
	switch (lingua) {
			case 'ita':
				var myalert = 'ATTENZIONE!';				
			break;
			
			case 'eng':
				var myalert = 'ATTENTION!';				
			break;
			
			case 'deu':
				var myalert = 'ACHTUNG!';				
			break;
	}
	
	if (s!=''){alert(myalert+':\t\t\t\t\n\n'+s)}
  document.MM_returnValue = (s=='');
}


// FUNZIONI PER LA MAPPA V3
var infowindow,maps;var setDirection={options:{dirContainer:document.getElementById('dirContainer'),dirService:"",dirRenderer:"",myMarker:"",mapId:"",zoom:"",mapType:"",showCursor:""},set:function(mapId,optiones,zoom,mapType,showCursor){setDirection.options.mapId=mapId;setDirection.options.zoom=zoom;setDirection.options.mapType=mapType;setDirection.options.showCursor=showCursor;setDirection.options.myMarker=new Array();for(names in optiones)setDirection.options.myMarker[names]=optiones[names];setDirection.options.myMarker['infowindow']='<div id="ballon"><h5>'+setDirection.options.myMarker['labelTitle']+'</h5>'+setDirection.options.myMarker['infowindow']+'<br /><br />'+setDirection.options.myMarker['labelCalculate']+'<br /><a href="javascript:;" onclick="setDirection.init(\'<h5>'+setDirection.options.myMarker['labelTitle']+'</h5><br />'+setDirection.options.myMarker['labelCalculate']+'\', \''+setDirection.options.myMarker['labelFrom']+'\', \''+setDirection.options.myMarker['labelTo']+'\', \'FROM\', \''+setDirection.options.myMarker['lat']+', '+setDirection.options.myMarker['lon']+'\');" title="'+setDirection.options.myMarker['labelCalculate']+'"><strong>'+setDirection.options.myMarker['labelFrom']+'</strong></a> - <a href="javascript:;" onclick="setDirection.init(\'<h5>'+setDirection.options.myMarker['labelTitle']+'</h5><br />'+setDirection.options.myMarker['labelCalculate']+'\', \''+setDirection.options.myMarker['labelFrom']+'\', \''+setDirection.options.myMarker['labelTo']+'\', \'TO\', \''+setDirection.options.myMarker['lat']+', '+setDirection.options.myMarker['lon']+'\');" title="'+setDirection.options.myMarker['labelCalculate']+'"><strong>'+setDirection.options.myMarker['labelTo']+'</strong></a></div>';setDirection.openMap();},openMap:function(){var latlng=new google.maps.LatLng(setDirection.options.myMarker['lat'],setDirection.options.myMarker['lon']);if(setDirection.options.mapType==undefined)setDirection.options.mapType="ROADMAP";if(setDirection.options.showCursor==undefined)setDirection.options.showCursor=false;var myOptions={disableDefaultUI:setDirection.options.showCursor,mapTypeControl:false,mapTypeControlOptions:{style:google.maps.MapTypeControlStyle.DROPDOWN_MENU},zoom:setDirection.options.zoom,center:latlng,mapTypeId:google.maps.MapTypeId[setDirection.options.mapType]};maps=new google.maps.Map(document.getElementById(setDirection.options.mapId),myOptions);var myLatLng=new google.maps.LatLng(setDirection.options.myMarker['lat'],setDirection.options.myMarker['lon']);var marker=new google.maps.Marker({position:myLatLng,map:maps,icon:setDirection.options.myMarker['icon'],zIndex:10000});if(setDirection.options.myMarker['infowindow']!=""){infowindow=new google.maps.InfoWindow({content:setDirection.options.myMarker['infowindow'],maxWidth:350,position:myLatLng,zIndex:100});infowindow.open(maps,infowindow);google.maps.event.addListener(marker,"click",function(){infowindow.open(maps,infowindow);});}},init:function(myText,from,to,direction,latLan){if(document.getElementById('ballon')){setDirection.options.dirService=new google.maps.DirectionsService();setDirection.options.dirRenderer=new google.maps.DirectionsRenderer();var myFormDirection,textDirection;if(direction=="FROM"){myFormDirection='<form name="direction" action="javascript:;" method="get"><input id="from-input" type="hidden" value="'+latLan+'" />';myFormDirection+='<input id="to-input" type="text" value="" class="inputE" />';myFormDirection+='<input class="inputB" onclick="setDirection.getDirections(document.getElementById(\'from-input\').value, document.getElementById(\'to-input\').value);" type="button" value=">" /></form>';textDirection=myText+'<br /><strong>'+from+'</strong> - <a href="javascript:;" onclick="setDirection.init(\''+myText+'\', \''+from+'\', \''+to+'\', \'TO\', \''+latLan+'\');"><strong>'+to+'</strong></a>'+myFormDirection;}else{myFormDirection='<form name="direction" action="javascript:;" method="get"><input id="from-input" type="text" value="" class="inputE" />';myFormDirection+='<input id="to-input" type="hidden" value="'+latLan+'" />';myFormDirection+='<input class="inputB" onclick="setDirection.getDirections(document.getElementById(\'from-input\').value, document.getElementById(\'to-input\').value);" type="button" value=">" /></form>';textDirection=myText+'<br /><a href="javascript:;" onclick="setDirection.init(\''+myText+'\', \''+from+'\', \''+to+'\', \'FROM\', \''+latLan+'\');"><strong>'+from+'</strong></a> - <strong>'+to+'</strong>'+myFormDirection;}document.getElementById('ballon').innerHTML=textDirection;}},getDirections:function(fromStr,toStr){var dirRequest={origin:fromStr,destination:toStr,travelMode:google.maps.DirectionsTravelMode.DRIVING,unitSystem:google.maps.DirectionsUnitSystem.METRIC,provideRouteAlternatives:true};setDirection.options.dirService.route(dirRequest,setDirection.showDirections);},showDirections:function(dirResult,dirStatus){if(dirStatus!=google.maps.DirectionsStatus.OK){if(typeof(dirStatusErrora)!=undefined){alert(dirStatusError+"\n(Google reports: "+dirStatus+")");}else{alert("The address entered was not found\n(Google reports: "+dirStatus+")");}return;}setDirection.openMap();$('html,body').animate({scrollTop:$('#'+setDirection.options.mapId).offset().top-20},1000);setDirection.options.dirRenderer.setMap(null);setDirection.options.dirRenderer.setMap(maps);$('#dirContainer').html('');setDirection.options.dirRenderer.setPanel(document.getElementById('dirContainer'));setDirection.options.dirRenderer.setDirections(dirResult);}}
// FINE MAPPA


// Funzione per creare testo in javascript
var jbase64 = {
 _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
 encode : function (input) {
  var output = "";
  var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  var i = 0;
  input = jbase64._utf8_encode(input);
  while (i < input.length) {
   chr1 = input.charCodeAt(i++);
   chr2 = input.charCodeAt(i++);
   chr3 = input.charCodeAt(i++);
   enc1 = chr1 >> 2;
   enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
   enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
   enc4 = chr3 & 63;
   if (isNaN(chr2)) {
    enc3 = enc4 = 64;
   } else if (isNaN(chr3)) {
    enc4 = 64;
   }
   output = output +
   this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
   this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);
  }
  return output;
 },
 decode : function (input) {
  var output = "";
  var chr1, chr2, chr3;
  var enc1, enc2, enc3, enc4;
  var i = 0;
  input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
  while (i < input.length) {
   enc1 = this._keyStr.indexOf(input.charAt(i++));
   enc2 = this._keyStr.indexOf(input.charAt(i++));
   enc3 = this._keyStr.indexOf(input.charAt(i++));
   enc4 = this._keyStr.indexOf(input.charAt(i++));
   chr1 = (enc1 << 2) | (enc2 >> 4);
   chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
   chr3 = ((enc3 & 3) << 6) | enc4;
   output = output + String.fromCharCode(chr1);
   if (enc3 != 64) {
    output = output + String.fromCharCode(chr2);
   }
   if (enc4 != 64) {
    output = output + String.fromCharCode(chr3);
   }
  }
  output = jbase64._utf8_decode(output);
  return output;
 },
 _utf8_encode : function (string) {
  string = string.replace(/\r\n/g,"\n");
  var utftext = "";
  for (var n = 0; n < string.length; n++) {
   var c = string.charCodeAt(n);
   if (c < 128) utftext += String.fromCharCode(c);
   else if((c > 127) && (c < 2048)) {
    utftext += String.fromCharCode((c >> 6) | 192);
    utftext += String.fromCharCode((c & 63) | 128);
   } else {
    utftext += String.fromCharCode((c >> 12) | 224);
    utftext += String.fromCharCode(((c >> 6) & 63) | 128);
    utftext += String.fromCharCode((c & 63) | 128);
   }
  }
  return utftext;
 },
 _utf8_decode : function (utftext) {
  var string = "";
  var i = 0;
  var c = c1 = c2 = 0;
  while ( i < utftext.length ) {
   c = utftext.charCodeAt(i);
   if (c < 128) {
    string += String.fromCharCode(c);
    i++;
   } else if((c > 191) && (c < 224)) {
    c2 = utftext.charCodeAt(i+1);
    string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
    i += 2;
   } else {
    c2 = utftext.charCodeAt(i+1);
    c3 = utftext.charCodeAt(i+2);
    string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
    i += 3;
   }
  }
  return string;
 }
}

// Funzione go top della pagina
function go_top(topper){
	var scrOfY = 0;
	if( typeof( window.pageYOffset ) == 'number' ) {
		scrOfY = window.pageYOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		scrOfY = document.body.scrollTop;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		scrOfY = document.documentElement.scrollTop;
	}
	if (topper == "null"){
		topper = scrOfY;
	} else {
		topper = topper;
	}
	var new_topper = Math.round(topper/10)*1;
	
	if ((topper-new_topper)>5){
		scrollTo(0, (topper-new_topper));
		setTimeout('go_top('+((topper*1)-(new_topper*1))+')',10);
	} else {
		scrollTo(0, 0);
		return false;
	}
}

// Funzione go to per una pagina
function go_to(id, initial){
	if (document.getElementById(id)){
		my_id = id;
		if (initial == undefined){
			//alert("123");
			setTimeout("go_to(my_id, 1)",1000);
			return;
		} else {
			var scrOfY = 0;
			var mio_blocco = document.getElementById(id);
			var scr2fY = mio_blocco.offsetTop;
			var mia_pagina = document.getElementById('page');
			var altezza_pagina = mia_pagina.offsetHeight + 150;
			var altezza_body = 0;
			if( typeof( window.pageYOffset ) == 'number' ) {
				scrOfY = window.pageYOffset;
				altezza_body = document.body.offsetHeight;
			} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
				scrOfY = document.body.scrollTop;
				altezza_body = document.body.offsetHeight;
			} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
				scrOfY = document.documentElement.scrollTop;
				altezza_body = document.body.offsetHeight;
			}
			
			var topper = -(scrOfY - scr2fY);
			
			var new_topper = scrOfY + (Math.round(topper/40)*1);
					
			if ((-new_topper + scr2fY) > 5){
				if (altezza_pagina > (new_topper + altezza_body)){
					scrollTo(0, new_topper);
					setTimeout("go_to(my_id, 1)",10);
				} else {
					return false;
				}
			} else {
				scrollTo(0, scr2fY);
				return false;
			}
		}
	} else {
		alert("Elemento " + id + " inesistente.");
	}
}

/*******************************************************   LINKS IN JAVASCRIPT */

function goToUrl(enUrl){
	
	var decUrl = jbase64.decode(enUrl);
	location.href=''+decUrl+'';	
}


// Funzione per l'inserimento della shadowbox
function shadowRel(){
	$('a.shadowBox').each(function() {
		$(this).attr('rel', 'shadowbox['+ $(this).attr('class').replace(/ /g, '_') +']');
	});
}

function shadowRelTable(){
	$('a.shadowBoxTable').each(function() {
		$(this).attr('rel', 'shadowbox['+ $(this).attr('class').replace(/ /g, '_') +']width=810;height=410');
	});
}

//=============================== APPLICA OPZIONE

function applyOption(option_category_id, option_id, caller) {
	var form_id = $(caller).parents('form').attr('id');
	
	// resetto le opzione precedentemente settate
	$('#'+form_id+' .tabs-'+option_category_id+' a').removeClass('selected');	// ...resetto tutti le opzioni dentro le pagine...
	$('#'+form_id+' .tabs-'+option_category_id+' .popup2').hide();
	
	// associo la classe selected all'opzione scelta
	$(caller).addClass('selected');
	$(caller).next().css("display","block");
	// aggiungo un campo hidden al form di acquisto del prodotto, contenente le informazioni relative all'opzione scelta per una data variante
	$('#'+form_id+' .opt_'+option_category_id).remove();
	$('#'+form_id).append('<input type="hidden" class="opt_'+option_category_id+'" name="variante['+option_category_id+']" value="'+option_id+'" />');
}

// Funzione per l'effetto sfumatura nelle scritte del menù laterale
$(function() {
	rainbows.init({
		selector: '#menulat li a strong, #menulat_2 li a strong',
		shadow: true,
		from: '#f7f7f7',
		to: '#a5a5a5'
	});
});



$(document).ready(function() {

	// Accordion Menù  ///////////////
	$("#menulat").accordion({header:'li a.category', active:false, navigation:true, autoHeight:false});
	var active = $('li.active a.category').attr('id');
	$("#menulat").accordion('activate',$('#'+active));
	
	// ----- Funzione per la gallery delle offerte in home -----//
	var gallery = $('#content_list_offers');
	var img_gallery = $('#content_list_offers li').length-3;
	var spostamento = 0;
		
	
	$('#list_offerte span.dx').click(function(){ 
		if ((spostamento < img_gallery) && (!gallery.is(':animated'))) {
			gallery.stop(true).animate({left:'+=-240px'});
			spostamento++;
		}
	});
	
	$('#list_offerte span.sx').click(function(){
		if ((spostamento > 0) && (!gallery.is(':animated'))) {
			gallery.stop(true).animate({left:'+=240px'});
			spostamento--;
		}
		
	});
	
	
	// Funzione per lo scroll
	window.onscroll = function()
		{
			if( window.XMLHttpRequest ) { // IE 6 doesn't implement position fixed nicely...
				var divScroll = document.documentElement.scrollTop;
				if (divScroll > 267) {
					$('#scrollBox').css({'position':'absolute', 'top':(divScroll-267+55)+'px','right':'0'}); 
				} else {
					$('#scrollBox').css({'position':'absolute', 'top':'55px', 'right':'0'});
				}
			}
		}
	
	// Init della shadowbox
	shadowRel();
	shadowRelTable();
	Shadowbox.init();
	
	// Zoom Immagini 
	$('.bubbleInfo').each(function () {
		// options
		var distance = 10;
		var time = 250;
		var hideDelay = 500;
	
		var hideDelayTimer = null;
	
		// tracker
		var beingShown = false;
		var shown = false;
		
		var trigger = $('.trigger', this);
		var popup = $('.popup', this).css('opacity', 0);
	
		// set the mouseover and mouseout on both element
		$([trigger.get(0), popup.get(0)]).mouseover(function () {
		  // stops the hide event if we move from the trigger to the popup element
		  if (hideDelayTimer) clearTimeout(hideDelayTimer);
	
		  // don't trigger the animation again if we're being shown, or already visible
		  if (beingShown || shown) {
			return;
		  } else {
			beingShown = true;
	
			// reset position of popup box
			popup.css({
			  top: -120,
			  left: 100,
			  display: 'block' // brings the popup back in to view
			})
	
			// (we're using chaining on the popup) now animate it's opacity and position
			.animate({
			  top: '-=' + distance + 'px',
			  opacity: 1
			}, time, 'swing', function() {
			  // once the animation is complete, set the tracker variables
			  beingShown = false;
			  shown = true;
			});
		  }
		}).mouseout(function () {
		  // reset the timer if we get fired again - avoids double animations
		  if (hideDelayTimer) clearTimeout(hideDelayTimer);
		  
		  // store the timer so that it can be cleared in the mouseover if required
		  hideDelayTimer = setTimeout(function () {
			hideDelayTimer = null;
			popup.animate({
			  top: '-=' + distance + 'px',
			  opacity: 0
			}, time, 'swing', function () {
			  // once the animate is complete, set the tracker variables
			  shown = false;
			  // hide the popup entirely after the effect (opacity alone doesn't do the job)
			  popup.css('display', 'none');
			});
		  }, hideDelay);
		});
	  });
	  
	// Zoom Immagine Variante Colori per i Prodotti 
	$('.bubbleInfo2').each(function () {
		// options
		var distance = 10;
		var time = 250;
		var hideDelay = 150;
			
		var hideDelayTimer = null;
	
		// tracker
		var beingShown = false;
		var shown = false;
		
		var trigger = $('.trigger', this);
		var popup = $('.popup2', this).css('opacity', 0);
	
		// set the mouseover and mouseout on both element
		$([trigger.get(0), popup.get(0)]).mouseover(function () {
		  // stops the hide event if we move from the trigger to the popup element
		  if (hideDelayTimer) clearTimeout(hideDelayTimer);
	
		  // don't trigger the animation again if we're being shown, or already visible
		  if (beingShown || shown) {
			return;
		  } else {
			beingShown = true;
	
			// reset position of popup box
			popup.css({
			  top: -65,
			  left: -20,
			  display: 'block' // brings the popup back in to view
			})
	
			// (we're using chaining on the popup) now animate it's opacity and position
			.animate({
			  top: '-=' + distance + 'px',
			  opacity: 1
			}, time, 'swing', function() {
			  // once the animation is complete, set the tracker variables
			  beingShown = false;
			  shown = true;
			});
		  }
		}).mouseout(function () {
			if(!$(this).parent().hasClass('selected')){
			  //console.log(this);
			  // reset the timer if we get fired again - avoids double animations
			  if (hideDelayTimer) clearTimeout(hideDelayTimer);
			  
			  // store the timer so that it can be cleared in the mouseover if required
			  hideDelayTimer = setTimeout(function () {
				hideDelayTimer = null;
				popup.animate({
				  top: '-=' + distance + 'px',
				  opacity: 0
				}, time, 'swing', function () {
				  // once the animate is complete, set the tracker variables
				  shown = false;
				  // hide the popup entirely after the effect (opacity alone doesn't do the job)
				  popup.css('display', 'none');
				});
			  }, hideDelay);
			}
		});
	  });
	  
	  // Controllo inserimento valori varianti obbligatorie (Colori e Taglie)
	  $('.add_to_cart').submit(function(){
			id = $(this).attr('id');
			var opt1_checked = $('#'+id+' .opt_1');
	  		var opt2_checked = $('#'+id+' .opt_2');
			var tabs_1 = $('#'+id+' .tabs-1');
	  		var tabs_2 = $('#'+id+' .tabs-2');

			if(opt1_checked.length > 0 && opt2_checked.length > 0) {
				return true;
			} else {
				if(opt1_checked.length == 0){
					$('.tabs-1 p.error').remove();
					$('#'+id+' .tabs-1 p.selTaglie').remove();
					tabs_1.append('<p class="error">&lsaquo; Seleziona la Taglia</p>');
				} 
				if(opt2_checked.length == 0){
					$('.tabs-2 p.error').remove();
					$('#'+id+' .tabs-2 p.selColori').remove();
					tabs_2.append('<p class="error">&lsaquo; Seleziona il Colore</p>');
				}
				return false;	
			}
			
	  });
	  
	  $('.tabs-1 ul li a').click(function(){
	  		$('.tabs-1 p.error').remove();
	  })
	  $('.bubbleInfo2 a').click(function(){
	  		$('.tabs-2 p.error').remove();
	  })

});
