jQuery.fn.exists = function(){return jQuery(this).length>0;}


var hexDigits = new Array
        ("0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"); 

//Function to convert hex format to a rgb color
function rgb2hex(rgb) {
 rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
 return hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

function hex(x) {
  return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16];
 }

$(document).ready(function(){
	
	//ANIMAZIONE MENU TERZO LIVELLO
	//$('#menuLeftLiv3 ul li').click(function(){

     //if($(this).children('ul').css('display')=='none')
	  //{
		//$('#menuLeftLiv3 ul li ul').slideUp();        
        //$(this).children('ul').slideDown();
	  //}
	 //else if($(this).children('ul').css('display')=='block')
	  //{
        //$(this).children('ul').slideUp();
	  //}

     //return false;
  //})

  // MOSTRA NASCONDI

	$(function(){

	// The height of the content block when it's not expanded
	var adjustheight = 168;
	// The "more" link text
	var moreText = "Leggi tutto";
	// The "less" link text
	var lessText = "Nascondi";
	
	
	//alert($(".more-less .more-block").css('height').replace('px','')+' | '+adjustheight)
	
	moreBlockHeight = $(".more-less .more-block").css('height');
	
	if(moreBlockHeight != null)
	{
	if(moreBlockHeight.replace('px','')<adjustheight)
	{
		// The section added to the bottom of the "more-less" div
		$(".more-less").append('<span class="content_adjust"></span>');
	}
	else
	{

	 // Sets the .more-block div to the specified height and hides any content that overflows
	 $(".more-less .more-block").css('height', adjustheight).css('overflow', 'hidden');
		// The section added to the bottom of the "more-less" div		
	  $(".more-less").append('<p class="continued">[...]</p><span class="content_adjust"><a href="#" class="adjust"></a></span>');
	}
	}


	
	//

	$("a.adjust").text(moreText);

	$(".adjust").toggle(function() {
			$(this).parents("div:first").find(".more-block").css('height', 'auto').css('overflow', 'visible');
			// Hide the [...] when expanded
			$(this).parents("div:first").find("p.continued").css('display', 'none');
			$(this).text(lessText);
		}, function() {
			$(this).parents("div:first").find(".more-block").css('height', adjustheight).css('overflow', 'hidden');
			$(this).parents("div:first").find("p.continued").css('display', 'block');
			$(this).text(moreText);
	});
	});

// FINE MOSTRA NASCONDI

  // MOSTRA NASCONDI DESCRIZIONE PV

	$(function(){

	// The height of the content block when it's not expanded
	var adjustheight = 125;
	// The "more" link text
	var moreText = "Maggiori info";
	// The "less" link text
	var lessText = "Chiudi";

	// Sets the .more-block div to the specified height and hides any content that overflows
	$(".more-less-pv .more-block-pv").css('height', adjustheight).css('overflow', 'hidden');

	// The section added to the bottom of the "more-less" div
	$(".more-less-pv").append('<p class="continued-pv" style="display:none;">[...]</p><a href="#" class="adjust-pv"></a>');

	$("a.adjust-pv").text(moreText);

	$(".adjust-pv").toggle(function() {
			$(this).parents("div:first").find(".more-block-pv").css('height', 'auto').css('overflow', 'visible');
			// Hide the [...] when expanded
			$(this).parents("div:first").find("p.continued-pv").css('display', 'none');
			$(this).text(lessText);
		}, function() {
			$(this).parents("div:first").find(".more-block-pv").css('height', adjustheight).css('overflow', 'hidden');
			$(this).parents("div:first").find("p.continued-pv").css('display', 'none');//block
			$(this).text(moreText);
	});
	});

// FINE MOSTRA NASCONDI DESCRIZIONE PV
   	
	$('#menu_top>li').each(function(){
		
		idCatalogo = $(this).attr('id');		
		
		$(this).children('a').css('background-image','url('+wwwRoot+'/comuni/img/menu/top/'+idCatalogo+'.gif)').html('');
		$(this).children('a:not(.selected)').mouseenter(function(){
			$(this).css('background-position','0px -10px');
		});
		$(this).children('a:not(.selected)').mouseleave(function(){
			$(this).css('background-position','0px 0px');
		})
	})
	
	
	
	$('#menu_catalogo>li').each(function(){
		
		idCatalogo = $(this).attr('id');
		statusMenu = $(this).attr('class');
		
		//alert(statusMenu)
		
		$(this).children('a').html('<img src="'+wwwRoot+'/comuni/img/menu/catalogo/'+idCatalogo+'.gif">');
		
		$(this).children('div').css('background-image','url('+wwwRoot+'/comuni/img/menu/catalogo/bg/'+idCatalogo+'_bg_btm.gif)');
		$(this).children('div').children('div').css('background-image','url('+wwwRoot+'/comuni/img/menu/catalogo/bg/'+idCatalogo+'_bg_top.gif)');
		
		
		if(statusMenu!='selected')
		{
			$(this).children('a').mouseenter(function(){
				
				//$(this).parent().children('div').fadeIn('fast');
				$(this).parent().children('div').show();
				
			})
			
			
			$(this).mouseleave(function(){
				$(this).children('div').fadeOut('fast');
				
			})
		}
		
	})

	$('div.form_newsletter div.first div.campi input.errore').keypress(function() {
		//alert('test');
		//$(this).attr('class','');
		//$('div#errore').fadeOut();
		$('div#errore').hide();
	})

	$('div.radio  span.si_no input').change(function() {
		//alert('test');
		//$(this).parent().attr('class','si_no');
		//$('div#errore').fadeOut();
		$('div#errore').hide();
	})
	
	$('ul.internal>li').each(function() {
		
		NameSection = $(this).parent().attr('rel');
		NameIcons = $(this).attr('rel');		
		//alert(NameSection);
		//alert(NameIcons);
		//$(this).children('a').css('background-image','url('+wwwRoot+'/comuni/img/menu/catalogo/icons/'+NameSection+'/'+NameIcons+'.gif)');
		$(this).children('a').css('background-image','url('+wwwRoot+'/media/icons/'+NameSection+'/'+NameIcons+'.gif)');
		$(this).children('a').mouseenter(function(){
			$(this).css('background-position','0px -30px');
		});
		$(this).children('a').mouseleave(function(){
			$(this).css('background-position','0px 0px');
		})			
	})
	
	$('div.content div.icons').each(function() {
		NameSection = $(this).parent().attr('rel');		
		NameIcons = $(this).attr('rel');
		//alert(NameSection);		
		//alert(NameIcons);
		//$(this).css('background-image','url('+wwwRoot+'/comuni/img/menu/catalogo/icons/'+NameSection+'/'+NameIcons+'.gif)');
		$(this).css('background-image','url('+wwwRoot+'/media/icons/'+NameSection+'/'+NameIcons+'.gif)');
		$(this).css('background-position','0px -30px');
	})
	
	$('#buttonSitemapPromo>li').each(function() {
		
		idImgButton = $(this).attr('id');
		
		$(this).children('a').css('background-image','url('+wwwRoot+'/comuni/img/'+idImgButton+'.gif)').html('');
		//alert(idButton);
		$(this).children('a').click(function() {
			idButton = $(this).parent().attr('id').replace('button','');
			id_visible_box = $('.sitemapPromoBox:visible').attr('id');
			//alert(id_visible_box+"||"+idButton)
			//alert(idButton);

			if(id_visible_box != idButton)
			{
			$('.sitemapPromoBox').fadeOut();
			$('#'+idButton).fadeIn();
			}			
		})			
	})
	$('#InfoPuntoVendita li#changePuntoVendita a').click(function() {
		$(this).parent().parent().css('display','none');
		$('#changeSelectPuntoVendita').css('display','block');
	})
	//$('input[type=checkbox]').prettyCheckboxes();
	
	
	//$("a[rel^='prettyPhoto']").prettyPhoto();	
		
	
	$("a[rel=example_group]").fancybox({
		'transitionIn'		: 'elastic',
		'transitionOut'		: 'none',
		'titlePosition' 	: 'over',		
		'opacity'		: true,
		'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
		return '<span id="fancybox-title-over">Img. ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
			}
	});
	$(".linkPrivacy").fancybox({
		'width'				: 404,
		'height'			: 504,
        'autoScale'     	: false,
        'transitionIn'		: 'elastic',
		'transitionOut'		: 'none',
		'type'				: 'iframe'
	});
	$(".linkCatalogo_2011").fancybox({
		'width'				: 880,
		'height'			: 570,
        'autoScale'     	: false,
        'transitionIn'		: 'elastic',
		'transitionOut'		: 'none',
		'type'				: 'iframe'
	});

	
	$(function(){
        $("div.immagine_prodotto").carousel({animSpeed: "fast"});
    }); 
    $(function(){
        $("div.carousel_prodotti").carousel({animSpeed: "slow"});
    });    
    $(function(){					
		$("div.promo_home_page").carousel({ pagination: true, autoSlide: true, autoSlideInterval: 6000, animSpeed: "fast"});
	});
    $(function(){					
		$("div.promo_pv").carousel({ pagination: true, autoSlide: true, autoSlideInterval: 6000, animSpeed: "fast"});
	});	

	$(function(){		
		$("div#content_top_punti_vendita>span#title").css('background-image','url('+wwwRoot+'/comuni/img/punti_vendita/title_punti_vendita.gif)').css('background-repeat','no-repeat').html('');		
		$("div#content_top_punti_vendita>span#scheda").css('background-image','url('+wwwRoot+'/comuni/img/punti_vendita/title_scheda_punto_vendita.gif)').css('background-repeat','no-repeat').html('');
		$("div#content_top_chi_siamo>span#scheda.cooperativa").css('background-image','url('+wwwRoot+'/comuni/img/chi_siamo/title_chi_siamo_cooperativa.gif)').css('background-repeat','no-repeat').html('');		
		$("div#content_top_chi_siamo>span#scheda.vision").css('background-image','url('+wwwRoot+'/comuni/img/chi_siamo/title_chi_siamo_vision.gif)').css('background-repeat','no-repeat').html('');
		$("div#content_top_chi_siamo>span#scheda.mission").css('background-image','url('+wwwRoot+'/comuni/img/chi_siamo/title_chi_siamo_mission.gif)').css('background-repeat','no-repeat').html('');
		$("div#content_top_chi_siamo>span#scheda.contatti").css('background-image','url('+wwwRoot+'/comuni/img/chi_siamo/title_chi_siamo_contatti.gif)').css('background-repeat','no-repeat').html('');
		$("div#content_top_chi_siamo>span#scheda.rassegna_stampa").css('background-image','url('+wwwRoot+'/comuni/img/chi_siamo/title_chi_siamo_rassegna_stampa.gif)').css('background-repeat','no-repeat').html('');
		$("div#content_top_servizi>span#scheda.scopri_servizi").css('background-image','url('+wwwRoot+'/comuni/img/servizi/title_servizi_scopri_servizi.gif)').css('background-repeat','no-repeat').html('');
		$("div#content_top_servizi>span#scheda.magazine").css('background-image','url('+wwwRoot+'/comuni/img/servizi/title_servizi_magazine.gif)').css('background-repeat','no-repeat').html('');
		$("div#content_top_servizi>span#scheda.elenco_articoli").css('background-image','url('+wwwRoot+'/comuni/img/servizi/magazine/elenco_articoli.gif)').css('background-repeat','no-repeat').html('');
		
		$("div#content_top_servizi>span#scheda.io_card").css('background-image','url('+wwwRoot+'/comuni/img/servizi/title_servizi_io_card.gif)').css('background-repeat','no-repeat').html('');
		$("div#content_top_servizi>form span#scheda.newsletter").css('background-image','url('+wwwRoot+'/comuni/img/servizi/title_servizi_newsletter.gif)').css('background-repeat','no-repeat').html('');
		$("div#content_top_servizi>span#scheda.newsletter").css('background-image','url('+wwwRoot+'/comuni/img/servizi/title_servizi_newsletter.gif)').css('background-repeat','no-repeat').html('');
		$("div#content_top_servizi>span#scheda.facebook").css('background-image','url('+wwwRoot+'/comuni/img/servizi/title_servizi_facebook.gif)').css('background-repeat','no-repeat').html('');
		$("div#titolo_io_mi_vesto").css('background-image','url('+wwwRoot+'/comuni/img/io_mi_vesto/title_io_mi_vesto.gif)').css('background-repeat','no-repeat').html('');
	})

	renderCheckbox();
	renderTitles();
	imgCatRenderTitle();	
	$(document).pngFix();
	selectPuntoVendita();
	selectPuntoVenditaAll();
	selectPuntoVenditaNewsletter();
	selectEtaFigli();
	abilitaFiltri();
	ricercaProdotto();
})

