// NAMESPACE Infoelba
var Infoelba = new function() {
	
	/**
		Lancia l'esecuzione di alcune funzioni al momento del caricamento della pagina.
	*/
	this.onLoad = function() {
		$('a[rel="external"]').attr('target', '_blank');
		$('a[rel="gallery"]').colorbox({maxWidth: '90%', maxHeight: '90%'});
		
		//Infoelba.Load.setNavCurrentLink();
		Infoelba.Load.enablePopupLinks();
		Infoelba.Load.alternateTableRows();
		Infoelba.Load.enableSitofonoInfo();
		Infoelba.Load.enableSubpageTogglers();
		Infoelba.Load.loadAds();
		Infoelba.Forms.disableButtonAfterSubmit();
		Infoelba.Load.enableToolbar();
		Infoelba.Load.loadSocialShareButtons();
	};
	
	this.scrollTo = function(elementId) {
		window.scrollTo = function(x,y) {
			return true;
		}
		if($('#' + elementId).length > 0) {
			$.scrollTo('#' + elementId);
		}
	};
};	// ns Infoelba


// NAMESPACE Infoelba.Forms
// Contiene metodi per l'abilitazione di effetti, validazione, invio dati relativi a moduli di richiesta.
Infoelba.Forms = new function() {
	
	/**
		METODO PRIVATO
		Nasconde i controlli all'interno dell'elemento con id containerId se nessuna delle checkbox
		è spuntata. Visualizza gli stessi controlli se almeno una checkbox è spuntata.
		@param		checkboxes		le checkbox con cui nascondere/visualizzare gli altri elementi
		@param		containerId		id del contenitore da nascondere/visualizzare
	*/
	var _toggleControlsWithCheckboxes = function(checkboxes, containerId) {
		checkboxes.change(function() {
			var showControls = false;
			checkboxes.each(function() {
				if($(this).is(':checked')) {
					showControls = true;
					return false;
				}
			});
			if(showControls) {
				$('#' + containerId).show('fast');
			} else {
				$('#' + containerId).hide('fast');
			}
		});
	};
	
	/**
		Abilita i datepicker per la selezione delle date nei moduli di richiesta.
	*/
	this.enableDatepickers = function() {
		var dates = $('.date').attr('autocomplete', 'off').datepicker({
			changeMonth: true,
			changeYear: true,
			onSelect: function(selectedDate) {
				if (this.id == "periodo-dal") {
					var instance = $(this).data('datepicker');
					var date = $.datepicker.parseDate(instance.settings.dateFormat || $.datepicker._defaults.dateFormat, selectedDate, instance.settings);
					dates.not(this).datepicker("option", 'minDate', date);
				}
			}
		});
	};
	
	this.prepareMiniSearch = function(validationMessage) {
		$('#search-category').val('').hide();
		$('#zona').val('');
		$('#tipo').val('').change(function() {
			var typeId = $(this).val();
			$('#search-category').css('display', (typeId == 'ht' || typeId == 're' || typeId == 'cp' || typeId == 'ag') ? 'block' : 'none');
		});
		
		$('#search-submit').click(function() {
			if($('#nome').val() == '' && $('#zona').val() == '' && $('#tipo').val() == '' && $('#categoria').val() == '') {
				alert(validationMessage);
				return false;
			}
		});
	};
	
	/**
		Abilita il controllo (select) per caricare i servizi in base al tipo di struttura scelta, e il pulsante
		per visualizzare/nascondere i servizi estesi.
		@see		Ajax.switchStructureTypeServices(), ajax.js
	*/
	this.prepareFullSearch = function() {
		$('#tipo').change(function() {
			var typeId = $(this).val();
			$('#search-category').css('display', (typeId == 'ht' || typeId == 're' || typeId == 'cp' || typeId == 'ag') ? 'block' : 'none').val('');
			
			if(typeId == 'bb') typeId = 'ht';
	
			Infoelba.Ajax.switchStructureTypeServices(this.value);
		});
		
		$('#show-more').click(function() {
			$('#more-services').slideToggle('slow');
			return false;
		});
	};
	
	this.disableButtonAfterSubmit = function() {
		$('button[type=submit]').removeAttr('disabled');
		$('form').submit(function(){
				$('button[type=submit]', this).attr('disabled', 'disabled');
		});
	}
	
	/**
		Genera i controlli per specificare le età dei bambini nei moduli di richiesta, in base al valore del controllo (select)
		contenente il numero di bambini.
	*/
	this.prepareChildrenAgeInputs = function(labelText, noteLabelText) {
		var ageContainer = $('#childrenages');
		var field, label, sel, opt;
		sel = $('<select></select>');
		for(var i=0;i<=12;i++) {
			opt = $('<option value="' + i + '">' + i + '</option>');
			opt.appendTo(sel);
		}
		$('#bambini').change(function() {
			ageContainer.empty();
			var children = this.selectedIndex;
			if(children > 0) {
				for(var i=1;i<=children;i++) {
					field = $('<div class="field"></div>');
					label = $('<label for="eta-bambino-' + i + '">' + labelText + i + '</label>');
					label.appendTo(field);
					sel.clone().attr('id', 'eta-bambino-' + i).attr('name', 'eta-bambino-' + i).appendTo(field);
					$('<span class="note">' + noteLabelText + '</span>').appendTo(field);
					field.appendTo(ageContainer);
				}
			}
		});
	};

	
	/**
		Abilita i controlli (checkbox) per visualizzarne o nasconderne altri nei moduli di richiesta.
	*/
	this.enableStructureTypesTogglers = function() {
		if(!$('#hotel').is(':checked')) $('#hotel-data').css('display', 'none');
		if(!$('#residence').is(':checked')) $('#residence-data').css('display', 'none');
		if(!$('#camping').is(':checked')) $('#camping-data').css('display', 'none');
		
		_toggleControlsWithCheckboxes($('#hotel'), 'hotel-data');
		_toggleControlsWithCheckboxes($('#residence'), 'residence-data');
		_toggleControlsWithCheckboxes($('#camping'), 'camping-data');
	};
	
	
		
	this.onMiniRequestSubmit = function(tabsInstance) {
		var date = $('#mini-periodo-dal').datepicker('getDate');

		if(date) {
			$('#periodo-dal').datepicker('setDate', date);
			
			var duration = parseInt($('#mini-periodo-durata').val());
			date.setDate(date.getDate() + duration);
			
			$('#periodo-al').datepicker('setDate', date);
		}
		$('#adulti').val($('#mini-adulti').val());
		$('#bambini').val($('#mini-bambini').val()).trigger('change');
		
		tabsInstance.tabs('select', 't-request');
		Infoelba.scrollTo('t-request');
	};
	
};	// ns Infoelba.Forms



