var typeLocation = "mirai"; /*mirai o geonames*/

if (typeof(arrLocationLevel)== "undefined") var arrLocationLevel = new Array();

var objDateInfo;

var strButtonText = {	es:'Click para mostrar el calendario', 
						en:'Click to show calendar', 
						fr:'Cliquer pour voir le calendrier', 
						de:'', 
						ja:'クリックするとカレンダーが開きます。'};

var strNoLocationSelectedText = {	es:'Por favor seleccione un destino', 
									en:'Please select a destination', 
									fr:'Veuillez choisir une destination', 
									de:'Bitte, Wählen Sie ein Ziel', 
									ja:'目的地を選んでください'};

var strNoHotelNameWrittenText = {	es:'Por favor escriba algún nombre', 
									en:'Please write a hotel name', 
									fr:'Veuillez saisir un nom', 
									de:'Bitte schreiben Sie einen Namen', 
									ja:'ホテル名を入力してください。'};

var strPleaseWait = {	es: 'Por favor espere...',
						en: 'Please Wait...',
						fr: 'Merci de patienter...',
						de: 'bitte warten...',
						ja: 'お待ちください...'};

if (typeof typeLocation == "undefined") var typeLocation = "mirai";

var objDialog = new xdDialog();

// LIKE WINDOW.ONLOAD
$(document).ready(function() {

	objDateInfo = dateInfo[lang];
	
    typeLocation = (typeLocation == "mirai") ? 0 : 1;
	
	/* NIAPA PARA SOLUCIONAR EL DOBLE CLICK EN LA LIBRERIA SHADOWBOX */
	$(document).bind("click",function() { if ($("#shadowbox").css("visibility")=="visible") { $("#shadowbox").hide(); } });
	
    $("#hotelNamesTabForm").hide();
    $("#selectDestinationsLevel2").hide();
    $("#selectDestinationsLevel3").hide();
	$("#searchButtonDestinations").css("position","absolute");

	$('#shareTitle').cluetip({splitTitle: '|', showTitle: false, cluezIndex:101, topOffset:2, positionBy:"mouse"});

	$("INPUT[@name='level1']").val('');
    $("INPUT[@name='level2']").val('');
    $("INPUT[@name='level3']").val('');    
	
    $("#mainTab>li").each(function(){
        $(this).children("a").bind("click", toggleTo);
    });
    
    $("#destinationsTabForm").bind("submit", function(){
		searchDestinations();
		return false; 
	});
	$("#destinationsTabForm").bind("keyup",function(Event) {
		onKeyCode(Event,"13","searchDestinations");
	});
	
    $("#hotelNamesTabForm").bind("submit", function(){
		searchHotelNames(); 
		return false;
	});
    $("#available").bind("click", function(){ $("#availability").toggle(); });
	$("#available").trigger("click");
	$("#available").attr("checked","checked");
    
    $("#searchButtonDestinations").bind("click", searchDestinations);
    
    $("#searchButtonHotelNames").bind("click", searchHotelNames);
    
    $("#selectDestinationsLevel1").bind("change", changeDestinationLevel1);	
    
    var i=0;
	$("#selectDestinationsLevel1").html("");
    for (;i < level1Menu.length; i++) {
		if (i == 13) {
			$("#selectDestinationsLevel1").append("<option style='display:none;' value='" + level1Menu[i].valueCode + "'>" + level1Menu[i][lang] + "</option>");
		} else {
			$("#selectDestinationsLevel1").append("<option value='" + level1Menu[i].valueCode + "'>" + level1Menu[i][lang] + "</option>");
		}
    }
	try {
    	$("#selectDestinationsLevel1 option[@value='#|']").attr("selected", "selected");

	} catch(e) {
		/* NADA */
	}
	$("#selectDestinationsLevel1").css("width","auto");
    
	$("#inDate").bind("change",calculateNights);
	$("#inDate").bind("blur", function(){
		try { $(this).datepicker("hide"); } catch(e) { }
	});	
	$("#outDate").bind("change",calculateNights);
	$("#outDate").bind("blur", function(){
		try { $(this).datepicker("hide"); } catch(e) { }
	});	
	 
	setTimeout("checkIfLevelExists(1);",1000);
  
 	configCalendar();

	var dateToday = outputDateFormated(today);
	var dateTomorrow = outputDateFormated(tomorrow);
	
	$('#inDate').val(dateToday[lang]);
	$('#outDate').val(dateTomorrow[lang]);
	
	var Shadowbox_options = {};
	if (typeof Shadowbox != "undefined") Shadowbox.init(Shadowbox_options);
	
	$("OPTION[@value='----#----|']").attr("disabled","disabled");
	
	var htmlLoadingBlock =  '<div id="loading" style="display:none;">' +
    						'<div class="loading-indicator clearfix">' +
		      				'<img src="/xsl/survey/images/large-loading.gif" />' +
       						'<span id="loading-msg"> ' + strPleaseWait[lang] + ' </span>' + 
           					'</div></div>';
	$("body").append(htmlLoadingBlock);
	
});

