function _0(num){
	return (num<10?"0":"") + num;
};

theFirstDate = new Date();
theSecondDate = new Date();
theSecondDate.setDate(theSecondDate.getDate()+1);

Search = {
	options:{
		from:"bform[checkin]",
		to:"bform[checkout]",
		trigger_from:"f_trigger_a",
		trigger_to:"f_trigger_b",
		override:false
	},
	calendarSetup:function(){
		var cal_from = Calendar.setup({
			inputField     :    Search.options.from,           //*
			ifFormat       :    "%d-%m-%Y",
			showsTime      :    false,
			button         :    Search.options.trigger_from,
			weekNumbers	   :	false,
			step           :    1,
			firstDay       :    1,
			dateStatusFunc :	Search.noOldDays,
			onUpdate	   :	Search.upDate,
			electric       :    false
		});
		var cal_to = Calendar.setup({
			inputField     :    Search.options.to,           //*
			ifFormat       :    "%d-%m-%Y",
			showsTime      :    false,
			button         :    Search.options.trigger_to, 
			weekNumbers	   :	false,
			step           :    1,
			firstDay       :    1,
			dateStatusFunc :	Search.noOldDaysTheSecond,
			onUpdate       :    Search.upDateTheSecond,
			electric       :    false
		});
		var cal_from2 = Calendar.setup({
			inputField     :    Search.options.from,           //*
			ifFormat       :    "%d-%m-%Y",
			showsTime      :    false,
			weekNumbers	   :	false,
			step           :    1,
			firstDay       :    1,
			dateStatusFunc :	Search.noOldDays,
			onUpdate	   :	Search.upDate,
			electric       :    false
		});
		var cal_to2 = Calendar.setup({
			inputField     :    Search.options.to,           //*
			ifFormat       :    "%d-%m-%Y",
			showsTime      :    false,
			weekNumbers	   :	false,
			step           :    1,
			firstDay       :    1,
			dateStatusFunc :	Search.noOldDaysTheSecond,
			onUpdate       :    Search.upDateTheSecond,
			electric       :    false
		});
	},
	init:function(){
		if(arguments.length == 1 && typeof(arguments[0]) == "object"){
			for(var ind in arguments[0]){
				Search.options[ind] = arguments[0][ind];
			}
		}
		if(Search.options.override){
			for(o in Overrides){
				Calendar.prototype[o] = Overrides[o];
			}
		}
		Search.calendarSetup();
	},
	noOldDays:function(date,y,m,d){
		var blockDate = new Date();
		blockDate.setDate(blockDate.getDate()-1);
		if(date<(blockDate)){
			return true;
		}else{
			return false;
		}
	},
	upDate:function(cal){
		theFirstDate = cal.date;
		if(theSecondDate.getTime()<=cal.date.getTime()){
			theSecondDate = cal.date;
			theSecondDate = new Date(theFirstDate.getFullYear(),theFirstDate.getMonth(),theFirstDate.getDate());
			theSecondDate.setDate(theSecondDate.getDate()+1);
			var theString = _0(theSecondDate.getDate())+"-"+_0(theSecondDate.getMonth()+1)+"-"+theSecondDate.getFullYear();
			document.getElementById(Search.options.to).value = theString;
		}
	},
	upDateTheSecond:function(cal){
		theSecondDate = cal.date;
	},
	noOldDaysTheSecond:function(date,y,m,d){
		var fgiorno = theFirstDate.getDate();
		var fmese = theFirstDate.getMonth();
		var fanno = theFirstDate.getFullYear();
	
		var secondBlockDate = new Date(fanno,fmese,fgiorno);
//		secondBlockDate.setDate(secondBlockDate.getDate()-1);
	
		if(date<secondBlockDate){
			
			return true;
		}else{
			return false;
		}
	}
};