// NAMESPACE Infoelba.Load
// Contiene metodi da eseguire al caricamento della pagina, come gestori di eventi e così via.
Infoelba.Load = new function() {
	
	this.enableHeaderSlide = function(imgCount) {
		$('#header-images').nivoSlider({
        effect: 'sliceUpDownLeft',
				pauseTime: 4000,
        slices: imgCount,
        controlNav: false,
        directionNav: false
    });
	};
	
	/**
		Abilita l'apertura di una finestra di popup per tutti quei link che hanno specificato l'attributo rel con questo formato:
		rel="popup[larghezza,altezza]",
		dove larghezza ed altezza sono le dimensioni del popup risultante.
	*/
	this.enablePopupLinks = function() {
		$('a[rel^="popup"]').each(function() {
	 		var rel, windex, width = 650, height = 650;
			rel = $(this).attr('rel');

			if((windex = rel.indexOf('[')) > -1) {
				width = rel.substring(windex + 1, rel.indexOf(','));
				height = rel.substring(rel.indexOf(',') + 1, rel.indexOf(']'));
			}
			
			$(this).colorbox({
				iframe:true,
				innerWidth:width,
				innerHeight:height,
				onComplete: function() {
					$("#cboxCurrent").hide();
					$("#cboxPrevious").hide();
					$("#cboxNext").hide();
				}});
		});
	};
	
	this.enableStructuresInfiniteScroll = function(hash, pageSize) {
		$(window).scroll(function() {
			if($(window).scrollTop() == ($(document).height() - $(window).height())) {
				var listElement = $('#result-' + hash);
				Infoelba.Ajax.getPagedStructures(hash, Math.ceil($('#result-' + hash + ' > li').size() / pageSize), pageSize, listElement);
			}
		});
	};
	
	this.setNavCurrentLink = function() {
		var location = document.location.pathname;
		if(location.lastIndexOf('/') > 1) {
			var parentLocation = '/' + location.substring(1, location.substring(1).indexOf('/') + 1) + '/';
			$('#nav li a[href='+ parentLocation +']').addClass('current');
		}
		$('#nav li a[href='+ location +']').addClass('current');
	};
	
	/**
		Abilita i pulsanti per aprire e chiudere le liste di sottopagine da un certo livello level in poi.
	*/
	this.enableSubpageTogglers = function(level) {
		if(!level) level = 3;
		
		var toggler = $('<a class="toggler" alt=">" href="#"></a>')
			.insertBefore($('.subpages ul.level-'+level))
			.click(function() {
				$(this).toggleClass('acc-open').next().toggle('fast');
				return false;
			});
		$('.subpages .toggler + ul').css('display', 'none');
	};
	
	/**
		Abilita il pulsante "maggiori informazioni" per il box riassuntivo del sistema Sitòfono.
	*/
	this.enableSitofonoInfo = function() {
		$('.sitofono a.info').click(function(e) {
			e.preventDefault();
			$('#sitofono-info').toggle();
		});
	};

	/**
		Aggiunge la classe "odd" a tutte le righe dispari delle tabelle con classe "list"
	*/
	this.alternateTableRows = function() {
		$("table.list tr:odd").addClass("odd");
	};
	
	/**
		Abilita il controllo (select) per cambiare il mese di partenza nel calendario disponibilità di una struttura.
		@see			Ajax.switchAvailabilityDate()
	*/
	this.enableAvailabilityDateSwitcher = function() {
		$("#starting-month option:eq(0)").attr("selected", "selected");
		$('#starting-month').change(function() {
			var date = this.value;
			var month = date.substring(0, date.lastIndexOf('/'));
			var year = date.substring(date.lastIndexOf('/')+1, date.length);
			var id = $('#sid').val();
			
			Infoelba.Ajax.switchAvailabilityDate(id, month, year);
		});
	};
	
	this.loadAds = function() {
    if ($('#infoelbads').length > 0) {
			var box = $('#infoelbads');
    	var height = box.height();
      var width = box.width();
			
			if(box.hasClass('infoelbads-horizontal')) {
	      box.append('<iframe src="http://ads.infoelba.it/?width=' + (width - 30) + '&amp;bordercolor=%23ffffff&amp;titlecolor=%233B5998" frameborder="0" scrolling="no" height="' + (height + 30) + '" width="100%"></iframe>');
			} else {
	      box.append('<iframe src="http://ads.infoelba.it/?height=' + height + '&amp;bordercolor=%23ffffff&amp;titlecolor=%233B5998" frameborder="0" scrolling="no" height="' + (height + 30) + '" width="100%"></iframe>');				
			}
    }
	};
	
	/**
		Rende un qualunque elemento galleggiante in verticale.
		@param		boxId		id dell'elemento
	*/
	this.makeFloat = function(boxId) {
		var box = $('#' + boxId);
		var offset = box.offset();
		var topPadding = 15;
		$(window).scroll(function() {
			if ($(window).scrollTop() > offset.top) {
				box.stop().animate({
					marginTop: $(window).scrollTop() - offset.top + topPadding
				});
			} else {
				box.stop().animate({
					marginTop: 0
				});
			};
		});
	};
	
	this.enableToolbar = function() {
		if(!$.cookie('toolbar') || $.cookie('toolbar') == '1') {
			$('#toolbar').show();
			$('#toolbar-show').hide();
		} else {
			$('#toolbar').hide();
			$('#toolbar-show').show();
		}
		
		$("#toolbar-hide a").click(function() {
			$("#toolbar").slideToggle("fast");
			$("#toolbar-show").fadeIn("slow");
			$.cookie('toolbar', '0', { path: '/' });
			return false;
		});
	
		$("#toolbar-show a").click(function() {
			$("#toolbar-show").fadeOut("fast");
			$("#toolbar").slideToggle("fast");
			$.cookie('toolbar', '1', { path: '/' });
			return false;
		});
		
		$('#toolbar-menu-container > a').click(function() {
			return false;
		});
	};
	
	this.loadSocialShareButtons = function() {
		setTimeout(function() {
			$.ajax({
			url: '/requests/ajax/social-share.asp?url=' + location.href + '&title=' + document.title,
			success: function(data) {
				$('#toolbar-left').append(data);
			}})}
		,	1500);
		
		setTimeout(function() {
			stButtons.locateElements();
			$('#loader').hide();
			$('#social-links, #social-share').show();
		}, 4000);
	};
	
};	// ns Infoelba.Load


