﻿/* jhover minified */
(function ($) { $.fn.jHover = function (f, g) { var cfg = { sensitivity: 7, interval: 100, timeout: 0 }; cfg = $.extend(cfg, g ? { over: f, out: g} : f); var cX, cY, pX, pY; var track = function (ev) { cX = ev.pageX; cY = ev.pageY; }; var compare = function (ev, ob) { ob.jHover_t = clearTimeout(ob.jHover_t); if ((Math.abs(pX - cX) + Math.abs(pY - cY)) < cfg.sensitivity) { $(ob).unbind("mousemove", track); ob.jHover_s = 1; return cfg.over.apply(ob, [ev]); } else { pX = cX; pY = cY; ob.jHover_t = setTimeout(function () { compare(ev, ob); }, cfg.interval); } }; var delay = function (ev, ob) { ob.jHover_t = clearTimeout(ob.jHover_t); ob.jHover_s = 0; return cfg.out.apply(ob, [ev]); }; var handleHover = function (e) { var p = (e.type == "mouseover" ? e.fromElement : e.toElement) || e.relatedTarget; while (p && p != this) { try { p = p.parentNode; } catch (e) { p = this; } } if (p == this) { return false; } var ev = jQuery.extend({}, e); var ob = this; if (ob.jHover_t) { ob.jHover_t = clearTimeout(ob.jHover_t); } if (e.type == "mouseover") { pX = ev.pageX; pY = ev.pageY; $(ob).bind("mousemove", track); if (ob.jHover_s != 1) { ob.jHover_t = setTimeout(function () { compare(ev, ob); }, cfg.interval); } } else { $(ob).unbind("mousemove", track); if (ob.jHover_s == 1) { ob.jHover_t = setTimeout(function () { delay(ev, ob); }, cfg.timeout); } } }; return this.mouseover(handleHover).mouseout(handleHover); }; })(jQuery);

/* List Ticker */
(function ($) {
    $.fn.list_ticker = function (options) {

        var defaults = {
            speed: 4000,
            effect: 'slide'
        };

        var options = $.extend(defaults, options);

        return this.each(function () {

            var obj = $(this);
            var list = obj.children();
            list.not(':first').hide();

            setInterval(function () {

                list = obj.children();
                list.not(':first').hide();

                var first_li = list.eq(0)
                var second_li = list.eq(1)

                if (options.effect == 'slide') {
                    first_li.slideUp();
                    second_li.slideDown(function () {
                        first_li.remove().appendTo(obj);
                    });
                } else if (options.effect == 'fade') {
                    first_li.fadeOut(function () {
                        second_li.fadeIn();
                        first_li.remove().appendTo(obj);
                    });
                }
            }, options.speed)
        });
    };
})(jQuery);

var Year = new Date().getFullYear();
var Month = new Date().getMonth() + 1;
var Months = 2;
var WeekdayChars = 1;

$(document).ready(function () {
    try {
        $(".selectBox").selectBox();
        $(".selectBox").selectBox('settings', { 'menuTransition': 'slide', 'menuSpeed': 'fast' });
    }
    catch (err) {
        alert("Unable to create SelectBoxes");
    }

    try {
        $("#partners a").tooltip();
        $("#likebar a.showtool").tooltip();
        $("#followus a").tooltip();
        $(".locationselect").tooltip({ position: "center right", tipClass: "tooltipRight" });
        $(".keywordselect").tooltip({ position: "center right", tipClass: "tooltipRight" });
    }
    catch (err) {
        alert("Unable to create ToolTips");
    }

    try {
        $("#copyright").html("Copyright " + new Date().getFullYear() + " Nox Rentals");
    }
    catch (err) {
        //alert("Unable to create Copyright");
    }

    try {
        SetupDatePickers(".arrivaldate", ".departuredate");
        SetupDatePickers(".enquiryarrivaldate", ".enquirydeparturedate");
    }
    catch (err) {
        alert("Unable to setup Date Pickers");
    }

    try {
        // menu level 2
        $('div#topmenu ul.ML1 li.ML1').jHover(
        function () { $(this).children('ul').slideDown('fast'); },
        function () { $(this).children('ul').slideUp('fast'); }
    );
        // menu level 3
        $('div#topmenu ul.ML1 li.ML1 ul.ML2 li.ML2').jHover(
        function () { $(this).children('ul').slideDown('fast'); },
        function () { $(this).children('ul').slideUp('fast'); }
    );
    }
    catch (err) {
        alert("Unable to setup menu dropdowns");
    }

    try {
        $('.splashimages').cycle({ fx: 'fade', speed: 2000 });
    }
    catch (err) {
        alert("Unable to setup Image rotation");
    }

    try {
        $("#enquirenow").modalpop({ speed: 700 });
        $(".popuphomeenquiry").modalpop({ speed: 700 });
        $("#loadingbutton").modalpop({ speed: 500 });
    }
    catch (err) {
        alert("Unable to setup popups");
    }
});