var configCalendar = function() {
	$.datepicker.setDefaults({ 	showOn: 'both', 
								buttonImageOnly: true, 
								buttonImage: '/imagesv02/icoCalendar.gif',
								buttonText: strButtonText[lang],
								dateFormat: objDateInfo.dateFormat, 
								dayNamesMin: objDateInfo.dayNamesMin,
								firstDay: 1,
								maxDate: null, 
								monthNames: objDateInfo.monthNames, 
								nextText: objDateInfo.nextText,
								prevText: objDateInfo.prevText,
								clearText: objDateInfo.clearText,
								currentText: objDateInfo.currentText,
								closeText: objDateInfo.closeText,
								yearRange: today_year + ":" + (today_year + 1),
								mandatory: true
							});
	$('#inDate').datepicker({	defaultDate: +0,
								numberOfMonths: 1,
								minDate: today,
								maxDate: null
							});
	$('#outDate').datepicker({	defaultDate: +1, 
								numberOfMonths: 1, 
								beforeShow: customRange,
								minDate: tomorrow,
								maxDate: null
							});
}

var customRange = function() {
	return;
	var dateInValue = $('#inDate').val();
	var tmp = getDateSplitted(dateInValue);
	var dateIn = new Date(tmp[0],tmp[1]-1,tmp[2]);
	dateIn.setDate(dateIn.getDate()+1);
	return {minDate: dateIn };
}

var calculateNights = function() {
	var outBlock;
	if ($(this).attr("id") == "outDate") {
		outBlock = "inDate";
	} else {
		outBlock = "outDate";
	}
	var dateInValue = $('#inDate').val();
	var tmp = getDateSplitted(dateInValue);
	var inDate = new Date(tmp[0],tmp[1]-1,tmp[2]);
	var dateInValue = $('#outDate').val();
	var tmp = getDateSplitted(dateInValue);	
	var outDate = new Date(tmp[0],tmp[1]-1,tmp[2]);
	var days = (outDate - inDate) / (3600 * 24 * 1000);
	var nights = days_between(outDate,inDate);
	var newDate;
	
	$("#Nights").html(nights);
	if ( days < 1) {
		if (outBlock == "outDate") {
			outDate = inDate;
			outDate.setDate(outDate.getDate() + 1);
			newDate = outputDateFormated(outDate);
		} else {
			inDate = outDate;
			inDate.setDate(inDate.getDate() - 1);
			newDate = outputDateFormated(inDate);
		}
		$("#"+outBlock).val(newDate[lang]);
		$("#Nights").html("1");
		$("#nightsPlural").html("");
	} else if (nights > 1 && lang != "ja") {
		$("#nightsPlural").html("s");
	} else  {
		$("#nightsPlural").html("");
	}
}