//CHECK BOX
	function renderCheckbox()
	{
	  $('input[type="checkbox"]:not([rel^="checkbox"])').each(function(){
		randomId = 'checkbox_'+Math.floor(Math.random()*999999999999);
		id      = $(this).attr('id');
		id      = $(this).attr('rel',randomId);
		checked = $(this).attr('checked');
		$(this).after('<div class="checkbox" rel="'+randomId+'"></div>');
		if($('input[rel="'+randomId+'"]').attr('checked')==false)
		{
			$('div[rel="'+randomId+'"]').css('background-position','0px 0px ');
		}
		else if($('input[rel="'+randomId+'"]').attr('checked')==true)
		{
			$('div[rel="'+randomId+'"]').css('background-position','0px -17px');
		}
		$(this).css('display','none');
	});
	
	$('.checkbox').click(function(){
		
		
		id = $(this).attr('rel');
		fieldName = ($('input[rel="'+id+'"]').attr('name').replace("[]",""));
		

			
		if($('input[rel="'+id+'"]').attr('checked')==false)
		{
			if($('input[rel="'+id+'"]').attr('value')=='tutte')
			{
				$('input[name^="'+fieldName+'"]').attr('checked',true);
			  $('input[name^="'+fieldName+'"]').each(function(){
			  	$('div[rel="'+$(this).attr('rel')+'"]').css('background-position','0px -17px ');
			  });
			}
			else
			{
			  $('input[name^="'+fieldName+'"]').each(function(){
 
			  	//alert($(this).val())
			  	
			  	if($(this).val()=='tutte')
			  	{
			  		$(this).attr('checked',false);
			  	  $('div[rel="'+$(this).attr('rel')+'"]').css('background-position','0px 0px ');
			  	}
			  });
			}
			$('input[rel="'+id+'"]').attr('checked',true);
			$(this).css('background-position','0px -17px ');
		}
		else if($('input[rel="'+id+'"]').attr('checked')==true)
		{
			if($('input[rel="'+id+'"]').attr('value')=='tutte')
			{
				$('input[name^="'+fieldName+'"]').attr('checked',false);
			  $('input[name^="'+fieldName+'"]').each(function(){
			  	$('div[rel="'+$(this).attr('rel')+'"]').css('background-position','0px 0px ');
			  });
			}
			
			$('input[rel="'+id+'"]').attr('checked',false);
			$(this).css('background-position','0px 0px');
		}
	})

	

	
	
	}	
	