var Overrides = {
	showAtElement:function (el, opts) {
	var self = this;
	var p = Calendar.getAbsolutePos(el);
	if (!opts || typeof opts != "string") {
		this.showAt(p.x, p.y + el.offsetHeight);
		return true;
	}
	function fixPosition(box) {
		if (box.x < 0)
			box.x = 0;
		if (box.y < 0)
			box.y = 0;
		var cp = document.createElement("div");
		var s = cp.style;
		s.position = "absolute";
		s.right = s.width = "0px";
		document.body.appendChild(cp);
		var br = Calendar.getAbsolutePos(cp);
		document.body.removeChild(cp);
		if (Calendar.is_ie) {
			br.x += document.body.scrollLeft;
		} else {
			br.x += window.scrollX;
		}
		var tmp = box.x + box.width - br.x;
		if (tmp > 0) box.x -= tmp;
	}
	this.element.style.display = "block";
	Calendar.continuation_for_the_fucking_khtml_browser = function() {
		var w = self.element.offsetWidth;
		var h = self.element.offsetHeight;
		self.element.style.display = "none";
		var valign = opts.substr(0, 1);
		var halign = "l";
		if (opts.length > 1) {
			halign = opts.substr(1, 1);
		}
		// vertical alignment
		switch (valign) {
			case "T": p.y -= h; break;
			case "B": p.y += el.offsetHeight; break;
			case "C": p.y += (el.offsetHeight - h) / 2; break;
			case "t": p.y += el.offsetHeight - h; break;
			case "b": break; // already there
		}
		// horizontal alignment
		switch (halign) {
			case "L": p.x -= w; break;
			case "R": p.x += el.offsetWidth; break;
			case "C": p.x += (el.offsetWidth - w) / 2; break;
			case "l": p.x += el.offsetWidth - w; break;
			case "r": break; // already there
		}
		p.width = w;
		p.height = h + 40;
		self.monthsCombo.style.display = "none";
		fixPosition(p);
		self.showAt(p.x, p.y);
	};
	if (Calendar.is_khtml)
		setTimeout("Calendar.continuation_for_the_fucking_khtml_browser()", 10);
	else
		Calendar.continuation_for_the_fucking_khtml_browser();
	}
};
var append = function(func,callback){
	return function(){
		try{
			func();
		}catch(e){};
		try{
			callback();
		}catch(e){};
	}
};

// FUNZIONI PER LA MAPPA V3
var i, infoBox, maps;
i = 1;
var myZindex = 0;
var changeZoom = false;

function setMarkers(mapId, optiones, zoom, mapType, showCursor, multiple, showBox, openBox) {
	if (multiple == undefined) multiple = false;
	var multipleCategory = "";
	if(multiple != false && multiple !== true){
		multipleCategory = multiple;
		multiple = true;
	}
	if (showBox == undefined) showBox = false;
	if (openBox == undefined) openBox = false;
	if (showBox || openBox != false) infoBox = new BFInfoWindow();
	var myMarker = new Array();
	myMarker['iconsize'] = "30,30";
	myMarker['iconhancor'] = "0,15";
	for (names in optiones) myMarker[names] = optiones[names];
	var latlng = new google.maps.LatLng(myMarker['lat'], myMarker['lon']);
	if(mapType == undefined) mapType = "ROADMAP"; //ROADMAP - SATELLITE - HYBRID - TERRAIN 
	if(showCursor == undefined) showCursor = false;
    var myOptions = {
		disableDefaultUI: showCursor,
		zoom: zoom,
		center: latlng,
		mapTypeId: google.maps.MapTypeId[mapType]
    };
	
    maps = new google.maps.Map(document.getElementById(mapId), myOptions);
	
	var markerBounds = new google.maps.LatLngBounds();
	
	var myLatLng = new google.maps.LatLng(myMarker['lat'], myMarker['lon']);
	
	if (multiple){
		if(multipleCategory != "") multipleCategory = "?sectionId="+ multipleCategory;
		downloadUrl("/assets/interestPoint.php"+ multipleCategory, function(data, responseCode) {

  			var markers_def = data.documentElement.getElementsByTagName("marker");
			for (var i_def=0; i_def<markers_def.length; i_def++) {
				
				markerBounds.extend(new google.maps.LatLng(parseFloat(markers_def[i_def].getAttribute("lat")), parseFloat(markers_def[i_def].getAttribute("lng"))));
				
				if(openBox != false && openBox == markers_def[i_def].getAttribute("id")){
					var marker = new google.maps.Marker({
						position: new google.maps.LatLng(parseFloat(markers_def[i_def].getAttribute("lat")), parseFloat(markers_def[i_def].getAttribute("lng"))),
						map: maps,
						icon: '/images/iconMarkerBig.png',
						zIndex: 1000000000
					});
					openInfoBox(marker, base_64.decode(markers_def[i_def].getAttribute("ballon")), maps);
				} else if(openBox != false && openBox != markers_def[i_def].getAttribute("id")){
					var marker = new google.maps.Marker({
						position: new google.maps.LatLng(parseFloat(markers_def[i_def].getAttribute("lat")), parseFloat(markers_def[i_def].getAttribute("lng"))),
						map: maps,
						title: markers_def[i_def].getAttribute("name"),
						icon: markers_def[i_def].getAttribute("idImg"),
						zIndex: myZindex + 1
					});
					attachURL(marker, markers_def[i_def].getAttribute("url"));
				} else if(openBox == false){
					var marker = new google.maps.Marker({
						position: new google.maps.LatLng(parseFloat(markers_def[i_def].getAttribute("lat")), parseFloat(markers_def[i_def].getAttribute("lng"))),
						map: maps,
						icon: markers_def[i_def].getAttribute("idImg"),
						zIndex: myZindex + 1
					});
					
					google.maps.event.addListener(marker, "mouseover", function() {
						this.setZIndex(myZindex + 1);
						myZindex = myZindex + 1;
					});
	
					if(markers_def[i_def].getAttribute("url") != "") {
						if(showBox) attachInfoBox(marker, base_64.decode(markers_def[i_def].getAttribute("ballon")), maps, markers_def[i_def].getAttribute("url"));
						attachURL(marker, markers_def[i_def].getAttribute("url"));
					} else {
						if(showBox) attachInfoBox(marker, base_64.decode(markers_def[i_def].getAttribute("ballon")), maps);
					}
					myZindex++;
				}
			}
			if(openBox == false){
				if(markers_def.length > 1){
					markerBounds.extend(new google.maps.LatLng(45.633831, 13.061603));
					maps.fitBounds(markerBounds);
				}
				google.maps.event.addListener(maps, 'zoom_changed', function() {
					if(changeZoom == false){
						if(markers_def.length < 2 && maps.getZoom() > 13) maps.setZoom(13);
						changeZoom = true;
					} 
				});
			}
		});
	} else {
		var marker = new google.maps.Marker({
			position: myLatLng,
			map: maps,
			icon: myMarker['icon']
		});
	}
	var markerHotel = new google.maps.Marker({
		position: new google.maps.LatLng(45.633831, 13.061603),
		map: maps,
		title: "Annia Park Hotel",
		icon:'/images/iconHotel.png',
		zIndex: 10000000000
	});
	
}
var infowindow;
function attachURL(marker, url) {
	google.maps.event.addListener(marker, "click", function() {
		location.href = url;
	});
}
function attachInfoBox(marker, text, myMap, url) {
	google.maps.event.addListener(marker, "mouseover", function() {
		myZindex = myZindex + 1;
		this.setZIndex(myZindex);
		infoBox.setContent(text);
		infoBox.setUrl(url);
		infoBox.open(myMap, this);
		this.setIcon('/images/iconMarkerBig.png');
	});
	google.maps.event.addListener(marker, "mouseout", function() {
		this.setIcon('/images/iconMarker.png');
		setTimeout('infoBox.close()', 100);
	});
}
function openInfoBox(marker, text, myMap) {
	var myLatLan = marker.getPosition();
	myMap.setCenter(myLatLan);
	infoBox.setContent(text);
	infoBox.open(myMap, marker);
}

