/*
 * @ ItalyHotels
 */
// it.opera21 namespace
var it = it || {};
it.opera21 = {
	
	getBeginWithKeyFromCollection: function(collection, obj, key) {
		
		var matches = [];
		var key = jQuery.trim(key.toLowerCase());
		
		for (var i=0; i<collection.length; i++) {
			
			var label = jQuery.trim(collection[i][obj].toLowerCase());
		
			if (label.indexOf(key) == 0) {
				matches.push(collection[i]);
			}
			
		}
		
		return matches;
	
	},
 		
 	collectionDiff: function(collectionA, collectionB, field) {
		
		function getKeyPosition(value, array) {
			
			for (var i=0; i<array.length; i++) {
				if (array[i][field] == value[field]) {
					return i;
				}
			}
			
			return -1;
			
		};
		
		for (var i=0; i<collectionB.length; i++) {
		
			var pos = getKeyPosition(collectionB[i], collectionA);
			
			if (pos != -1) {
				collectionA.splice(pos, 1);
			}
			
		}
		
		return collectionA;
		
	}
		
};

/**
 * JSON
 */
Json = (function(){
	 var JSON = {};
	(function () {
	
	    function f(n) {
	        return n < 10 ? '0' + n : n;
	    }
	
	    if (typeof Date.prototype.toJSON !== 'function') {
	
	        Date.prototype.toJSON = function (key) {
	
	            return this.getUTCFullYear()   + '-' +
	                 f(this.getUTCMonth() + 1) + '-' +
	                 f(this.getUTCDate())      + 'T' +
	                 f(this.getUTCHours())     + ':' +
	                 f(this.getUTCMinutes())   + ':' +
	                 f(this.getUTCSeconds())   + 'Z';
	        };
	
	        String.prototype.toJSON =
	        Number.prototype.toJSON =
	        Boolean.prototype.toJSON = function (key) {
	            return this.valueOf();
	        };
	    }
	
	    var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
	        escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
	        gap,
	        indent,
	        meta = {    
	            '\b': '\\b',
	            '\t': '\\t',
	            '\n': '\\n',
	            '\f': '\\f',
	            '\r': '\\r',
	            '"' : '\\"',
	            '\\': '\\\\'
	        },
	        rep;
	
	
	    function quote(string) {
	
	        escapable.lastIndex = 0;
	        return escapable.test(string) ?
	            '"' + string.replace(escapable, function (a) {
	                var c = meta[a];
	                return typeof c === 'string' ? c :
	                    '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
	            }) + '"' :
	            '"' + string + '"';
	    }
	
	
	    function str(key, holder) {
	
	        var i, 
	            k, 
	            v,  
	            length,
	            mind = gap,
	            partial,
	            value = holder[key];
	
	        if (value && typeof value === 'object' &&
	                typeof value.toJSON === 'function') {
	            value = value.toJSON(key);
	        }
	
	        if (typeof rep === 'function') {
	            value = rep.call(holder, key, value);
	        }
	        switch (typeof value) {
	        case 'string':
	            return quote(value);
	
	        case 'number':
	
	            return isFinite(value) ? String(value) : 'null';
	
	        case 'boolean':
	        case 'null':
			
	            return String(value);
	
	        case 'object':
	
	            if (!value) {
	                return 'null';
	            }
	            gap += indent;
	            partial = [];
	
	            if (Object.prototype.toString.apply(value) === '[object Array]') {
	
	                length = value.length;
	                for (i = 0; i < length; i += 1) {
	                    partial[i] = str(i, value) || 'null';
	                }
	
	                v = partial.length === 0 ? '[]' :
	                    gap ? '[\n' + gap +
	                            partial.join(',\n' + gap) + '\n' +
	                                mind + ']' :
	                          '[' + partial.join(',') + ']';
	                gap = mind;
	                return v;
	            }
	            if (rep && typeof rep === 'object') {
	                length = rep.length;
	                for (i = 0; i < length; i += 1) {
	                    k = rep[i];
	                    if (typeof k === 'string') {
	                        v = str(k, value);
	                        if (v) {
	                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
	                        }
	                    }
	                }
	            } else {
	                for (k in value) {
	                    if (Object.hasOwnProperty.call(value, k)) {
	                        v = str(k, value);
	                        if (v) {
	                            partial.push(quote(k) + (gap ? ': ' : ':') + v);
	                        }
	                    }
	                }
	            }
	            v = partial.length === 0 ? '{}' :
	                gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' +
	                        mind + '}' : '{' + partial.join(',') + '}';
	            gap = mind;
	            return v;
	        }
	    }
	    if (typeof JSON.stringify !== 'function') {
	        JSON.stringify = function (value, replacer, space) {
	            var i;
	            gap = '';
	            indent = '';
	            if (typeof space === 'number') {
	                for (i = 0; i < space; i += 1) {
	                    indent += ' ';
	                }
	
	            } else if (typeof space === 'string') {
	                indent = space;
	            }
	            rep = replacer;
	            if (replacer && typeof replacer !== 'function' &&
	                    (typeof replacer !== 'object' ||
	                     typeof replacer.length !== 'number')) {
	                throw new Error('JSON.stringify');
	            }
	            return str('', {'': value});
	        };
	    }
	    if (typeof JSON.parse !== 'function') {
	        JSON.parse = function (text, reviver) {
	            var j;
	
	            function walk(holder, key) {
	                var k, v, value = holder[key];
	                if (value && typeof value === 'object') {
	                    for (k in value) {
	                        if (Object.hasOwnProperty.call(value, k)) {
	                            v = walk(value, k);
	                            if (v !== undefined) {
	                                value[k] = v;
	                            } else {
	                                delete value[k];
	                            }
	                        }
	                    }
	                }
	                return reviver.call(holder, key, value);
	            }
	
	            cx.lastIndex = 0;
	            if (cx.test(text)) {
	                text = text.replace(cx, function (a) {
	                    return '\\u' +
	                        ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
	                });
	            }
	            if (/^[\],:{}\s]*$/.
	test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
	replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
	replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
	                j = eval('(' + text + ')');
	                return typeof reviver === 'function' ?
	                    walk({'': j}, '') : j;
	            }
	            throw new SyntaxError('JSON.parse');
	        };
		}
	}());
	return {
		encode: function(o){
			return JSON.stringify(o);
		},
		decode: function(o){
			return JSON.parse(o);
		}
		
	}
})();