function imgCatRenderTitle()
{
	$('[class^="imgRender"]').each(function(){
		
		typeImage = $(this).attr('class').replace('imgRender_','');
		idImage   = $(this).attr('id');
		$(this).html('<img src="'+wwwRoot+'/comuni/img/catalogo/'+typeImage+'/'+idImage+'.png">');
		
	})
}

function renderTitles() {
   $(".renderTitle").each(function(i) {
      var item_title      = $(this).text();
      var item_label      = escape($(this).text());
      
      item_label          = item_label.replace('"','&quot;');
      
      var item_width      = $(this).css('width');
      var item_fontSize   = $(this).css('font-size');
      var item_lineHeight = $(this).css('line-height');
      var item_color      = $(this).css('color');
      var text_transform  = $(this).css('text-transform');
      if(text_transform=='uppercase')
      {
      	item_label = item_label.toUpperCase();
      }
      
      if(!item_color.match('#')){
       var item_color      = rgb2hex($(this).css('color'));
      }
      else
      {
       var item_color      = item_color.replace("#","");
      }
      
      //alert(item_title+"||"+item_width+"||"+item_fontSize+"||"+item_lineHeight)
      
      
      if (item_title != '') {
   	      var img_tag = "<img src=\""+wwwRoot+"/media/titles/custom/"+item_width+"/"+item_fontSize+"/"+item_lineHeight+"/"+item_color+"/"+item_label+".png\" alt=\""+item_title+"\" border=\"0\"/>";
   	      $(this).text("");
   	      $(this).html(img_tag);
      }
   });
   //if ($.browser.msie) { $(".png").ifixpng(); }
}