var setDirection = {
	options:{
		mapContainer: document.getElementById('mapBig'),
		dirContainer: document.getElementById('dirContainer'),
		dirService: "",
		dirRenderer: "",
		map: null
	},
	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(dirStausError) != 'undefined') alert(dirStausError +"\n(Google reports: "+ dirStatus +")");
		  return;
		}
		if(infowindow) infowindow.close();
		//jq('html,body').animate({scrollTop: jq('#mapBig').offset().top - 20}, 1000);
		setDirection.options.dirRenderer.setMap(maps);
		setDirection.options.dirRenderer.setPanel(document.getElementById('dirContainer'));
		setDirection.options.dirRenderer.setDirections(dirResult);
	}

}
var infowindow;
function setPoint(mapId, optiones, zoom, mapType, showCursor) {
	var myMarker = new Array();
	myMarker['iconsize'] = "30,30";
	myMarker['iconhancor'] = "0,15";
	myMarker['infowindow'] = "";
	
	for (names in optiones) myMarker[names] = optiones[names];
	var latlng = new google.maps.LatLng(myMarker['lat'], myMarker['lon']);
	if(mapType == undefined) mapType = "ROADMAP"; //ROADMAP - SATELLITE - HYBRID - TERRAIN 
	if(showCursor == undefined) showCursor = false;
    var myOptions = {
		disableDefaultUI: showCursor,
		mapTypeControl: true,
    	mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
		zoom: zoom,
		center: latlng,
		mapTypeId: google.maps.MapTypeId[mapType]
    };
    maps = new google.maps.Map(document.getElementById(mapId), myOptions);
	
	var myLatLng = new google.maps.LatLng(myMarker['lat'], myMarker['lon']);

	var marker = new google.maps.Marker({
		position: myLatLng,
		map: maps,
		icon: myMarker['icon'],
        zIndex: 10000
	});

	if(myMarker['infowindow'] != ""){
		infowindow = new google.maps.InfoWindow({
			content: myMarker['infowindow'],
			maxWidth: 350,
			position: myLatLng,
			zIndex: 100
		});
		infowindow.open(maps, infowindow);
		google.maps.event.addListener(marker, "click", function() {
			infowindow.open(maps, infowindow);
		});
	}
}

var base_64 = {
	_keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
	encode : function (input) {
		var output = "";
		var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
		var i = 0;
		input = Base64._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 = base_64._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;
	}
}

