var video;
var mapImmagineErrore;

(function ($) {

  Drupal.behaviors.pbr_theme = {
    attach: function (context, settings) {
    	//init sostituzione elementi form
    	//$('header').removeClass('clearfix');
    	var lang = $('html').attr('lang');
		
    	$(window).one('load',function() {
    		if($('.selector').length == 0) {
    			//pulizia option per trattini e spazi iniziali e finali
    			$('option').each(function() {
					valore = $(this).text();
					valore = valore.replace(/^[\s\-]+|[\-\s]+$/g,'');
					$(this).text(valore);
				})
    			
				
				//eliminazione spazio fra cifra e valuta euro
				$('#views-form-commerce-cart-block-default span, #views-form-commerce-cart-block-default td, .page-cart td, .page-cart span, .page-checkout td, .page-checkout span').each(function() {
					valore = $(this).html();
					valore = valore.replace(/\s\u20ac/g,'\u20ac');
					$(this).html(valore);
				})
				
				
    			if ($('.page-media-browser').length == 0) {
    				$("input:radio, input:file, select").uniform();
    			}
    						
				//sostituzione checkbox tranne per aree selezioni multiple
				$('input:checkbox').each(function() {
					if($(this).parents('.views-field-views-bulk-operations').length == 0
					&& $(this).parents('.bef-select-all-none').length == 0 && $('.page-media-browser').length == 0) {
						$(this).uniform();
					}
				});
				
				if($(this).parents('.views-field-views-bulk-operations').length == 0
					&& $(this).parents('.bef-select-all-none').length == 0 && $('.page-media-browser').length == 0) {
					$("input:checkbox").live("click", function() {
					    $.uniform.update(
					        $(this).attr("checked", this.checked)
					    );
					});
				}

			}	
		});
		

		
		//#############
		//azioni per homepage
		//############# 
		
		if($('.front').length != 0) {
		
			//aggiunta campo form per barche
			$('#views-exposed-form-annunci-ricerca').append('<input name="t" type="hidden" value="All" id="camporicercabarche"/>');
			
			//eliminazione label tipo
			$('#block-views-exp-annunci-ricerca .views-exposed-widgets > .views-exposed-widget > label').remove();
			
			//preparazione link barca per style
			$('.front #wrapper #views-exposed-form-annunci-ricerca .bef-select-as-links .form-item .form-item').each(function() {
				_this = this;
				if($(this).find('a').length == 0) {
					var testo = $(_this).text();
					//testo = testo.replace(/^[\-\s]+/g,'');
					$(this).html('<a href="#">'+testo+'</a>');
				}
			})
			
			/*etichetteTipologia = new Array();
			etichetteTipologia['Barche a motore'] = 'Motorboats';
			etichetteTipologia['Barche a vela'] = 'Sailing Boats';
			etichetteTipologia['Gommoni e scafi'] = 'Inflatables &amp; boats';
			etichetteTipologia['Altri natanti'] = 'Other boats';
			etichetteTipologia['Accessori'] = 'Accessories';
			etichetteTipologia['Servizi'] = 'Services';*/
			
			//Drupal.t('Motorboats');
			//Drupal.t('Sailing boats');
			//Drupal.t('Inflatables & boats');
			//Drupal.t('Other boats');
			//Drupal.t('Accessories');
			//Drupal.t('Services');
						
			$('.front #wrapper #views-exposed-form-annunci-ricerca .bef-select-as-links .form-item a').each(function() {
				_this = this;
				var testo = $(_this).text();
				testo = testo.replace(/^[\-\s]+/g,'');
				
				$(_this).html('<div class="labeltipobarca">'+ Drupal.t(testo) +'</div>')
			})			
			
			
			
			$('.front #wrapper #views-exposed-form-annunci-ricerca .bef-select-as-links .form-item a').each(function() {
				_this = this;
				valore = $(_this).attr('href');
				valore = valore.replace('node','annunci');
				$(_this).attr('href',valore	);	
			});
			
			
			
		
			//spostamento titolo search home
			$('#block-views-exp-annunci-ricerca h2').prependTo('.wrappersearchhome');
			
			//preparazione campi search
			//eliminazione campi minimo e label and
			$('#edit-l-min, #edit-p-min,[for=edit-l-max],[for=edit-p-max]').remove();
			
			
			
			
			
		}//fine azioni per home 
		
		//#############
		//azioni per colonna destra ricerca
		//#############
		
		if($('.not-front').length!= 0 && $('#views-exposed-form-annunci-ricerca').length != 0) {
			
			//aggiunta elemento per slider ricerca lunghezza 
			$('.views-widget-filter-field_ad_lunghezza_value').append('<div class="sliderricercalunghezzasfondo"><div class="sliderricercalunghezza"></div><div class="labellunghezza"></div><div>');
			
			//eliminazione i campi per la lunghezza
			$('.views-widget-filter-field_ad_lunghezza_value .views-widget').hide();
			
			//eliminazione label per tipo di barca
			$('[for=edit-k]:eq(1)').hide();
			
			//inversione marca condizioni
			$('.not-front .views-widget-filter-field_ad_marca_tid').insertAfter($('.not-front .views-widget-filter-field_ad_conditions_tid'));
			
			//init slider lunghezza
			$( ".sliderricercalunghezza" ).slider({
				range: true,
				min: 0,
				max: 100,
				step: 5,
				slide: function( event, ui ) {
					$( "#edit-l-min" ).val(ui.values[0]);
					
					if(ui.values[1] == 100) {
						$( "#edit-l-max" ).val('10000');
						$('.labellunghezza').html('da '+ui.values[0]+'m a >100m');
					} else {
						$( "#edit-l-max" ).val(ui.values[1]);
						$('.labellunghezza').html('da '+ui.values[0]+'m a '+ui.values[1]+'m');
					}
				}
			}); 
			
			var lunghezzaMinima = parseFloat($( "#edit-l-min").val());
			if(String(lunghezzaMinima) == 'NaN') {
				lunghezzaMinima = 0;
			}
			
			var lunghezzaMassima = parseFloat($( "#edit-l-max").val());
			if(String(lunghezzaMassima) == 'NaN') {
				lunghezzaMassima = 100;
			}
			
			//impostazione default slider lunghezza
			$(".sliderricercalunghezza" ).slider( "option", "values", [lunghezzaMinima,lunghezzaMassima]);
			//impostazione default label lunghezza
			if(lunghezzaMassima >= 100) {
				lunghezzaMassima = ">100";
			}
			$('.labellunghezza').html('da '+lunghezzaMinima+'m a '+lunghezzaMassima+'m');
			
			//aggiunta elemento per slider ricerca prezzo 
			$('.views-widget-filter-field_ad_prezzo_value').append('<div class="sliderricercaprezzosfondo"><div class="sliderricercaprezzo"></div><div class="labelprezzo"></div><div>');
			
			//eliminazione i campi per il prezzo
			$('.views-widget-filter-field_ad_prezzo_value .views-widget').hide();
			
			//eliminazione i campo date value
			$('[for=edit-y-value]').hide();
			
			//eliminazione se top categoria  vuoto
			if($('.not-front .view-display-id-att_top_cat div').length == 0) {
				$('.not-front .view-display-id-att_top_cat').hide();
				$('.not-front .view-display-id-att_top_cat').parent().css('margin','10px 0 0 0');
			}
			
			

			//init slider prezzo
			$( ".sliderricercaprezzo" ).slider({
				range: true,
				min: 0,
				max: 1000000,
				step: 10000,
				slide: function( event, ui ) {
					$( "#edit-p-min" ).val(ui.values[0]);
					
					if(ui.values[1] == 1000000) {
						$( "#edit-p-max" ).val('1000000000');
						$('.labelprezzo').html('da '+ui.values[0]+'&euro; a >1000000&euro;');
					} else {
						$( "#edit-p-max" ).val(ui.values[1]);
						$('.labelprezzo').html('da '+ui.values[0]+'&euro; a '+ui.values[1]+'&euro;');
					}
					
				}
			});
			
			var prezzoMinimo = parseFloat($( "#edit-p-min").val());
			if(String(prezzoMinimo) == 'NaN') {
				prezzoMinimo = 0;
			}
			
			var prezzoMassimo = parseFloat($( "#edit-p-max").val());
			if(String(prezzoMassimo) == 'NaN') {
				prezzoMassimo = 1000000;
			}
			
			//impostazione default slider prezzo
			$(".sliderricercaprezzo" ).slider( "option", "values", [prezzoMinimo,prezzoMassimo]);
			//impostazione default label prezzo
			if(prezzoMassimo >= 1000000) {
				prezzoMassimo = ">1000000";
			}
			$('.labelprezzo').html('da '+prezzoMinimo+'&euro; a '+prezzoMassimo+'&euro;');
			
			
			//spostare tasto ricerca qualsiasi
			$('.not-front #edit-t-all').appendTo($('.not-front #edit-t-509').parent());
			valore = $('.not-front #edit-t-all a').text();	
			valore = valore.replace(/^[\s\-]+|[\-\s]+$/g,''); 
			$('.not-front #edit-t-all a').text(valore);
			
			//sostituzione label "qualsiasi"
			$('#edit-t-all a').text(Drupal.t('Show all'));
			
			//fix paginazione tastoni tipologia
			$('.views-widget-filter-field_ad_tipo_tid .form-item > a').each(function() {
				href = $(this).attr('href');
				href = href.replace(/page=[0-9]+/g,'page=0');
				$(this).attr('href',href);
			})
								
			
		}//fine azioni per colonna destra ricerca
		
		//#############
		//azioni per all

		//wrapper per pager
		$('.item-list ul.pager').wrap('<div class="wrapperpager"></div>');
		
		//style per blocco autore ne il mio annuncio	
		$('.view-display-id-block_ad_author .view-content').addClass('silver-grad rounded shadow-box');
		
		//style per tabella i miei annunci
		$('.page-user .view-id-my_classifieds table th a').wrap('<div class="wrapperintestaziontabellaannunci"></div>');
		$('.page-user .view-id-my_classifieds table th:eq(0) a').append('Annuncio');
		$('.wrapperintestaziontabellaannunci').addClass('silver-grad');
		
		//spostamento paese pagina registrazione
		$('.page-user-register #user_user_form_group_personal_info  .form-item-field-profile-address-und-0-country').appendTo($('.page-user-register #user_user_form_group_personal_info #edit-field-profile-address .fieldset-wrapper'));
		
 		//sostituzione decimali in corpo annuncio
 		valore = $('.node-type-classified-ad  #block-system-main .field-name-field-ad-prezzo .field-items .field-item').text();
 		valore = valore.replace(/,[0-9]+/g,'');
 		$('.node-type-classified-ad  #block-system-main .field-name-field-ad-prezzo .field-items .field-item').text(valore);
 		
 		//spostamento label profilo personale
 		/*$('.page-user #block-system-main .profile .field-type-addressfield .field-label').addClass('labelprofilopersonale');*/
 		$('.labelprofilopersonale').insertBefore($('.page-user #block-system-main .profile'));
 		
 		//upsell utente - label su checkbox per seleziona tutto
 		$('<span>Seleziona tutto</span>').appendTo('.view-id-ad_selector table tr th .form-type-checkbox');
 		
 		
 		//formattazione tasto annulla popup multimedia
        $('.page-media .fake-cancel').addClass('rounded silver-grad tastoannulamedia');
        $('.page-media .ui-tabs-nav').addClass('silver-grad');
        
        //azioni relative a trattativa privata e valorizzazione per tipologia
        //Annunci top trattativa privata
        
        $('.view-id-top_sell .views-field-field-ad-private-price').each(function() {
        	$(this).hide();
        	$(this).parents('.views-row').find('.views-field-field-ad-prezzo').html('Trattativa privata');
        })
        
        //trattativa privata vetrina home
        $('.view-id-homepage .views-field-field-ad-private-price').each(function() {
        	$(this).hide();
        	$(this).parents('.views-row').find('.views-field-field-ad-prezzo').html('Trattativa privata');
        })
        
        
        //lunghezza annunci top
        $('.view-id-top_sell .views-field-field-ad-lunghezza').each(function() {
        	if($(this).find('.field-content').text() == '0,00 m') {
        		$(this).hide();
        	}
        })
        
        //lunghezza annunci categoria
        $('.view-id-annunci .field-name-field-ad-lunghezza').each(function() {
        	if($(this).find('.field-item').text() == '0,0 m') {
        		$(this).hide();
        	}
        })
        
        //trattativa privata annunci bottom
        $('.view-id-bottom_sell .views-field-field-ad-private-price').each(function() {
        	$(this).hide();
        	$(this).parents('.views-row').find('.views-field-field-ad-prezzo').html('Tratt. privata');
        })
        
         //trattativa privata top categoria
        $('.view-display-id-att_top_cat .views-field-field-ad-private-price').each(function() {
        	$(this).hide();
        	$(this).parents('.views-row').find('.views-field-field-ad-prezzo').html('Trattativa privata');
        })
        
        //trattativa privata annuncio
        $('.view-id-annuncio .views-field-field-ad-private-price').each(function() {
        	$(this).hide();
        	$(this).parent('.silver-grad').find('.views-field-field-ad-prezzo').html('Tratt. privata');
        }) 
         
        
        //azioni per annuncio accessori
        if($('.node-type-classified-ad .ad-type-accessori').length != 0 || $('.node-type-classified-ad .ad-type-accessories').length != 0) {
        	$('#googlemap').hide();
        	$('.field-name-field-ad-lunghezza').parent().hide();
        	$('#ad-inside-boat').hide();
        	$('#ad-engines').hide();
        }
        
        //azioni per annuncio servizi
        if($('.node-type-classified-ad .ad-type-servizi').length != 0 || $('.node-type-classified-ad .ad-type-services').length != 0) {
        	$('#googlemap').hide(); 
        	$('.field-name-field-ad-lunghezza').parent().hide();
        	$('.field-name-field-ad-stato').hide();
        	$('#ad-inside-boat').hide();
        	$('#ad-engines').hide();
        }
        
        //shadow su testata box
        $('.blog-context-section #page-title').addClass('shadow-box');
        
        //wrapper per immagini annuncio
        $(window).one('load',function() {
        	$('.gallery-slides').wrap('<div class="gallery-slides-wrap"></div>');
        })
        
        //video youtube su annuncio
        $('.file-video-youtube a').addClass('link-video-youtube colorbox-load');
		video = $('.link-video-youtube').text();
		if($('.link-video-youtube').length!=0) {
	        $('.link-video-youtube').colorbox({
	        	iframe: false,
	        	html: '<iframe width="480" height="360" src="http://www.youtube.com/embed/'+video+'" frameborder="0" allowfullscreen></iframe>'
	        });
        }
        
        //azione check immagine sostitutiva
        $('.views-row img').each(function() {
        	path = $(this).attr('src');
        	if(path.match(/PBR_jolly/)) {
        		$(this).parents('.views-row').find('.img-count').remove();
        	}
        })
 		
 		/*google maps init*/
		indirizzo = $('#googlePorto').text();
		if ($('#googlePorto').length != 0) {
			loadScript();
		}
		
		if($('body.page-node-2458').length!=0) {
			if($('body.not-logged-in').length!=0) {
				$('#block-system-user-menu').remove();
			}
		}
		
		//rimozione "o" da checkout-buttons form-wrapper
		if ($('.checkout-buttons .fieldset-wrapper').length != 0) {
			var testo = $('.checkout-buttons .fieldset-wrapper').html();
			var testo = testo.replace(/>o</g,'><');
			$('.checkout-buttons .fieldset-wrapper').html(testo);
		}
		
		//eliminazione stili inutili su radio e checkbox
		$(':checkbox, :radio').css({
			background: '#ffffff',
			border: 'none',
			borderRadius: 0
		});
		
		//rimozione update cart
		$('.commerce-line-item-actions input:first').remove();
		
		//fix contatta inserzionista
		$('#webform-component-contatta-inserzionista .fieldset-wrapper').append($('.node-type-classified-ad  #edit-actions'));
		
	
 		
    	//attivazione grid 
    	/*  	
         if(!($('#grid-toggle').length)) {
          $('<div id="grid-toggle"><a href="#">Toggle grid</a></div>').appendTo('body').css('text-align', 'center');
        }
                
        
       
        $('#grid-toggle a').click(function(){
          $('#wrapper').toggleClass('showgrid');
        });
        */
        
        /*mapImmagineErrore = function mapImmagineErrore() {
        	$('#googlemap').html('<img src="/sites/all/themes/pbr/images/PBR_isola.jpg" alt="Indirizzo non trovato" />');
        }*/
            
        
    } //end attach
  }; // end behaviour

}(jQuery)); //end jQuery

//funzioni per inizializzazione e settaggio google maps
var initialize = function initialize() {
	geocoder = new google.maps.Geocoder();
	geocoder.geocode( {'address': indirizzo}, function(results,status) {
	if (status == google.maps.GeocoderStatus.OK) {
	    var options = {
	    	mapTypeControl: true,
	    	panControl: false,
	    	rotateControl: false,
	    	zoomControl: true,	
	        zoom: 9,
	        center: results[0].geometry.location,
	        mapTypeId: google.maps.MapTypeId.ROADMAP
	    };
	var map = new google.maps.Map(document.getElementById('googlemap'), options);
	var marker = new google.maps.Marker({position: results[0].geometry.location, map: map});
	} else {
	    //alert("Problema nella ricerca dell'indirizzo: " + status);
	    document.getElementById('googlemap').innerHTML = '<img src="/sites/all/themes/pbr/images/PBR_isola.jpg" alt="Indirizzo non trovato" />';
	}
	});
} 		
	
function loadScript() {
	var script = document.createElement("script");
	script.type = "text/javascript";
	script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize&language=en";
	document.body.appendChild(script);
}  






	    
	    
;