/*****************************************************************************************************
 * CONF
 *****************************************************************************************************/

/* oggetto di configurazione */
var config = {	
	
	// caledar
	CALENDAR_BUTTON_IMG_SRC : '/portlets/images/cal_icon.png',
	
	// dom 
	CALENDAR_CLASS : 'uiCal',
	LOCALITA_ID : 'LOCALITA',
	UBICAZIONE_ID : 'UBICAZIONE',
	TIPOLOGIA_ID : 'TYPOLOGY',
	CATEGORIA_ID : 'CATEGORY',
	SERVIZI_ID : 'SERVIZI',
	TOURISTZONE_ID : 'TOURISTZONE',
	SERVIZI_MONITOR_ID : 'serviziMonitor',
	SERVIZI_MONITOR_ID_RIGHT : 'serviziMonitorRight',
	SEARCH_MONITOR :'searchResultMonitor',
	BOOKING_HOTEL_ID : 'bookingProductList',
	ROOM_N_ID : 'camera_n',
	ROOM_N_ID_REQUEST : 'camera_n_request',
	TABLE_PAX_ID : 'pax',
	PRENOTAZIONE_ID : "prenotazione",
	CREDITCARD_ID : "datiCarta",
	HOTEL_DETTAGLIO_ID : "hotelDetailsContainer",
	TABLE_PAX_ID_REQUEST : 'paxRequest',
	SIMPLE_SEARCH_ID : 'simpleSearchForm',
	ADVANCED_SEARCH_ID : 'advancedSearchForm',
	SLIDER_ID : 'slider',
	SLIDER_MAXRANGE_ID : 'maxRange',
	SLIDER_MINRANGE_ID : 'minRange',
	GALLERY_CLASS : 'boxGalleryContent',
	DAY : 1000*60*60*24,	

	// proxy
	SITE_URL : '/',
	PAGE_SIZE : 20,
	PAGING_ENABLED : true,
	
	// rooms
	MAX_ROOM : 8,
	MAX_PAX_PER_ROOM : 5,
	MAX_ADULTI : 4,
	MAX_CHD : 3,
	DEFAULT_ADULTI : 2,
	DEFAULT_CHD :0,
	CHD_MAX_AGE :18,
	
	//gallery
	ON_MOUSE_OUT_OPACITY : 0.67,
	
	// slider
	SLIDER_MIN : 0,
	SLIDER_MAX : 1000
}

config.calendarBase ={
	showOn : 'button',
	buttonImage : config.CALENDAR_BUTTON_IMG_SRC,
	dateFormat: 'D dd/mm/yy',
	minDate : new Date(),
	onSelect: function(dateText, inst){
		
		var month = inst.selectedMonth + 1;
		var id = jQuery(this).attr('id');
		jQuery("input[name='" + id + "']").val(inst.selectedDay + '/' + month + '/' + inst.selectedYear);
		/* se si modifica la data di arrivo restringi la scelta di quella di partenza*/
		if(jQuery(this).attr('id') == 'arrivo'){
			var arrDate = new Date(jQuery('#arrivo').datepicker('getDate'));			
			jQuery('#partenza').datepicker( 'option', 'minDate', new Date(arrDate.setDate(arrDate.getDate() + 1)));
			var suppDate = document.getElementById('partenza').value;			
			jQuery('input[name="partenza"]').val(suppDate.substr(4,11));
		}
		/* show the number of nights*/
		if(jQuery('#partenza').datepicker('getDate')){
			var one_day= config.DAY;
			var nights = Math.ceil((jQuery('#partenza').datepicker('getDate') - jQuery('#arrivo').datepicker('getDate'))/(one_day));		
			jQuery('span#nights').text(nights);
		}
	}
}

config.autocompleteBase ={
	dataType: "json",
	matchSubset : false
}