function selectEtaFigli() {
	$('#select_figli select.numero_figli').change(function() {
		numeroFigli = $('#select_figli select.numero_figli').val();		
		//alert('numero figli='+numeroFigli);
		
		selectEtaFigli = '';
		
		numeroMaxFigli = $('.select_anno_nascita').size();
		
		//alert(numeroMaxFigli);
		
		for (i=1; i<=numeroMaxFigli; i++) {

			if(i<=numeroFigli)
			{
			  $('#anno_nascita_figlio_'+i).show();
			}
			else
			{
			  $('#anno_nascita_figlio_'+i).hide();
			  $('select[name="anno_nascita_figlio_'+i+'"]').val('')
			}
			//$(this).after('<div id="figlio_'+i+'"><span>Eta Figlio '+i+'</span><select class="eta_figlio"><option>Eta 1</option><option>Eta 2</option><option>Eta 3</option><option>Eta 4</option><option>Eta 5</option></select></div>');					
			//selectEtaFigli += ('<div id="figlio_'+i+'"><span>Eta Figlio '+i+'</span><select class="eta_figlio" name="eta_figlio_'+i+'"><option>Eta 1</option><option>Eta 2</option><option>Eta 3</option><option>Eta 4</option><option>Eta 5</option></select></div>');					
		}	
		
		//$(this).parent().children('#boxEtaFigli').html(selectEtaFigli)
	});
}
function selectPuntoVendita() {
	$('#puntoVenditaSelect select#regione').change(function() {
	
		selectedRegione = $('#puntoVenditaSelect select#regione option:selected').val();
		
		$.ajax({
		  method: "GET",
		  data: 'regione='+selectedRegione,
		  url: wwwRoot+"/ajax/selectPuntoVendita.php",
		  success: function(select_citta){
		  	$('#puntoVenditaSelect select#citta').html(select_citta);
		  }
		});
	});	
		
	$('#puntoVenditaSelect select#citta').change(function() {
		selectedRegione = $('#puntoVenditaSelect select#regione').val();
		selectedCitta = $(this).val();
		
		$.ajax({
		  method: "GET",
		  data: 'regione='+selectedRegione+'&citta='+selectedCitta,
		  url: wwwRoot+"/ajax/selectPuntoVendita.php",
		  success: function(select_indirizzo){
		  	$('#puntoVenditaSelect select#indirizzo').html(select_indirizzo);
		  }
		});		
	});
	
	$('#puntoVenditaSelect #enterPuntoVendita').click(function(){
		pv_url = $('#puntoVenditaSelect select#indirizzo').val();
		
		if (pv_url =='Indirizzo') {

			alert('Selezionare tutti i campi!');		
		}
		
		else {
			location.href = wwwRoot+"/"+wwwLang+"/punti_vendita/"+pv_url+"/";
		}
	
	})
		
}