var checkIfLevelExists = function(level) {
	if (typeof arrLocationLevel[level] != 'undefined') {
        var tmp;
        var tmp2;
        $($("#selectDestinationsLevel"+level).children()).each(function() {
            tmp = $(this).val().split("|");
            tmp2 = tmp[0].split("#");
            if (tmp2[typeLocation] == arrLocationLevel[level]) {
				try {
                	$(this).attr("selected", "selected");
				} catch(e) {  
					/* NADA */
				}
            }
        });
		$("#selectDestinationsLevel"+level).trigger("change");		
        $("INPUT[@name='level"+level+"']").val(arrLocationLevel[level]);
    }
	if (level < 3) {
		setTimeout(function() { checkIfLevelExists(level + 1) },200);
	}
}


var searchDestinations = function() {
    var level1 = $("INPUT[@name='level1']").val();
    var level2 = $("INPUT[@name='level2']").val();
    var level3 = $("INPUT[@name='level3']").val();
	var bLevel2Showed = ($("#selectDestinationsLevel2").css("display")!="none");
	var bLevel3Showed = ($("#selectDestinationsLevel3").css("display")!="none");
    if (	( level1 == "" || level1 == null ) || 
			( bLevel2Showed && (level2 == "" || level2 == null) ) ||
			( bLevel3Showed && (level3 == "" || level3 == null) ) 
	   ) {
        alert(strNoLocationSelectedText[lang]);
    }
    else {
		objDialog.wait();
		var indate = $("#inDate").val();
		var indateSplitted = getDateSplitted(indate);
		var inDate = new Date(indateSplitted[0],indateSplitted[1]-1,indateSplitted[2]);
		var outdate = $("#outDate").val();
		var outdateSplitted = getDateSplitted(outdate);
		var outDate = new Date(outdateSplitted[0],outdateSplitted[1]-1,outdateSplitted[2]);

		var tmpDate = new Date(indateSplitted[0],indateSplitted[1]-1,indateSplitted[2]);
		var nights = $("#Nights").html();
        if ($("#available").attr("checked")) {
			var pax = $('#pax').attr("value");
            document.location.href = "/search/search.php?typesearch=availability&level1=" + level1 + "&level2=" + level2 + "&level3=" + level3 + "&language=" + objLang[lang] + "&fivestars=true&fourstars=true&threestars=true&inyear=" + indateSplitted[0] + "&inmonth=" + (indateSplitted[1]-1) + "&inday=" + indateSplitted[2] + "&outyear=" + outdateSplitted[0] + "&outmonth=" + (outdateSplitted[1]-1) + "&outday=" + outdateSplitted[2] + "&nights=" + nights + "&pax=" + pax;
        }
        else {
            document.location.href = "/search/search.php?typesearch=normal&level1=" + level1 + "&level2=" + level2 + "&level3=" + level3 + "&language=" + objLang[lang] + "&from=destination";
        }
    }
    return false;
}


var searchHotelNames = function() {
    var hotelValue = $("INPUT[@name='hotelName']").val();
    if (hotelValue == "" || hotelValue == null) {
		alert(strNoHotelNameWrittenText[lang]);
    }
    else {
		objDialog.wait();
        var url = "/search/search.php";
		var params = {
			language: objLang[lang],
			typesearch: 'normal',
			from: 'hotelname',
			strsearch: hotelValue,
			autocomplete_xwd: 'false'
		};
		if (typeof(arrLocationLevel[1]) != "undefined") params.level1 = arrLocationLevel[1];
		if (typeof(arrLocationLevel[2]) != "undefined") params.level1 = arrLocationLevel[2];
		if (typeof(arrLocationLevel[3]) != "undefined") params.level1 = arrLocationLevel[3];
		if (typeof(hotelnamesearchCodes) != "undefined") params.level1 = hotelnamesearchCodes;
		window.location=url+"?"+paramsToQueryString(params);
    }
    return false;
}

var paramsToQueryString = function(params) {
	var arrQueryString = new Array();
	for(param in params) {
		arrQueryString.push(param + "=" + params[param]);
	}
	return arrQueryString.join("&");
}