config.validationRules = {
	errorContainer: "#messageBox",
   	errorLabelContainer: "#messageBox ul",
   	wrapper: "li", 
	rules :{
	localita :{
			notBothEmpty : 'hotel'
		},
		hotel : {
			notBothEmpty : 'localita',
			minlength: 3
		},
		arrivo :{
			required : true
		},
		partenza :{
			required : true
		}	
	}
};

if(dictionary){
	config.validationRules.messages = {
			localita :{
			notBothEmpty : dictionary.ih_search_dove_error_msg
		},
		hotel : {
			notBothEmpty : dictionary.ih_search_dove_hotel_error_msg,
			minlength:dictionary.ih_search_dove_hotel_length_error_msg
		},
	    arrivo :{
			required : dictionary.ih_search_arrivo_error_msg
		},
	    partenza :{
			required : dictionary.ih_search_partenza_error_msg
		}		
	}
}


/****************************************************************************************************
 * REMOTE PROXY
 ****************************************************************************************************/
if(!IH){
	var IH = {}; 
}

IH.externalInterface = {
	
	setRegione : function(id,label,entity){
		
		jQuery("#" + config.LOCALITA_ID.toLowerCase()).value = label;
		jQuery("input[name='localita']").val(label);
		jQuery("input[name='locationEntity']").val(entity);
		jQuery("input[name='locationId']").val(id);
		
	}//,
	//getDetail : function(hotelCode){
	//	location.href = linkDettaglioPart1+"&hotelCode="+hotelCode;
	//}
}


IH.handlers = {
	
	
	errorDisplay : function(id,msg){
		jQuery('#' + id).html(msg);
		jQuery.unblockUI();		
	},
	
	formatErrorMsg : function(text){
		var html = '<div class="portlet-content"><span class="portlet-msg-error">' + text + '</span></div>'
		return html;
	},
	
	doSelection : function(obj,value){
		
		var options = jQuery(obj).children();
		for(var i=0; i < options.length; i++){
			if(options[i].value == value){				
				options[i].selected = true;
			}	
		}
	},
	
	doCheckBoxSelection : function(obj,value){
		
		for(var s=0; s < value.length; s++){
			var item = value[s];
			for(var i=0; i < obj.length; i++){
				var el = jQuery(obj[i]);
				if(el.val() == item){
					el.attr('checked','checked');
				}
			}	
		}
	},
	
	setSliderValues : function(obj,min,max){
		
		var els = jQuery(obj).find('a');
		jQuery(obj).slider('values',min,max);
		jQuery(els[0]).text(min);
		jQuery('#' + config.SLIDER_MINRANGE_ID).val(min);
		jQuery(els[1]).text(max);
		jQuery('#' + config.SLIDER_MAXRANGE_ID).val(max);	
	}	
	
};


/****************************************************************************************************
 * DETTAGLIO PAX
 * Classe rappresenta il dettaglio viaggiatori
 ****************************************************************************************************/

var DettaglioPax = function(id){
	
	this.el = jQuery(document.getElementById(id));
	this.addRow();
	this.bind();
}