function createXmlHttpRequest(){
	try {
		if (typeof ActiveXObject != 'undefined') {
			return new ActiveXObject('Microsoft.XMLHTTP');
		} else if (window["XMLHttpRequest"]) {
			return new XMLHttpRequest();
		}
	} catch (e) {
		changeStatus(e);
	}
	return null;
}

function downloadUrl(url, callback) {
	var status = -1;
	var request = createXmlHttpRequest();
	if (!request) {
		return false;
	}
	
	request.onreadystatechange = function(){
		if (request.readyState == 4) {
			try {
				status = request.status;
			} catch (e) {
			}
			if (status == 200) {
				callback(request.responseXML, request.status);
				request.onreadystatechange = function() {};
			}
		}
	}
	request.open('GET', url, true);
	try {
		request.send(null);
	} catch (e) {
		changeStatus(e);
	}
}

// FINE MAPPA

// FUNZIONI PER IL FORM BOOKING OFFERTE //

function setRoomHome(nrooms, label_adults, label_children, label_children_age, label_room, element) {
	var form = element.parents('form');
	var myResults = '';
	
	if (nrooms > 1)	// se viene scelta pił di una camera...
	{
		for (var i=2; i<=nrooms; i++)	// preparo la stringa da accodare alla prima camera, contenente i campi necessari
		{
			myResults = myResults + '<li class="room'+ i +' roomTitle">'+ label_room +' '+ i +'</li>';
			
			myResults = myResults +	'<li class="room'+ i +' adults">'+
										'<label>'+ label_adults +'</label>'+
										'<select name="bform[reqRooms]['+ i +'][adults]">'+
											createSelect(6, 1, label_adults, "", 2)+
										'</select>'+
									'</li>'+
									'<li class="room'+ i +' children">'+
										'<label>'+ label_children +'</label>'+
										'<select name="bform[reqRooms]['+ i +'][child]" onchange="setChildAge(this.value,\'chdAge_'+ i +'\', '+ i +',\''+ label_children_age +'\', $(this));">'+
											createSelect(3, 0, label_children, "", 0)+
										'</select>'+
									'</li>'+
									'<li class="room'+ i +' childAge chdAge_'+ i +'"></li>';
		}
		
		$('li.room1.roomTitle', form).remove();				// rimuovo il titolo della camera 1 (per evitare duplicazioni nel caso sia gią presente: vedi istruzione successiva)
		$('li.room1:first', form).before('<li class="room1 roomTitle">'+ label_room +' 1</li>');		// aggiungo il titolo della camera 1, prima del primo campo della camera 1
		$('li.room1:last', form).nextAll().remove();		// rimuovo tutti gli elementi dopo l'ultimo elemento della camera 1
		$('li.room1:last', form).after(myResults);			// aggiungo dopo l'ultimo elemento della camera 1, la stringa preparata in precedenza
	}
	else			// se viene scelta una sola camera...
	{
		$('li.room1.roomTitle', form).remove();				// rimuovo il titolo della camera 1
		$('li.room1:last', form).nextAll().remove();		// rimuovo tutti gli elementi dopo l'ultimo elemento della camera 1
	}
}


function setChildAge(nchild, chdid, roomn, label_children_age, element){
	var form = element.parents('form');
	var selectHtml = "";
	
	if(nchild > 0){
		selectHtml = '<label>'+ label_children_age +'</label>';
		for (var cc=1; cc<=nchild; cc++) {
			selectHtml =  selectHtml + '<select name="bform[reqRooms]['+roomn+'][childAge][' + cc + ']">' +
                '<option value="0">&lsaquo; 1</option>';
				for(var k=1; k<=18; k++){
					k_opt = k<10 ? "&nbsp;"+ k : k;
					selectHtml =  selectHtml + "\n" + '<option value="'+ k +'">'+ k_opt +'</option>';
				}
				selectHtml =  selectHtml + '</select>';
		}
	}

	if($('.'+chdid, form)){
		$('.'+chdid, form).html(selectHtml);
	}
}


function createSelect(num, init, label, labels, selected){
	if(label != ""){
		label = " "+ label;
	}
	if(labels != ""){
		labels = " "+ labels;
	} else {
		labels = label;
	}
	var mySel = "";
	for(var k=init; k<=num; k++){
		if(k!=init) label = labels;
		if (selected != 0 && selected == k){
			//mySel = mySel + "\n" + '<option value="'+ k +'" selected="selected">'+ k + label +'</option>';	// numero + nome
			mySel = mySel + "\n" + '<option value="'+ k +'" selected="selected">'+ k + '</option>';				// solo numero
		} else {
			//mySel = mySel + "\n" + '<option value="'+ k +'">'+ k + label +'</option>';	// numero + nome
			mySel = mySel + "\n" + '<option value="'+ k +'">'+ k + '</option>';				// solo numero
		}
	}
	return mySel;
}