// NAMESPACE Infoelba.Ajax
Infoelba.Ajax = new function() {
	
	/**
		Effettua una chiamata in base alla quale si stabilisce se il browser dell'utente supporta Javascript.
	*/
	this.enableJs = function() {
		$.ajax({
			type: "POST",
			url: "/requests/ajax/enablejs.asp",
			data: "enabled=1"
		});
	};
	
	this.getPagedStructures = function(hash, pos, pageSize, listElement, nextButton) {
		$('#loader').show();
		$.ajax({
			type: "POST",
			url: "/requests/ajax/paged-structures.asp",
			data: "hash=" + hash + "&pageSize=" + pageSize + "&pos=" + pos + "&next=" + (nextButton ? "1" : "0"),
			success: function(data){ 
				if(data) {
					$(data).hide().appendTo(listElement).slideDown('slow');
				}
				$('#loader').hide();
				//window.location.hash = hash + "," + pos + "," + pageSize + "," + nextButton;
			},
			error: function() {
				$('#loader').hide();
			}
		});
	};
	
	
	/**
		Ottiene il numero di telefono dell'operatore che ha pubblicato l'annuncio immobiliare.
		@param		id		id dell'annuncio
		@param		oid		id dell'operatore
		@param		tel		nome della colonna a db del numero di telefono che si vuole
	*/
	this.getAdvertisingContact = function(id, oid, tel) {
		$.ajax({
			type:"POST",
			url: "/requests/ajax/advertisings.asp",
			data: "id=" + id + "&oid=" + oid + "&tel=" + tel,
			success: function(msg){ $('#' + tel).html(msg); }
		});
		return false;
	};
	
	/**
		Incrementa un contatore di una struttura
		@param		sid		id della struttura
		@param		cid		id del tipo di contatore
	*/
	this.updateStats = function(sid, cid) {
		$.ajax({
			type:"POST",
			url: "/requests/ajax/stats.asp",
			data: "sid=" + sid + "&cid=" + cid
		});
		return false;
	};
	
	/**
		Cambia la lista dei servizi in base al tipo di struttura nella ricerca avanzata.
		@param		id		id del tipo di struttura
		@see			Forms.prepareFullSearch(), functions.js
	*/
	this.switchStructureTypeServices = function(id) {
		$.ajax({
			type:"POST",
			url: "/requests/ajax/structuretype-services.asp",
			data: "id=" + id + "&type=base",
			success: function(msg){ $('#services').html(msg); }
		});
		
		$.ajax({
			type:"POST",
			url: "/requests/ajax/structuretype-services.asp",
			data: "id=" + id + "&type=more",
			success: function(msg){ $('#more-services').html(msg); }
		});
		return false;
	};
	
	/**
		Cambia il mese di inizio del calendario disponibilità di una struttura.
		@param		id		id della struttura
		@param		month	mese di partenza
		@param		year	anno di partenza
		@see			Infoelba.Load.enableAvailabilitySwitcher()
	*/
	this.switchAvailabilityDate = function(id, month, year) {
		$.ajax({
			type:"POST",
			url: "/requests/ajax/availability.asp",
			data: "id=" + id + "&month=" + month + "&year=" + year,
			success: function(msg){
				$('#availability').html(msg);
			}
		});
		return false;
	};
	
	/**
		Registra un'azione (mi piace, non mi piace, non mi interessa) per una curiosità.
		@param		id		id della curiosità
		@param		op		operazione ('like', 'dislike', 'uninteresting')
	*/
	this.curiosityAction = function(id, op) {
		$.ajax({
			type:"POST",
			url: "/requests/ajax/curiosities.asp",
			data: "action=" + op + "&id=" + id,
			success: function(msg){ $("#like-buttons").html(msg); }
		});
		return false;
	};

	
	/**
		Richiede la spedizione via email della vcard di una struttura.
		@param		id		id della struttura
	*/
	this.getStructureVCard = function(id) {
		$.ajax({
			type:"POST",
			url: "/requests/vcard.asp",
			data: "id=" + id + "&vcard-email=" + $('#vcard-email').val(),
			success: function(msg){
				$('#vcard-request').html(msg);
			}
		});
		return false;
	};
	
	this.trackGooglePlusOne = function(obj) {
		_gaq.push(['_trackEvent', 'plusone', obj.state, location.href]);
	};
	
};	// ns Infoelba.Ajax