function InitScrollable() {
    $(".scrollable").scrollable();

    $(".items img").mouseover(function () {
        $(this).trigger("click")
    });

    $(".items img").click(function () {

        // see if same thumb is being clicked
        if ($(this).hasClass("active")) { return; }

        // calclulate large image's URL based on the thumbnail URL
        var url = $(this).attr("rel");

        // get handle to element that wraps the image and make it semi-transparent
        var wrap = $("#image_wrap").fadeTo("fast", 1);

        // the large image from www.flickr.com
        var img = new Image();

        // call this function after it's loaded
        img.onload = function () {

            // make wrapper fully visible
            wrap.fadeTo("fast", 1);

            // change the image
            wrap.find("img").attr("src", url);

            // if it's higher than the container's css height
            if (img.height > 480) {
                $("#image_wrap img").css("margin-top", (480 - img.height) / 2);
            } else {
                $("#image_wrap img").removeAttr("style");
            }

        };

        // begin loading the image from www.flickr.com
        img.src = url;

        // activate item
        $(".items img").removeClass("active");
        $(this).addClass("active");

        // when page loads simulate a "click" on the first image
    }).filter(":first").click();
}

function LoadCalendar(PropertyID, TargetID, ProxyURL) {
    $.ajax({
        type: "GET",
        url: ProxyURL + "?ID=" + PropertyID + "&Year=" + Year.toString() + "&Month=" + Month.toString() + "&Months=" + Months.toString(),
        dataType: "xml",
        success: function (xmlDoc) {

            var Results = $("#" + TargetID);
            Results.html("");
            var MonthCounter = 0;

            while (MonthCounter < Months) {
                MonthCounter++;
                var WeekdayCounter = 0;
                var ExceedsMonth = true;
                var m = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
                var htmlInsert = "";
                var htmlRow = "";
                var MondayIsInMonth = false;
                var SundayIsInMonth = false;
                var FirstDayOfTargetMonth = new Date("1 " + m[Month - 1] + " " + Year);
                FirstDayOfTargetMonth = new Date(new Date(FirstDayOfTargetMonth).setMonth(FirstDayOfTargetMonth.getMonth() + (MonthCounter - 1)));

                $(xmlDoc).find("col").each(function () {
                    if (!ExceedsMonth) return;

                    WeekdayCounter++;

                    var xmlDate = $(this);
                    var calDate = xmlDate.find("date").text();
                    var calDay = xmlDate.find("day").text();
                    var calMonth = xmlDate.find("month").text();
                    var calYear = xmlDate.find("year").text();
                    var calState = xmlDate.find("state").text();
                    var thisDate = new Date(calDay + " " + m[calMonth - 1] + " " + calYear);
                    var OtherMonth = ""
                    var Weekend = ""

                    if (WeekdayCounter % 7 == 1) MondayIsInMonth = (thisDate.getMonth() == FirstDayOfTargetMonth.getMonth());
                    if (WeekdayCounter % 7 == 0) SundayIsInMonth = (thisDate.getMonth() == FirstDayOfTargetMonth.getMonth());

                    if (WeekdayCounter % 7 == 1) htmlRow = "<tr>";
                    if (WeekdayCounter % 7 == 6 || WeekdayCounter % 7 == 0) Weekend += " Weekend";
                    if (thisDate.getMonth() != FirstDayOfTargetMonth.getMonth()) OtherMonth = " OtherMonth";
                    htmlRow += "<td class=\"" + calState + OtherMonth + Weekend + "\">" + calDay + "</td>";
                    if (WeekdayCounter % 7 == 0) htmlRow += "</tr>";

                    //if(thisDate.getDay() == 0 && thisDate.getMonth() != (Month - 1)) htmlRow = "";
                    //if(thisDate.getDay() == 0 && thisDate.getMonth() != (Month - 1)) ExceedsMonth = false;
                    if (WeekdayCounter % 7 == 0 && (MondayIsInMonth || SundayIsInMonth)) htmlInsert += htmlRow;
                });

                htmlInsert = "<table cellpadding=\"0\" cellspacing=\"0\" class=\"Availability\"><thead><tr><th colspan=\"7\" class=\"MonthName\">" + m[FirstDayOfTargetMonth.getMonth()] + " " + FirstDayOfTargetMonth.getFullYear().toString() + "</th></tr>"
                                + "<tr><th>" + "Monday".substring(0, WeekdayChars) + "</th><th>" + "Tuesday".substring(0, WeekdayChars) + "</th><th>" + "Wednesday".substring(0, WeekdayChars) + "</th><th>" + "Thursday".substring(0, WeekdayChars) + "</th><th>" + "Friday".substring(0, WeekdayChars) + "</th><th class=\"Weekend\">" + "Saturday".substring(0, WeekdayChars) + "</th><th class=\"Weekend\">" + "Sunday".substring(0, WeekdayChars) + "</th></tr></thead><tbody>"
                                + htmlInsert
                                + "</tbody></table>";
                Results.append(htmlInsert);
            }
        }
    });
}