DettaglioPax.prototype ={
	
	addRow: function(){
		
		if(this.el.find('tr').length < 8) {
			var rowIndex = this.el.find('tr').length + 1;
			var arr = [];
			arr.push('<tr rel="' + rowIndex + '"><td><label>'+dictionary.ih_booking_mail_adult+'</label><select class="onAdultChange" name="camera_' + rowIndex + '_adult">');
			/*inizia da uno. Non e' possibile selezionare 0 Adulti */
			for(var i=1; i <= config.MAX_ADULTI; i++){
				if(i == config.DEFAULT_ADULTI){
					arr.push('<option value="' + i + '" selected="selected">' + i + '</option>');				
				}else{
					arr.push('<option value="' + i + '">' + i + '</option>');				
				}
			}
			arr.push('</select></td>');
			if(window.isConvenzione != undefined){
				if(isConvenzione!="true"){
				arr.push('<td><label>'+dictionary.ih_booking_mail_chd+'</label><select name="camera_' + rowIndex + '_chd" class="onChdChange">');
				/* children */
				for(var i=0; i <= config.MAX_CHD; i++){
					if(i == config.DEFAULT_CHD){
						arr.push('<option value="' + i + '" selected="selected">' + i + '</option>');				
					}else{
						arr.push('<option value="' + i + '">' + i + '</option>');				
					}
				}
				arr.push('</td>');
				}
			}
			arr.push('</tr>');					
			this.el.append(arr.join(' '));
		}
		
	},
	
	addRows : function(n){
		
		for(var i=1; i <=n; i++){
			this.addRow();
			this.bind();
		}
		
	},
	
	removeRows : function(n){

		for(var i=1; i <=n; i++){
			this.removeLastRow();
		}
		
	},
		
	removeLastRow : function(){
		var el = this.el.find('tr')[this.el.find('tr').length - 1];
		jQuery(el).remove();
	},
	
	bind : function(){
		
		var _instance = this;
		
		//onAdultChange		
		jQuery(this.el).find('select.onAdultChange').bind('change',function(){
			var $el = jQuery(this);
			var adults = $el.val();
			var row = $el.parent().parent('tr').attr('rel');
			// resetta chd select  
			_instance.resetChdSelection(row,adults);
			// resetta slots eta' bambini 
			
		});
		
		//onChdChange
		jQuery(this.el).find('select.onChdChange').bind('change',function(){
			var $el = jQuery(this);
			var $row = jQuery($el.parent().parent('tr'));
			var rowIndex = $row.attr('rel');
			var value = $el.val();
			var actualElements = $row.find('td.chdAge').length;
			
			// add remove chd age slots
			if(value != actualElements){
				
				if(value > actualElements){
					_instance.addChdAge(rowIndex,value - actualElements);	
				}else if(value < actualElements){
					_instance.removeChdAge(rowIndex,actualElements - value);						
				}
			}
			
			//reset adults select
			_instance.resetAdultsSelection(rowIndex,value);
		});
		
		
	},
	
	resetChdSelection : function(row,adults){
		
		var $sel = this.el.find("tr[rel='" + row + "']").find('.onChdChange');
		var value = $sel.val();
		var chdAvailable = config.MAX_PAX_PER_ROOM - adults;
		// reset to max chd if is over ( ex: 1 adults should give 4 chs slots )
		if(chdAvailable > config.MAX_CHD){
			chdAvailable = config.MAX_CHD;
		}
		// if previous selection is over the new max change selected 
		if(value > chdAvailable){
			value = chdAvailable;
		}
				
		var arr = [];
		
		for(var i = 0 ; i <= chdAvailable; i++){
			var el = '<option value="' + i + '">' + i + '</option>';
			if(i == value){
				el = '<option value="' + i + '" selected="selected">' + i + '</option>';
			}
			arr.push(el);
		}
		// write the chd select
		$sel.html(arr.join(' '));
		
		// remove the extra chd age slots
		var chdSlots = this.el.find("tr[rel='" + row + "']").find('.chdAge').length;
		var toRemove = chdSlots - value;
		if(toRemove > 0){
			this.removeChdAge(row,toRemove);		
		}
	},

	resetAdultsSelection : function(row,chds){
		
		var $sel = this.el.find("tr[rel='" + row + "']").find('.onAdultChange');
		var value = $sel.val();
		var adultsAvailable = config.MAX_PAX_PER_ROOM - chds;
		// reset to max chd if is over ( ex: 1 adults should give 4 chs slots )
		if(adultsAvailable > config.MAX_ADULTI){
			adultsAvailable = config.MAX_ADULTI;
		}
		// if previous selection is over the new max change selected 
		if(value > adultsAvailable){
			value = adultsAvailable;
		}
				
		var arr = [];
		
		for(var i = 1 ; i <= adultsAvailable; i++){
			var el = '<option value="' + i + '">' + i + '</option>';
			if(i == value){
				el = '<option value="' + i + '" selected="selected">' + i + '</option>';
			}
			arr.push(el);
		}
		// write the chd select
		$sel.html(arr.join(' '));
	},
	
	addChdAge : function(rowIndex,n){
		
		var jQueryrow = this.el.find("tr[rel='" + rowIndex + "']");
		var elementIndex = jQueryrow.find('td.chdAge').length + 1;
		var inf = '0-2';
		
		for(var i = 1; i <= n; i++){
			var arr = ['<td class="chdAge"><label>Et&agrave; Bambino</label><select name="camera_' + rowIndex + '_chd_' + elementIndex + '">'];
			for(var a = 1; a <= config.CHD_MAX_AGE; a++){
				if(a == 1 ){
					arr.push('<option value="' + inf + '">' + inf + '</option>');		
				}else{				
					arr.push('<option value="' + a + '">' + a + '</option>');		
				}				
			}
			arr.push('</select></td>');
			jQueryrow.append(arr.join(' '));
			elementIndex++;	
		}
	},
	
	removeChdAge : function(rowIndex,n){
		
		var jQueryrow = this.el.find("tr[rel='" + rowIndex + "']");
		
		for(var i=1; i <= n; i++){
			var el = jQueryrow.find('td.chdAge')[jQueryrow.find('td.chdAge').length -1];
			jQuery(el).remove();
		}
		
	},
	
	getRowsCount : function(){
		
		return this.el.find("tr").length;
	}
	
}





/************************************************
 * TOOLTIP PRODUCT DESCRIPTION
 * result page
 ***********************************************/

showDescription = function(nomeHotel,name,description){
	jQuery.blockUI({ 
        message: "<div id='tooltip'><img src='/portlets/images/close.gif' id='tooltipClose' onclick='jQuery.unblockUI();'/><p class='tooltipHotel'>"+ nomeHotel +"</p><hr class='hr1'/><div class='clear'/><p class='contenuto'><a class='description'>Descrizione</a><br/>"+ name + "<br/>" +description +"</p><hr class='hr2'/></div>",
		css: {
			left: '25%',
			width:'652px'
		}
    }); 
}