// NAMESPACE Infoelba.Maps
Infoelba.Maps = new function() {

	/**
		Aggiunge un controllo cliccabile (pulsante) ad una mappa di Google.
		@param		label			testo del pulsante
		@param		tooltip		tooltip del pulsante
		@param		map				oggetto di tipo google.maps.Map
		@param		position	costante da google.maps.ControlPosition
		@param		onClickFunction		funzione da richiamare al click del pulsante
	*/
	this.addMapControl = function(label, tooltip, map, position, onClickFunction) {
		
		var controlDiv = document.createElement('DIV');
		controlDiv.style.padding = '5px 0';
		controlDiv.index = 1;
		
		var controlUI = document.createElement('DIV');
		controlUI.style.backgroundColor = 'white';
		controlUI.style.borderStyle = 'solid';
		controlUI.style.borderWidth = '1px';
		controlUI.style.borderColor = '#A9BBDF';
		controlUI.style.borderRadius = '0 2px 2px 0';
		controlUI.style.boxShadow = '2px 2px 3px rgba(0, 0, 0, 0.35)';
		controlUI.style.padding = '0 8px';
		controlUI.style.cursor = 'pointer';
		controlUI.style.textAlign = 'center';
		if(position == google.maps.ControlPosition.BOTTOM_CENTER) {
			controlUI.style.marginBottom = '15px';
		}
		controlUI.title = tooltip;
		controlDiv.appendChild(controlUI);
	
		var controlText = document.createElement('DIV');
		controlText.style.fontFamily = 'Arial,sans-serif';
		controlText.style.fontSize = '12px';
		controlText.style.paddingLeft = '4px';
		controlText.style.paddingRight = '4px';
		controlText.innerHTML = label;
		controlUI.appendChild(controlText);
		
		google.maps.event.addDomListener(controlUI, 'click', onClickFunction);
	
		map.controls[position].push(controlDiv);
	};
};	// ns Infoelba.Maps


// NAMESPACE Infoelba.MyChoice
Infoelba.MyChoice = new function() {
	
	/**
		Effettua una richiesta asincrona per aggiungere o rimuovere una struttura da 'la mia scelta'.
		@param		id		id della struttura
		@param		op		operazione ('add', 'remove')
	*/
	this.action = function(id, op) {
		$.ajax({
			type:"POST",
			url: "/requests/ajax/mychoice.asp",
			data: "action=" + op + "&id=" + id,
			async: false,
			success: function(res) {
				var cssClass = $('#mychoice-' + id).attr('class').replace('-add', '').replace('-remove', '');
				$("#mychoice-" + id).replaceWith('<span class="' + cssClass + '">' + res.data.msg + '</span>');
				$('#mychoice-count').html(res.data.count).addClass('notify');
				if($('#mychoice-ids').length > 0) {
					$('#mychoice-ids').val(res.data.mychoice);
				}
			}
		});
		return false;
	};
};	// ns Infoelba.MyChoice