// load an xml doc (for availability)
function loadXMLDoc(docName) {
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    }
    else {
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.open("GET", docName, false);
    xhttp.send("");
    return xhttp.responseXML;
}

String.prototype.padLeft = function (n, pad) {
    t = '';
    if (n > this.length) {
        for (i = 0; i < n - this.length; i++) {
            t += pad;
        }
    }
    return t + this;
}
String.prototype.padRight = function (n, pad) {
    t = this;
    if (n > this.length) {
        for (i = 0; i < n - this.length; i++) {
            t += pad;
        }
    }
    return t;
}
Date.prototype.getMonthName = function () {
    d = this;
    switch (d.getMonth()) {
        case 0: return "January"; break;
        case 1: return "February"; break;
        case 2: return "March"; break;
        case 3: return "April"; break;
        case 4: return "May"; break;
        case 5: return "June"; break;
        case 6: return "July"; break;
        case 7: return "August"; break;
        case 8: return "September"; break;
        case 9: return "October"; break;
        case 10: return "November"; break;
        case 11: return "December"; break;
        default:
            return ""; break;
    }
}

// google map load
function mapLoad(mapTarget, latitude, longitude, width, height, IsLocal) {
    if (IsLocal == false) {
        if (GBrowserIsCompatible()) {
            var mapOptions = { size: new GSize(width, height) };
            var map = new GMap2(document.getElementById(mapTarget), mapOptions);
            map.addControl(new GLargeMapControl3D());
            map.addControl(new GMapTypeControl());
            var marker = new GMarker(new GLatLng(latitude, longitude));
            map.addOverlay(marker);
            var givenmaptypes = map.getMapTypes();
            map.setMapType(givenmaptypes[2]);
            map.setCenter(new GLatLng(latitude, longitude), 15);
        }
    }
}

/* setup datepickers for search */
function SetupDatePickers(ArrivalID, DepartureID) {
    // Arrival datepicker setup
    $(ArrivalID).datepicker({
        dateFormat: 'dd M yy', minDate: 0, maxDate: "+12M", changeMonth: true, changeYear: true, showOtherMonths: true, selectOtherMonths: true, firstDay: 1,
        onSelect: function (dateText, inst) {
            // if there is a valid arrival date
            if ($(ArrivalID).datepicker("getDate")) {
                // get the arrival date
                var dtArrival = new Date($(ArrivalID).datepicker("getDate").toDateString());
                //dtArrival.setDate($(ArrivalID).datepicker("getDate").toDateString());
                // set min. departure date
                var dtMinDeparture = new Date($(ArrivalID).datepicker("getDate").toDateString());
                dtMinDeparture.setDate(dtMinDeparture.getDate() + 1);
                // if there's already a departure
                if ($(DepartureID).datepicker("getDate")) {
                    // get the departure date
                    var dtDeparture = new Date($(DepartureID).datepicker("getDate").toDateString());
                    // if departure is now invalid
                    if (dtDeparture <= dtArrival) {
                        // blank out the departure date
                        $(DepartureID).datepicker("setDate", null);
                    }
                }
                $(DepartureID).datepicker("option", "minDate", new Date(dtMinDeparture.toDateString()));
            }
        }
    });
    // Departure datepicker setup
    $(DepartureID).datepicker({ dateFormat: 'dd M yy', minDate: 0, maxDate: "+12M", changeMonth: true, changeYear: true, showOtherMonths: true, selectOtherMonths: true, firstDay: 1 });
}