showServiceDescription = function(nomeHotel, name, description, images){
	var imagesTag = "";
	var slideArray = new Array();
	if (images.length > 0) {
		for (im = 0; im < images.length; im++) {
			imagesTag = imagesTag + "<img src='" + images[im] + "' alt='Immagine Servizio' class='serviceImage' style='max-width:500px;'/><br/>";
			slideArray[im] = [images[im],"","",""];
		}
	}
	/*imagesTag nel center*/	
	jQuery.blockUI({ 
        message: "<div id='tooltip'><p class='tooltipHotel'>"+ nomeHotel +"</p><hr class='hr1'/><img src='/portlets/images/close.gif' id='tooltipCloseServices' onclick='jQuery.unblockUI();'/><div class='clear'/><p class='contenuto'><a class='description'>Descrizione</a><br/>"+ name + "<br/>" + description + "<br/><center><div id='simplegallery1'>&nbsp;</div></center><br/></p><hr class='hr2'/></div>",
		css: {
			left: '25%',
			top: '18%',
			width:'652px'
		}
    }); 
	if (images.length > 0) {
		var mygallery = new simpleGallery({
			wrapperid: "simplegallery1",
			dimensions: [250, 180],
			imagearray: slideArray,
			autoplay: [true, 2500, 2],
			persist: false,
			fadeduration: 500,
			oninit: function(){
			
			},
			onslide: function(curslide, i){
			
			}
		});
	}
}


this.tooltip = function(){	
	/* CONFIG */		
		xOffset = 10;
		yOffset = 20;		
		// these 2 variable determine popup's distance from the cursor
		// you might want to adjust to get the right result		
	/* END CONFIG */		
	jQuery("a.tooltip").hover(
		function(e){
		    e.preventDefault();
			this.t = this.title;
			this.title = "";
		},function(e){
			e.preventDefault();
			this.title = this.t;
	}); 
	jQuery("a.tooltip").click(function(e){											  
		
		jQuery.blockUI({ 
            message: "<div id='tooltip'><img src='/portlets/images/close.gif' id='tooltipClose' onclick='jQuery.unblockUI();'/><hr/><p><a class='description'>Descrizione</a><br/>"+ this.t +"</p><hr/></div>",
			css: {
				left: '25%',
				width:'652px'
			}
        }); 								  
				
    },
	function(){
		this.title = this.t;		
		jQuery("#tooltip").remove();
    });	

};



/********************************************************************************************************
 * PAGE LOADER
 * classe che gestisce il caricamento degli script in base agli elementi della pagina
 ********************************************************************************************************/