var changeDestinationLevel1 = function() {
    var codeValue = $(this).attr("value");
    
    if (codeValue == "" || codeValue == null) {
        setLevel(1, '');
        return;
    }
    
    var arrCodesLocationOrNextLevel = codeValue.split("|");
    var codesLocation = arrCodesLocationOrNextLevel[0];
    var nextLevel = arrCodesLocationOrNextLevel[1];
    if (codesLocation != "") {
        var arrCodesLocation = codesLocation.split("#");
        setLevel(1, arrCodesLocation[typeLocation]);
    }
    if (nextLevel != "") {
        var arrLevel2 = eval(nextLevel);
        $("#selectDestinationsLevel2").html("");
        for (i = 0; i < arrLevel2.length; i++) {
            $("#selectDestinationsLevel2").append("<option value='" + arrLevel2[i].valueCode + "'>" + arrLevel2[i][lang] + "</option>");
        }
        try {
            $($('#selectDestinationsLevel2').children()[0]).attr("selected", "selected");
        } 
        catch (e) {
			/* NADA */
        }
        $("#selectDestinationsLevel2").show();
        $("#selectDestinationsLevel3").hide();
        $("#selectDestinationsLevel2").bind("change", changeDestinationLevel2);
		$("#selectDestinationsLevel2").trigger("change");		
    }
	$("OPTION[@value='----#----|']").attr("disabled","disabled");
}

var setLevel = function(level, level1Value){
    var i = level + 1;
    for (; i <= 3; i++) {
        $("#selectDestinationsLevel" + i).hide();
        $("INPUT[@name='level" + i + "']").val('');
    }
    $("INPUT[@name='level" + level + "']").val(level1Value);
}


var changeDestinationLevel2 = function() {
    var codeValue = $(this).attr("value");
    
    if (codeValue == "" || codeValue == null) {
        setLevel(2, '');
        return;
    }
    
    var tmp = codeValue.split("|");
    if (tmp[0] != "") {
        var tmp2 = tmp[0].split("#");
        setLevel(2, tmp2[typeLocation]);
    }
    if (tmp[1] != "") {
        var arrLevel3 = eval(tmp[1]);
        $("#selectDestinationsLevel3").html("");
        for (i = 0; i < arrLevel3.length; i++) {
            $("#selectDestinationsLevel3").append("<option value='" + arrLevel3[i].valueCode + "'>" + arrLevel3[i][lang] + "</option>");
        }
        try {
            $($('#selectDestinationsLevel3').children()[0]).attr("selected", "selected");
        } 
        catch (e) {
			/* NADA */
        }
        $("#selectDestinationsLevel3").show();
        $("#selectDestinationsLevel3").bind("change", changeDestinationLevel3);
		$("#selectDestinationsLevel3").trigger("change");
    }
    $("OPTION[@value='----#----|']").attr("disabled","disabled");
}

var changeDestinationLevel3 = function() {
    var codeValue = $(this).attr("value");
    
    if (codeValue == "" || codeValue == null) {
        $("#selectDestinationsLevel3").hide();
        $("INPUT[@name='level3']").val('');
        return;
    }
    var tmp = codeValue.split("|");
    var tmp2 = tmp[0].split("#");
    $("INPUT[@name='level3']").val(tmp2[typeLocation]);
	$("OPTION[@value='----#----|']").attr("disabled","disabled");
}


var toggleTo = function() {
    var oldSelectedTab = $("#mainTab>li.selected");
    oldSelectedTab.removeClass("selected");
    oldSelectedTab.addClass("notSelected");
    var clickedTab = $(this).parent();
    clickedTab.removeClass("notSelected").addClass("selected").unbind("click", toggleTo);
    $("#mainTab>li.notSelected").each(function(){ $(this).children("a").bind("click", toggleTo); });
    $("#" + oldSelectedTab.attr("id") + "Form").toggle();
    $("#" + clickedTab.attr("id") + "Form").toggle();
	if (clickedTab.attr("id")=="hotelNamesTab") 
		$("#hotelName").focus();
	else 
		$("#selectDestinationsLevel1").focus();
}

var getDateSplitted = function(strDate) {
	var ret = new Array();
	var separator = ( lang == 'ja' ) ?/[年月日]/ :"/";
	var tmp = strDate.split(separator);
	return new Array(tmp[objDateInfo.yearPos], tmp[objDateInfo.monthPos], tmp[objDateInfo.dayPos]);
}