function ShowLoading() {
    
    if ($(".arrivaldate").val() != 'Arrival Date' && $(".departuredate").val() != 'Departure Date') {
        $('#loadingbutton').trigger('click');
    }
    return false;
}

/* popup */
(function () {

    jQuery.fn.modalpop = function (options) {

        var defaults = {
            speed: 500,
            center: false
        };

        var options = $.extend(defaults, options);
        var width = $(window).width();
        //Get the full page height including the scroll area
        var height = $(document).height();
        jQuery('body').prepend("<div id='popupmask'></div>");
        jQuery('#popupmask').css('height', height);
        jQuery('#popupmask').css('width', width);

        return this.each(function () {

            jQuery(this).click(function () {
                $this = jQuery(this);
                var id = $this.attr('href');
                //Get the window height and width
                var winH = height;
                var winW = width;

                //Set the popup window to center if required
                if (defaults.center == true) {
                    $(id).css('top', winH / 2 - $(id).height() / 2);
                } else {
                    $(id).css('top', ($(window).scrollTop() + 40) + "px");
                }
                $(id).css('left', winW / 2 - $(id).width() / 2);
                jQuery('#popupmask').fadeIn(defaults.speed);
                jQuery(id).fadeIn(defaults.speed);
                return false;
            });

            jQuery('#popupmask').click(function () {
                jQuery('#popupmask').fadeOut(defaults.speed);
                jQuery('.popupwindow').fadeOut(defaults.speed);
                return false;
            });

            jQuery('.popupclose').click(function () {
                jQuery('#popupmask').fadeOut(defaults.speed);
                jQuery('.popupwindow').fadeOut(defaults.speed);
                return false;
            });

        });
    };

})(jQuery);

function GetQuoteFromXML(PropertyID, FromDateID, ToDateID, ProxyURL, QuoteID, DepositID) {
    // from date
    if (!isValidDate($(FromDateID).val(), "DD MMM YYYY")) {
        $(QuoteID).html("Enter your dates");
        return;
    }
    else {
        var FromDate = new Date($(FromDateID).val());
    }

    // to date
    if (!isValidDate($(ToDateID).val(), "DD MMM YYYY")) {
        $(QuoteID).html("Enter your dates");
        return;
    }
    else {
        var ToDate = new Date($(ToDateID).val());
    }

    if (FromDate >= ToDate) {
        $(QuoteID).html("Invalid Dates");
        return;
    }

    // get xml
    if (PropertyID != 0 && PropertyID != null) {
        $.ajax({
            type: "GET",
            url: ProxyURL + "?ID=" + PropertyID + "&From=" + (new Date(FromDate)).formatDate("dd-MM-yyyy") + "&To=" + (new Date(ToDate)).formatDate("dd-MM-yyyy"),
            dataType: "xml",
            success: function (xmlDoc) {
                if ($(xmlDoc).find("message").text().indexOf("The property is not available for these dates") >= 0) {
                    $(QuoteID).html("Sorry: not available");
                }
                else {
                    $(QuoteID).html($(xmlDoc).find("currency").text() + " " + $(xmlDoc).find("quote").find("quote").text());
                    //$(DepositID).html($(xmlDoc).find("currency").text() + " " + $(xmlDoc).find("deposit").text());
                }
            },
            failure: function () {
                $(QuoteID).html("Offline; please try later");
            }
        });
    }
}