var ihPage = (function(){
	
	var paxs;

	return{
		
		doCalendar : function(c){
			
			jQuery('.' + c).datepicker(config.calendarBase);
			
			var today = new Date();
			if(typeof(params) == 'object' && params.arrivo){
				var sp = params.arrivo.split('/');
				today.setDate(sp[0]);
				today.setMonth(sp[1] - 1);
				today.setFullYear(sp[2]);
			}
			var month = today.getMonth()+1;
			
			jQuery('#arrivo').datepicker('setDate', today);
			jQuery('input[name="arrivo"]').val(today.getDate() + '/' + month + '/' + today.getFullYear());
			
			var arrDate = new Date(jQuery('#arrivo').datepicker('getDate'));
			var depDate = new Date(arrDate.setDate(arrDate.getDate() + 1));
			
			if(typeof(params) == 'object' && params.partenza) {
				var sp = params.partenza.split('/');
				depDate.setDate(sp[0]);
				depDate.setMonth(sp[1] - 1);
				depDate.setFullYear(sp[2]);				
			}
			
			jQuery('#partenza').datepicker( 'option', 'minDate', depDate);
			jQuery('#partenza').datepicker( 'setDate',depDate);
			
			var departureMonth = depDate.getMonth();
			departureMonth++;			
			jQuery('input[name="partenza"]').val(depDate.getDate() + '/' + departureMonth + '/' + depDate.getFullYear());	

			var one_day=config.DAY;
			var nights = Math.ceil((jQuery('input[id="partenza"]').datepicker('getDate') - jQuery('input[id="arrivo"]').datepicker('getDate'))/(one_day));		
			jQuery('span#nights').text(nights);		

		},
		
		doAutoComplete : function(id){

			var el = jQuery(document.getElementById(id));
			var opts = config.autocompleteBase;
			
			opts.parse = function(data) {
				
				// used to sort data by label
				var sortFunction = function(a, b){
					var k1 = a.label.toLowerCase();
					var k2 = b.label.toLowerCase();
					return (k1 > k2) - (k1 < k2); 
				};
				//kia invece di data.data -> solo data per nuovo flusso con ejb "{"code":"","data":" rimosso
				// show exact matches before similar matches (ie: "Roma" before "Fiano Romano")
				var rightMatches = it.opera21.getBeginWithKeyFromCollection(data, "label", el.val());
				var likeMatches = it.opera21.collectionDiff(data, rightMatches, "label");
				
				rightMatches.sort(sortFunction);
				likeMatches.sort(sortFunction);
				
				var parsed = [];
				data = rightMatches.concat(likeMatches);
				
				for (var i = 0; i < data.length; i++) {
					if(data[i].entity == 'PROVINCE'){
						data[i].label = data[i].label + ' (Prov.)'
					}
					parsed[i] = {
						data: data[i],
						value: data[i].id,
						result: data[i].label
					};
				}
				
				return parsed;
				
			}
						
			opts.formatItem = function(row) {
				return row.label;
			}

			var url = config.SITE_URL + 'portlets/json/getEntityList/';
			

			opts.extraParams = {
				entity : config.LOCALITA_ID,
				locale : locale,
				limit  : 1000,
				site   : sitedef
				}
			  
			jQuery('input[name="locationEntity"]').val("");
		    jQuery('input[name="locationId"]').val("");		

			
			jQuery(el).autocomplete(url,opts).result(function(e, item) {
			    jQuery('input[name="locationEntity"]').val(item.entity);
			    jQuery('input[name="locationId"]').val(item.id);					
			});
				
		},
		
		doMaxRoomSelect :function(id,tableId,pax){

			var el = jQuery(document.getElementById(id));

			/* crea la select per la selezione del numero di camere*/
			var els = [];
			for(var i=0; i<config.MAX_ROOM;i++){
				var counter = i + 1;
				els.push('<option value="' + counter + '">' + counter + '</option>' );
			}
			
			el.html(els.join(' '));

			/*bind the num room change only if exists the table for the pax details*/
			if(jQuery('#' + tableId).length){
				
				el.change(function(){
					var value = jQuery(this).val();
					var actualRows = pax.getRowsCount();
					
					if(value > actualRows){
						pax.addRows(value - actualRows);
					}else if(value < actualRows){
						pax.removeRows(actualRows - value);
					}
					 	
				});
				
			}
			
		},
		
		doSlider : function(id){
			
			jQuery('#' + id).slider({
					range: true,
					min: config.SLIDER_MIN, 
					max : config.SLIDER_MAX,
					slide: function(event, ui ,els) {
						var els = jQuery('#' + id).find('a');
						var min = ui.values[0];
						var max = ui.values[1];						
						jQuery(els[0]).text(min).addClass('sliderLeft');
						jQuery('#' + config.SLIDER_MINRANGE_ID).val(min);
						jQuery(els[1]).text(max).addClass('sliderRight');
						jQuery('#' + config.SLIDER_MAXRANGE_ID).val(max);								
					}
				});

			/* init default */
			var min = 1;
			var max = config.SLIDER_MAX;
			if(typeof(params) == 'object' && typeof(params.rangeMin) != 'undefined' && typeof(params.rangeMax) != 'undefined'){
				min = params.rangeMin;
				max = params.rangeMax;
			}	
			
			IH.handlers.setSliderValues(jQuery('#slider'),min,max);
			
			/* set the checkBox behaviour*/
			if(jQuery('#checkPrice').length){
				jQuery('#checkPrice').click(function(){
					if(jQuery(this).attr('checked')){
						jQuery('#slider').slider('disable');
						jQuery('#' + config.SLIDER_MINRANGE_ID).attr('disabled','disabled');
						jQuery('#' + config.SLIDER_MAXRANGE_ID).attr('disabled','disabled');
					}else{
						jQuery('#slider').slider('enable');
						jQuery('#' + config.SLIDER_MINRANGE_ID).attr('disabled','');
						jQuery('#' + config.SLIDER_MAXRANGE_ID).attr('disabled','');
					}
				});
			}							
		},
		checkMonth : function (){
			
			var minExpDate = new Date();
			var selectedExpYear = jQuery("#expYear").val();
			var currentMonth = minExpDate.getMonth()+1;
			var defaultMonth = currentMonth+1;
			if(selectedExpYear==minExpDate.getFullYear()){
				jQuery("#expMonth option").each(function (index,obj){
					if(jQuery(obj).val() <= currentMonth){
						jQuery(obj).attr("disabled","disabled");
					}
					if(jQuery(obj).val() == defaultMonth){
						jQuery(obj).attr("selected","selected");
					}
				});
			}else{
				jQuery("#expMonth option").each(function (index,obj){
					if(jQuery(obj).val() <= currentMonth){
						jQuery(obj).removeAttr("disabled");
						jQuery(obj).removeAttr("selected");
					}
				});
			}
		},
		doGallery : function(id,index){
			
			jQuery('#thumbs_' + index + ' ul.thumbs li').css('opacity', config.ON_MOUSE_OUT_OPACITY)
				.hover(
					function () {
						jQuery(this).not('.selected').fadeTo('fast', 1.0);
					}, 
					function () {
						jQuery(this).not('.selected').fadeTo('fast', config.ON_MOUSE_OUT_OPACITY);
					}
				);

			var galleryAdv = jQuery('#' + id).galleriffic('#thumbs_' + index, {
				delay:                  3000,
				numThumbs:              9,
				preloadAhead:           10,
				enableTopPager:         false,
				enableBottomPager:      true,
				imageContainerSel:      '#slideshow_' + index,
				controlsContainerSel:   '#controls_' + index,
				captionContainerSel:    '#caption_' + index,
				loadingContainerSel:    '#loading_' + index,
				renderSSControls:       true,
				renderNavControls:      false,
				playLinkText:           '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Play',
				pauseLinkText:          '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Pause',
				prevLinkText:           '&lsaquo; Previous Photo',
				nextLinkText:           'Next Photo &rsaquo;',
				nextPageLinkText:       'Next &rsaquo;',
				prevPageLinkText:       '&lsaquo; Prev',
				enableHistory:          false,
				autoStart:              false,
				onChange:               function(prevIndex, nextIndex) {
					jQuery('#thumbs_' + index + ' .thumbs').children()
						.eq(prevIndex).fadeTo('fast', config.ON_MOUSE_OUT_OPACITY).end()
						.eq(nextIndex).fadeTo('fast', 1.0);
					var img = jQuery('#thumbs_' + index + ' .thumbs').children().eq(nextIndex).find('img');
					var imgHeight = parseInt(img.css('height'));
					var imgWidth = parseInt(img.css('width'));							
					var monitorHeight = 188;
					var ratio = monitorHeight / imgHeight;
					width = Math.ceil(imgWidth * ratio);
				},
				onTransitionOut:        function(callback) {
					jQuery('#slideshow_' + index).fadeTo('fast', 0.0, callback);
				},
				onTransitionIn: function() {
					jQuery('#slideshow_' + index).fadeTo('fast', 1.0);
					var href = jQuery('#slideshow_' + index + ' img').attr('src');
					jQuery('a.fullScreen_' + index).attr({
						'href': href
					});
					jQuery('#slideshow_' + index + ' img').css('width',width);
					jQuery('#slideshow_' + index + ' img').css('heigth',10);
				},
				onPageTransitionOut:    function(callback) {
					jQuery('#thumbs_' + index + ' .thumbs').fadeTo('fast', 0.0, callback);
				},
				onPageTransitionIn:     function() {
					jQuery('#thumbs_' + index + ' .thumbs').fadeTo('fast', 1.0);
				}
			});
			jQuery('#controls_' + index).append('<a href="#"class="fullScreen_' + index + ' cursor thumb">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Fullscreen</a>');
			
			jQuery('a.fullScreen_' + index).click(function(e){
				e.preventDefault();
				jQuery('a.pause').trigger('click');					
				Shadowbox.open({
					player: 'img', 
					content : jQuery('#slideshow_' + index).find('img').attr('src')
				})
			});
		}		
	}
})();

