﻿/* Function: init - Executed on document.ready
 * Description: Initializes all the javascript elements in the search page.
 * This includes the calendar, cookies and room selector.
 *
 * The hotels search initialization supports configuration in order
 * to adapt it's behaviour to different templates.
 */
$(function () {
	// Configuration defaults
	var configuration = {
	  // URL to retrieve in order to get the autocompletion list for the location names.
		autocompleteURL: "keywords.asmx/GetCompletionList",
		// Use cookies to store and retrieve the previous search.
		useCookie: true,
		// Path to the image to use as calendar icon near the input box with the date.
		calendarIcon: "../img/calendar.gif"
	};
	
	/* Extend external configuration if available - Needs to be defined as: hotelsSearchEngineConfiguration */
	if (typeof(hotelsSearchEngineConfiguration) == "object") {
		$.extend(configuration, hotelsSearchEngineConfiguration);
	}
	
	/* Date format used in date <-> string conversions using the datepicker functions */
	var dateFormat = 'dd/mm/yy',
			/* data from the hotelsearchform cookie. This stores the date and place selections */
			cookieDataRaw = $.cookie("hotelsearchform"),
			/* Parsed cookie data */
			cookieData,
			/* Splitted cookie data */
			expandedCookie;
    
    /* Function: customRange
     * Description: Link the start and end date fields on both calendars.
     *   When you select a starting date. The ending date has to be bigger than it.
    */
    function customRange(input) {
        var minimum = 0;

        if (input.id == 'enddate') {
            minimum = $('#startdate').datepicker("getDate");
            minimum.setDate(minimum.getDate()+1);
        }
        return {
            minDate: minimum
        };
    }
     
     /* If we have a cookie with previous data, we recover it */
     
     if (configuration.useCookie && typeof(cookieDataRaw) == "string") {
        expandedCookie = cookieDataRaw.split("\t");
        cookieData = {
            place: expandedCookie[0],
            start: expandedCookie[1],
            end: expandedCookie[2]
        };
     }
        
    /* Configures the datepicker */    
    $.datepicker.setDefaults({ 
        dateFormat: dateFormat, 
        numberOfMonths: 2,
        mandatory: true,
        minDate:0,
        firstDay: 1, 
        changeFirstDay: false,
        showOn: "both",
        showAnim: "show",
        /* This will disable the animation and will make life easier for IE6 */
        duration: 0,
        buttonImage: configuration.calendarIcon,
        buttonImageOnly: true
    });      
    $("#enddate").datepicker({ 
        beforeShow: customRange,
        onSelect: function (datetext) {
            var newend = $.datepicker.parseDate(dateFormat,datetext);
        }

    });
    $("#startdate").datepicker({
        beforeShow: customRange,
        /* This will make the ending date as bigger as the starting date if the starting
        date changs */
        onSelect: function(datetext,datebox) {
            
            var newstart = $('#startdate').datepicker('getDate');
            var end = $('#enddate').datepicker('getDate');
            
            if (newstart >= end) {
                /* If you select a starting date bigger than the ending date, the ending date
                 * will be CHANGED to startdate + 3 days */
                newstart.setDate(newstart.getDate()+3);
                document.getElementById('enddate').value = $.datepicker.formatDate(dateFormat, newstart);
            }
        }
    });
    
    /* Start with today + 1 week, and end 3 days after */
    var today = new Date();
    var shouldstart = new Date();
    shouldstart.setDate(today.getDate() +7);
    
    /* Let's validate the stored dates from the cookies. 
     * previous date: this date was stored in the cookie and has been recovered.
     * proposed date: default initialization date.
     *
     * It can hapen that even if we have a date, this date is older than the default initial date.
     * In this case, even if we have a previous date, we choose the proposed date
     */
    function shouldIUseTheCookie(previous,proposed) {
        if(previous && $.datepicker.parseDate(dateFormat,previous) > proposed) return true;
        return false;
    }
    
    /* If we have previous data, we use it, if not, we get todays date */
    var usecookie = false;
    if (cookieData)
        usecookie = shouldIUseTheCookie(cookieData.start, today);
    
    document.getElementById('startdate').value = (usecookie) ? cookieData.start : $.datepicker.formatDate(dateFormat, shouldstart);
    shouldstart.setDate(shouldstart.getDate()+3);
    document.getElementById('enddate').value = (usecookie) ? cookieData.end : $.datepicker.formatDate(dateFormat, shouldstart);
    
    var selectAllText = function () {
        if (this.setSelectionRange)
            this.setSelectionRange(0,this.value.length);
        return false;
    };
    
    /* Generate the place box:
     * - With autocomplete
     * - Default value
     * - Select all when focus (useful to delete previous values) */
    $('#placename').autocompleteHotels(configuration.autocompleteURL, {
        scroll: false,
        matchSubset: false,
        matchCase: true
    }).
    /* Assign a default value */
    val( (cookieData)?cookieData.place:"" ).
    /* On focus select all text */
    focus(selectAllText);
    
    /* Creates the room selector */
    $('.roomselector').roomselector({
        rooms: 4,
        adults: 4,
        children: 4,
        age: 12
    });
    
  /* Store form information when unloading if we use cookies. */
	if(configuration.useCookie) {
    $(window).bind('unload', function () {
				/* Save place name, start date and end date */
        var result = document.getElementById('placename').value + "\t" +
            document.getElementById('startdate').value + "\t" +
            document.getElementById('enddate').value;
        $.cookie("hotelsearchform",result);
    });
	}
});