function isValidDate(datestring, format) {
    if (format == "DD MMM YYYY") {

        var re = new RegExp("^[0-9][0-9] [A-Za-z][A-Za-z][A-Za-z] [0-9][0-9][0-9][0-9]$");
        if (!datestring.match(re)) {
            return false;
        }
        else {
            var dteDate;
            var day = datestring.substring(0, 2);
            var monthname = datestring.substring(3, 6);
            var month;
            switch (monthname) {
                case "Jan": month = 1; break;
                case "Feb": month = 2; break;
                case "Mar": month = 3; break;
                case "Apr": month = 4; break;
                case "May": month = 5; break;
                case "Jun": month = 6; break;
                case "Jul": month = 7; break;
                case "Aug": month = 8; break;
                case "Sep": month = 9; break;
                case "Oct": month = 10; break;
                case "Nov": month = 11; break;
                case "Dec": month = 12; break;
                default: month = -1;
            }
            var year = datestring.substring(7, 11);

            dteDate = new Date(year, month - 1, day);

            return ((day == dteDate.getDate()) && (month == dteDate.getMonth() + 1) && (year == dteDate.getFullYear()));
        }
    }
    else {
        alert("Invalid format passed to isValidDate function");
        return false;
    }
}

function SummarizeDescription() {
    var fullDescription = $("#DescriptionContainer").html();
    if (fullDescription.length > 1200) {
        var pos = 0;
        var minPos = 1000;
        if (fullDescription.substring(minPos, fullDescription.length).indexOf("</p>") > 0)
            pos = 1000 + fullDescription.substring(minPos, fullDescription.length).indexOf("</p>") + 4;
        else if (fullDescription.substring(minPos, fullDescription.length).indexOf("<br>") > 0)
            pos = 1000 + fullDescription.substring(minPos, fullDescription.length).indexOf("<br>") + 4;
        else if (fullDescription.substring(minPos, fullDescription.length).indexOf("<br/>") > 0)
            pos = 1000 + fullDescription.substring(minPos, fullDescription.length).indexOf("<br/>") + 5;
        else if (fullDescription.substring(minPos, fullDescription.length).indexOf("<br />") > 0)
            pos = 1000 + fullDescription.substring(minPos, fullDescription.length).indexOf("<br />") + 6;
        if (pos > 0) {
            fullDescription = fullDescription.substring(0, pos) + " <a id=\"readmore\" href=\"#\">Read more...</a><span id=\"readmorehidden\">" + fullDescription.substring(pos, fullDescription.length) + "</span>";
            $("#DescriptionContainer").html(fullDescription);
            $("#readmorehidden").hide(1);
            $("#readmore").click(function () { $("#readmore").hide(); $("#readmorehidden").slideDown(900); return false; });
        }
    }
}

Date.prototype.formatDate = function (format) {
    var date = this;
    if (!format)
        format = "MM/dd/yyyy";

    var month = date.getMonth() + 1;
    var year = date.getFullYear();

    format = format.replace("MM", month.toString().padL(2, "0"));

    if (format.indexOf("yyyy") > -1)
        format = format.replace("yyyy", year.toString());
    else if (format.indexOf("yy") > -1)
        format = format.replace("yy", year.toString().substr(2, 2));

    format = format.replace("dd", date.getDate().toString().padL(2, "0"));

    var hours = date.getHours();
    if (format.indexOf("t") > -1) {
        if (hours > 11)
            format = format.replace("t", "pm")
        else
            format = format.replace("t", "am")
    }
    if (format.indexOf("HH") > -1)
        format = format.replace("HH", hours.toString().padL(2, "0"));
    if (format.indexOf("hh") > -1) {
        if (hours > 12) hours - 12;
        if (hours == 0) hours = 12;
        format = format.replace("hh", hours.toString().padL(2, "0"));
    }
    if (format.indexOf("mm") > -1)
        format = format.replace("mm", date.getMinutes().toString().padL(2, "0"));
    if (format.indexOf("ss") > -1)
        format = format.replace("ss", date.getSeconds().toString().padL(2, "0"));
    return format;
}
String.repeat = function (chr, count) {
    var str = "";
    for (var x = 0; x < count; x++) { str += chr };
    return str;
}
String.prototype.padL = function (width, pad) {
    if (!width || width < 1)
        return this;

    if (!pad) pad = " ";
    var length = width - this.length
    if (length < 1) return this.substr(0, width);

    return (String.repeat(pad, length) + this).substr(0, width);
}
String.prototype.padR = function (width, pad) {
    if (!width || width < 1)
        return this;

    if (!pad) pad = " ";
    var length = width - this.length
    if (length < 1) this.substr(0, width);

    return (this + String.repeat(pad, length)).substr(0, width);
} 