/*
 * OnReady apply behaviours required
 */

function loadSearchForm(){
var form;
	
	if(document.getElementById(config.SIMPLE_SEARCH_ID)){
		form = document.getElementById(config.SIMPLE_SEARCH_ID);	
	}else if(document.getElementById(config.ADVANCED_SEARCH_ID)){
		form = document.getElementById(config.ADVANCED_SEARCH_ID);
	}

	if(form){
		var $form = jQuery(form);

		if(jQuery('#nonsaidove').size()==0){
			form.reset();
			$form.validate(config.validationRules);
		}
	}

	/* Autocomplete Localita*/
	if(document.getElementById(config.LOCALITA_ID.toLowerCase())){
		if(jQuery('#nonsaidove').size()==0){		
		ihPage.doAutoComplete(config.LOCALITA_ID.toLowerCase());
		}
	}
	
	/*Room Number select*/
	if(document.getElementById(config.ROOM_N_ID)){
		ihPage.doMaxRoomSelect(config.ROOM_N_ID,config.TABLE_PAX_ID,new DettaglioPax(config.TABLE_PAX_ID));
	}	
	
	/*Slider */
	if(jQuery('#' + config.SLIDER_ID).length){
		ihPage.doSlider(config.SLIDER_ID);
	}
	
	/* cradit card stuff*/
	if(document.getElementById(config.CREDITCARD_ID)){
		ihPage.checkMonth();
		tooltip();
	}
	
	jQuery("#simpleSearchForm, #advancedSearchForm").bind("submit", function(){
		
		return checkLocalita(this);
		
	});

}

jQuery(document).ready(function(){
	fixLanguageChange();
	
	/*Gallery */
	if(jQuery('.' + config.GALLERY_CLASS).length){
		Shadowbox.init({
		    players: ["img"]
		});
	}
	
	/*Calendar*/
	if(jQuery('.' + config.CALENDAR_CLASS).length){
		
		setTimeout(function() {
			ihPage.doCalendar(config.CALENDAR_CLASS);
		}, 0);
		
	}

	richiediDisp();


	tooltip();
});

