﻿$(document).ready(function () {


   


        //****** First aquire latest stays via ajax call *************
        $.ajax({
        	url: 'stay/AjaxRetrieveRecentStaysList',
        	type: 'GET',
        	dataType: 'json',
        	success: function (data) {
        		$("#latest_stays_cnt").html(data.PartialViewHtml);
        		resolveTimers();

        		$("#latest_stays_cnt").click(function () {
        		    window.location = 'Stay/Search';
        		});
        	}
        });






        //APPLIES SELECTBOX STYLE
    (function ($) {

        $.fn.extend({

            customStyle: function (options) {
                if (!$.browser.msie || ($.browser.msie && $.browser.version > 6)) {

                    //For each selectbox
                    return this.each(function () {

                        //Get the selected value for this selectbox
                        var currentSelected = $(this).find(':selected');

                        //Place styled elements (exterior and interior )after this selectbox and then make it transparent
                        $(this).after('<div class="customStyleSelectBox"><div class="customStyleSelectBoxInner">' + currentSelected.text() + '</div></div>')
									.css({ position: 'absolute', opacity: 0, fontSize: $(this).next().css('font-size') });

                        //Get the exterior styled span element
                        var selectBoxSpan = $(this).next();

                        var selectBoxWidth = parseInt($(this).width()) - parseInt(selectBoxSpan.css('padding-left')) - parseInt(selectBoxSpan.css('padding-right'));

                        //Get the interior styled span element
                        var selectBoxSpanInner = selectBoxSpan.find(':first-child');

                        //Set both styled span elements to block elemnts
                        selectBoxSpan.css({ display: 'inline-block' });
                        selectBoxSpanInner.css({ width: selectBoxWidth, display: 'inline-block' });

                        var selectBoxHeight = parseInt(selectBoxSpan.height()) + parseInt(selectBoxSpan.css('padding-top')) + parseInt(selectBoxSpan.css('padding-bottom'));

                        //Set event handler for select action
                        $(this).height(selectBoxHeight).change(function () {
                            // selectBoxSpanInner.text($(this).val()).parent().addClass('changed');   This was not ideal
                            selectBoxSpanInner.text($(this).find(':selected').text()).parent().addClass('changed');
                            // Thanks to Juarez Filho & PaddyMurphy
                        });

                        $(this).mouseover(function () {
                            selectBoxSpan.css("background-color", "#F5FBFC");
                        });

                        $(this).mouseout(function () {
                            selectBoxSpan.css("background-color", "#ffffff");
                        });

                    });
                }
            }
        });
    })(jQuery);
    $('.selectbox').customStyle();


        //********************************************************* Date Picker Code ****************************************************
        var arriveDate = new Date();
        var $arrive = $(".date_cnt:eq(0) :input");
        var $depart = $(".date_cnt:eq(1) :input")

        $arrive.datepicker({
        	dateFormat: 'd M, y',
        	showOn: "button",
        	buttonImage: '../../Content/images/datepicker.png',
        	buttonImageOnly: true,
        	minDate: arriveDate,
        	showAnim: 'slideDown',
        	onSelect: function (selecteddate) {
        		//Get datepicker instance associated with arrival date textbox and convert date string to "Date" object
        		instance = $(this).data("datepicker");
        		arriveDate = $.datepicker.parseDate(instance.settings.dateFormat, selecteddate, instance.settings);

        		//Set the "min date" and "date" of the datepicker associated with the departure date textbox
        		departDate.setTime(arriveDate.getTime() + 1000 * 60 * 60 * 24);
        		$depart.datepicker("option", "minDate", departDate);
        		$depart.datepicker("setDate", departDate);

        		$("#period").text("1 Day");

        	}

        });
        $arrive.datepicker("setDate", arriveDate);


        var departDate = new Date();
        departDate.setTime(departDate.getTime() + 1000 * 60 * 60 * 24);
        $depart.datepicker({
        	dateFormat: 'd M, y',
        	showOn: "button",
        	buttonImage: '../../Content/images/datepicker.png',
        	buttonImageOnly: true,
        	minDate: departDate,
        	showAnim: 'slideDown',
        	onSelect: function (selecteddate) {
        		//Get datepicker instance associated with departure date textbox and convert date string to "Date" object
        		instance = $(this).data("datepicker");
        		departDate = $.datepicker.parseDate(instance.settings.dateFormat, selecteddate, instance.settings);

        		//Get difference between dates
        		if (departDate - arriveDate <= 86400000)
        		    $("#period").text(Math.ceil((departDate - arriveDate) / (1000 * 60 * 60 * 24)) + " Day");
        		else
        		    $("#period").text(Math.ceil((departDate - arriveDate) / (1000 * 60 * 60 * 24)) + " Days");
        	}
        });
        $depart.datepicker("setDate", departDate);


        $("#period").text("1 Day");
        //**************************************************************************************************************************************



        //******************* Timer Code ********************************

        function get_elapsed_time_string(total_seconds) {
        	function pretty_time_string(num) {
        		return (num < 10 ? "0" : "") + num;
        	}

        	var days = Math.floor(total_seconds / 86400);
        	total_seconds = total_seconds % 86400;

        	var hours = Math.floor(total_seconds / 3600);
        	total_seconds = total_seconds % 3600;

        	if (days > 0) {
        		// Pad the minutes and seconds with leading zeros, if required
        		days = days + "d";
        		hours = hours + "h";

        		// Compose the string for display
        		var currentTimeString = days + " " + hours;
        	}
        	else {
        		var minutes = Math.floor(total_seconds / 60);
        		total_seconds = total_seconds % 60;

        		var seconds = Math.floor(total_seconds);

        		// Pad the minutes and seconds with leading zeros, if required
        		hours = pretty_time_string(hours);
        		minutes = pretty_time_string(minutes);
        		seconds = pretty_time_string(seconds);

        		// Compose the string for display
        		var currentTimeString = hours + ":" + minutes + ":" + seconds;

        		if (hours == 0) {
        		    timerflag = 1;
        		}
        	}

        	return currentTimeString;
        }



        function resolveTimers() {

        	var timervalues = new Array(); //Stores the time value associated with each timer element
        	var timerelements = new Array();

        	//Get the times
        	$(".timer :input").each(function (index) {
        		timervalues.push(this.value);
        		timerelements.push($(this).parent());
        	});

        	var timerflag = 0; //Used to indicates if timer is less than 1 hour				

        	setInterval(function () {


        		for (var i = 0; i < timerelements.length; i++) {
        		    timerelements[i].attr("class");
        		    if (timervalues[i] == 0) {
        		        timerelements[i].css("color", "#A8A8A8");
        		    }
        		    else {
        		        timerelements[i].text(get_elapsed_time_string(--timervalues[i]))
        		        if (timerflag == 1) {
        		            timerelements[i].css("color", "#ED1C24");
        		        }
        		        timerflag = 0;
        		    }
        		}

        	}, 1000);
        }
        //**********************************************************************************



    });

		
		

    $(function () {
	    function log(message) {
		    //$("<div/>").text(message).prependTo("#log");
		    //$("#log").attr("scrollTop", 0);
		    //$("#Destination").text(message);
	    }
	    $("#destination").autocomplete({
		    source: function (request, response) {
			    $.ajax({
				    url: "http://ws.geonames.org/searchJSON",
				    dataType: "jsonp",
				    data: {
					    featureClass: "P",
					    style: "full",
					    maxRows: 12,
					    name_startsWith: request.term
				    },
				    success: function (data) {
					    response($.map(data.geonames, function (item) {
						    return {
							    label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
							    value: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
						    }
					    }));
				    }
			    });
		    },
		    minLength: 2,
		    select: function (event, ui) {
			    log(ui.item ?
				    "Selected: " + ui.item.label :
				    "Nothing selected, input was " + this.value);
		    },
		    open: function () {
			    $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
		    },
		    close: function () {
			    $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
		    }
	    });
    });