function selectPuntoVenditaNewsletter() {
	$('#puntoVenditaSelectNewsletter select#regioneNewsletter').change(function() {
	
		selectedRegione = $('#puntoVenditaSelectNewsletter select#regioneNewsletter option:selected').val();
		
		$.ajax({
		  method: "GET",
		  data: 'regione='+selectedRegione,
		  url: wwwRoot+"/ajax/selectPuntoVendita.php",
		  success: function(select_citta){
		  	$('#puntoVenditaSelectNewsletter select#cittaNewsletter').html(select_citta);
		  }
		});
	});	
		
	$('#puntoVenditaSelectNewsletter select#cittaNewsletter').change(function() {
		selectedRegione = $('#puntoVenditaSelectNewsletter select#regioneNewsletter').val();
		selectedCitta = $(this).val();
		
		$.ajax({
		  method: "GET",
		  data: 'regione='+selectedRegione+'&citta='+selectedCitta,
		  url: wwwRoot+"/ajax/selectPuntoVendita.php",
		  success: function(select_indirizzo){
		  	$('#puntoVenditaSelectNewsletter select#indirizzoNewsletter').html(select_indirizzo);
		  }
		});		
	});	
}

function selectPuntoVenditaAll() {
	$('#puntoVenditaSelectAll select#regioneAll').change(function() {
	
		selectedRegione = $('#puntoVenditaSelectAll select#regioneAll option:selected').val();
		
        if(selectedRegione){
		document.location.href = '?regione='+selectedRegione;}

	});	
		
}


		function outMap(where,lat,lon,locations,dpt,mks){
			$("#"+where).googleMaps({
					controls: true,
					depth:dpt,
					latitude: lat, longitude: lon,
					addresses: locations,
					markers: mks
			});
		}

		
		function abilitaFiltri()
		{
			$('div.checkbox').click(function(){
				
				  elenco_filtri = $('form#prodotti').serialize();
				  
				$.ajax({
				  type: "POST",
				  data: elenco_filtri,
				  url: wwwRoot+"/ajax/prodotti.php",
				  success: function(prodotti){
				  	
				  	//alert(prodotti);
				  	//$('.mainContent_prodotti #contentBoxProdotti').html(prodotti);
				  	$('#bodyPage #prodotti #contentBoxProdotti').html(prodotti);
						renderCheckbox();
				  	imgCatRenderTitle();
				  	abilitaFiltri();
				  }
				});
				
			})
		}
		
		$(function() {
		function log( message ) {
			$( "<div/>" ).text( message ).prependTo( "#log" );
			$( "#log" ).attr( "scrollTop", 0 );
		}

		$( "#cerca_prodotto" ).autocomplete({
			source: wwwRoot+"/ajax/cerca_prodotto.php",
			minLength: 2,
			select: function( event, ui ) {
			  callback: goToProduct(ui.item.id),
				log( ui.item ?
					"Selected: " + ui.item.value + " aka " + ui.item.id :
					"Nothing selected, input was " + this.value );
			}
		});
	});
		
	
	
	function goToProduct(subProdId)
	{
		$.ajax({
		  type: "POST",
		  data: "subprod_id="+subProdId,
		  url: wwwRoot+"/ajax/url_prodotto.php",
		  success: function(urlProdotto){
		  	//alert(urlProdotto)
		  	window.location.href = wwwRoot+'/'+wwwLang+'/catalogo'+urlProdotto;
		  }
		});
	}

	
	function ricercaProdotto()
	{
		$('#ricercaProdotto select[name="brand"]').change(function(){
			
			$.ajax({
			  type: "POST",
			  data: "brand="+$(this).val(),
			  url: wwwRoot+"/ajax/ricercaProdotto.php",
			  success: function(form){
			  	//alert(form)
			  	$('#ricercaProdotto div#select').html(form);
			  	ricercaProdotto();
			  }
			});
			
		})
		
		$('#ricercaProdotto select[name="categoria"]').change(function(){
			brand = $('#ricercaProdotto select[name="brand"]').val();
			$.ajax({
			  type: "POST",
			  data: "brand="+brand+"&categoria="+$(this).val(),
			  url: wwwRoot+"/ajax/ricercaProdotto.php",
			  success: function(form){
			  	$('#ricercaProdotto div#select').html(form);
			  	ricercaProdotto();
			  }
			});
			
		})
		
		$('#ricercaProdotto select[name="prodotto"]').change(function(){
					goToProduct($(this).val());
		})
	}