function checkLocalita(form){
	
	
	var url = config.SITE_URL + 'portlets/json/getEntityList/';

	var hiddenFieldsNotDef = jQuery.trim(form.locationEntity.value) == "" || jQuery.trim(form.locationId.value) == "" || jQuery.trim(form.localita.value) == "";

	var bottone = form.locationId;	
	for(var i=0; i<bottone.length; i++) {
	  if(bottone[i].checked) {
		  hiddenFieldsNotDef = false;
	    break;
	  }
	}
	// Form is invalid!!
	if (
		(jQuery.trim(form.hotel.value) == "" && hiddenFieldsNotDef) ||
		(jQuery.trim(form.localita.value) != "" && hiddenFieldsNotDef)
	) {
		// Retrieve data
		jQuery.ajax({
			"url": url,
			method: "post",
			dataType: "json",
			data: {
				criteria: form.localita.value,
				entity: config.LOCALITA_ID,					
				locale: locale,
				limit: 1000,
				site   : sitedef
			}, 
			success: function(res) {
				
				// I've got data
				if (res.length) {
					
					// sort data by "label" field
					res.sort(function(a, b) {
						var k1 = a.label.toLowerCase();
						var k2 = b.label.toLowerCase();
						return (k1 > k2) - (k1 < k2);
					});
					
					// exact labels
					var exactMatches = [];
					
					// "entity" field importance (a lower values means higher importance)
					var entitiesValues = {
						city: 1,
						province: 2,
						area: 3,
						region: 4,
						iatacode: 5
					};
					
					// find exact labels
					for (var i=0; i<res.length; i++) {
						if (jQuery.trim(res[i].label.toLowerCase()) == jQuery.trim(form.localita.value.toLowerCase())) {
							exactMatches.push(res[i]);
						}
					}
					
					// I've got one or more matching labels
					if (exactMatches.length) {
						
						var item = exactMatches[0];
						
						// sort matches by importance
						exactMatches.sort(function(a, b) {
							var e1 = a.entity.toLowerCase();
							var e2 = b.entity.toLowerCase();
							return entitiesValues[e1] > entitiesValues[e2];
						});
					
						jQuery('input[name="locationEntity"]').val(item.entity);
				    	jQuery('input[name="locationId"]').val(item.id);	
						
						form.submit();
						
					} else { // No exact match found, user must choose one among results
						
						createModalDialogHTML(dictionary.ih_search_select_loc_modal, '<ul id="opt-modal-win"></ul>');
						
						window._setHiddenFields = function(obj) {
							var o = jQuery(obj);
							jQuery('input[name="locationEntity"]').val(o.attr("opt-entity"));
				    		jQuery('input[name="locationId"]').val(o.attr("opt-id"));	
							form.localita.value = jQuery.trim(o.html());
							jQuery(".ac_results").hide();
							jQuery("#modal-win").dialog("destroy");
						};
						
						for (var j=0; j<res.length; j++) {
							
							var li = res[j];
							
							jQuery("#opt-modal-win").append([
								'<li opt-id="', li.id, '" opt-entity="', li.entity, '" onclick="_setHiddenFields(this)">',
									li.label,
								'</li>'
							].join(""));
						}
						
					}
					
				} else {
					
					form.localita.value = "";
					
					createModalDialogHTML(dictionary.error, "<p>"+dictionary.ih_search_not_found_loc+"<p>");
					
				}
				
			},
			error: function(xhr, status, e) {
				
				if (typeof console != "undefined") {
					console.log("error: ", e);
				}
				
			}
		});
		
		// Block form submission
		return false;
		
	
}
	return true;
}
function createModalDialogHTML(title, body) {
		
		if (document.getElementById("modal-win")) {
			jQuery(document.getElementById("modal-win")).remove();
		} 
			
		var html = [
			'<div id="modal-win" title="', title, ':">',
				body,
			'</div>'
		].join("");
		
		jQuery("body").append(html);
		
		jQuery("#modal-win").dialog({
			modal: true,
			height: 250
		});
		
	}

function fixLanguageChange(){
	if(jQuery('.MenuLanguages').find('.fixed').size()==0){
		jQuery('.MenuLanguages').find('.hiddenLinks').addClass('fixed');
		jQuery('.MenuLanguages').find('.hiddenLinks > a').each(function(){
		var h=jQuery(this).attr('href');
		var d=h.substring(h.lastIndexOf("/"),h.indexOf("?"));
                h=h.replace(d,"");
                jQuery(this).attr('href',h);
		});
	}
}

function richiediDisp(){
	
	

	//Form di richiesta disponibilità
	if(document.getElementById(config.ROOM_N_ID_REQUEST)){
		ihPage.doMaxRoomSelect(config.ROOM_N_ID_REQUEST,config.TABLE_PAX_ID_REQUEST,new DettaglioPax(config.TABLE_PAX_ID_REQUEST));
	}
	
	jQuery('a.richiediDispo').click(function(e){
		jQuery.blockUI({
			message : jQuery('#richiestaDispo'),
			css: {
				top : '20px',
				width : '442px',
				left : '30%',
				background : '#e6e6e6'
				
			}
		});

		/*Form di richeista disponibilità*/
		jQuery('#richiestaDispo input[name="hotelCode"]').val(jQuery(this).attr('hotelcode'));
		jQuery('#richiestaDispo input[name="mailTo"]').val(jQuery(this).attr('hotelmail'));
		
		/* validazione e' fatta quando il form e' visibile */
		jQuery('.formRichiediDispo').validate({
			submitHandler : function(form){
				jQuery(form).ajaxSubmit({
					url:richdispoURL
				}),
				/*nascondi modale form e visualizza modale di conferma*/
				jQuery.unblockUI();
				jQuery.blockUI({
					message: '<h1>Grazie per averci contattato</h1>', 
		            timeout: 5000 
				});
			}	
		});
	});


		jQuery('.closeRichiestaDispo').click(function(e){
			jQuery.unblockUI();
		});

		jQuery('.simpleSearchButton').click(function(e){
			
		});
}