﻿// Hotel form for multiple forms in hotel detail
var Hresform = {
    maxRooms: 8,
    hotelresurl: "",
    isAjax: false,  // 10/14/2009, isAjax allows overriding search method to use ajax or not
    isInHouse: true,    // 10/14/2009, isInHouse allows overrding search method to use travelnow or our own result    

    init: function(notsetval, checkajax, customQS) {
        Hresform.childChanged(0, 1);
        if (!notsetval) Hresform.setValues(customQS);
        if ($("table[name=hresform]:eq(0) input[type=text]:eq(0)").val() == "") {
            Hresform.setDefaultCheckin();
        }

        // 10/14/2009, querystring overriding of isAjax and isInHouse
        if (window.location.search.toLowerCase().indexOf("hotelmethod=ajax") >= 0) {
            Hresform.isAjax = true;
            Hresform.isInHouse = true;
        } else if (window.location.search.toLowerCase().indexOf("hotelmethod=tn") >= 0) {
            Hresform.isAjax = false;
            Hresform.isInHouse = false;
        } else if (window.location.search.toLowerCase().indexOf("hotelmethod=nonajax") >= 0) {
            Hresform.isAjax = false;
            Hresform.isInHouse = true;
        }

        // check ajax
        if (checkajax) Hresform.resultsAjaxSupport();
    },

    resultsAjaxSupport: function() {
        // used in search results
        var useajax;
        var regexBrowser = new RegExp("version/2", "i");

        // 10/14/2009, overriding useajax 
        if (Hresform.isAjax) {
            // Browser detection, if Safari 2.0 or Chrome, non-ajax search instead 
            if (navigator.userAgent.toLowerCase().indexOf("safari") >= 0 && (navigator.userAgent.toString().match(regexBrowser))) {
                useajax = false;
            } else {
                useajax = Ajax.isSupported();
            }
        } else {
            useajax = false;
        }

        if (!useajax) {
            $(".hsFilters input[id$=btncheckrate]").click(function() { return Hresform.refineSearch(); });
            $(".hsFilters select[id$=bookCurrency]").change(function() {
                return Hresform.currencyChanged();
            });
            // $("#hsFilters").show();
        } else {
            if (location.search.match(/(?:bookareas|otherloc)/i)) { // outside
                $(".hsFilters input[id$=btncheckrate]").click(function() { return Hresform.checkrateOAJAX(); });
            } else {
                $(".hsFilters input[id$=btncheckrate]").click(function() { return Hresform.checkrateAJAX(); });
            }
            $(".hsFilters select[id$=bookCurrency]").change(function() {
                return Hresform.currencyChanged(true);
            });
            // $("#hsFilters").hide();
        }
    },

    sortChanged: function() {
        // used in search results
        // get the new sortmethod
        var val = $("#sortmethod").val();

        if (!val) return false;

        var url;
        if (location.href.indexOf("sort=") > -1)
            url = location.href.replace(/sort=[^&]*/, "sort=" + val);
        else
            url = location.href.replace("?", "?sort=" + val + "&");

        var dir = "asc";

        switch (val) {
            case "1": case "rate": case "distance": break;
            case "editor": case "user": dir = "desc"; break;
        }

        if (url.indexOf("dir=") > -1)
            url = url.replace(/dir=[^&]*/, "dir=" + dir);
        else
            url = url.replace("?", "?dir=" + dir + "&");

        // when sort, remove the currentcachekey
        url = url.replace(/&(?:currentcachekey|currentcachelocation)=[^&]*/ig, '');

        LoadingMask.show();

        location.href = url;
    },

    currencyChanged: function(nolocalredir) {
        // used in search results
        var idpf = "#" + $(".hsFilters select")[0].id.substring(0, $(".hsFilters select")[0].id.lastIndexOf("_") + 1);
        // get the new currency
        val = $(idpf + "bookCurrency").val();
        if (val) {
            if (val.length > 3) {
                // have to redirect to travelnow				
                url = "http://hotel.nyc.com/index.jsp?pageName=hotSearch&cid=4092&city=New+York&stateProvince=NY&country=US&validateCity=true&submitted=true&specials=false&showHotels=true&isHotels=true&showCondos=true&isCondos=false&netOnly=false&s=4&n=Hotel&sn=Specials&s=4&n=Booking&sn=";
                window.location = url + "&locale=" +
					val.split("-")[0] +
					"&currencyCode=" +
					val.split("-")[1];
            } else {
                if (!nolocalredir) {
                    // just change the currency
                    if (location.href.indexOf("currency=") > -1) {
                        location.href = location.href.replace(/currency=[^&]*/, "currency=" + val);
                    } else {
                        location.href = location.href.replace("?", "?currency=" + val + "&");
                    }
                }
            }
        }
    },

    getSearchOptions: function() {
        // used in search results
        var idpf = "#" + $(".hsFilters select")[0].id.substring(0, $(".hsFilters select")[0].id.lastIndexOf("_") + 1)
        var val, qs = "";

        val = $("#sortmethod").val();
        switch (val) {
            case "1": qs += "&sort=default&dir=asc"; break;
            case "editor": qs += "&sort=editor&dir=desc"; break;
            case "user": qs += "&sort=user&dir=desc"; break;
            case "rate": qs += "&sort=rate&dir=asc"; break;
            case "distance": qs += "&sort=distance&dir=asc"; break;
        }

        val = $(idpf + "hotelname").val();
        if (val) qs += "&name=" + escape(val);

        val = $(idpf + "bookAreas").val();
        if (val) qs += "&area=" + val;

        val = $(idpf + "star").val();
        if (val) qs += "&star=" + val;

        val = $(idpf + "bookBrands").val();
        if (val) qs += "&bookbrands=" + val;

        val = $(idpf + "bookFeature").val();
        if (val) qs += "&bookfeature=" + val;

        val = $(idpf + "bookCurrency").val();
        if (val) qs += "&currency=" + val;

        return qs;
    },

    checkrateOAJAX: function() {
        // used in ppc outside
        var idpf = "#" + $(".hsFilters select")[0].id.substring(0, $(".hsFilters select")[0].id.lastIndexOf("_") + 1);
        var qs = Hresform.getTravelInfo().substr(1);
        qs += "&currency=" + $(idpf + "bookCurrency").val();
        qs += "&bookAreas=" + location.search.match(/bookareas=([^&]*)/i)[1];
        var href = "findhso.aspx?" + qs;
        location.href = href;

        return false;
    },

    checkrateAJAX: function() {
        // used in search results
        var val, qs = "", hash = "", hash2 = "";

        var midx = location.href.indexOf("?");
        if (midx == -1) return false;

        var q = location.href.substring(midx + 1); // get the querystring
        q = q.replace(location.hash, "");

        var qsobj = q.match(/([^&=]*=[^&]*)/g);

        for (var i = 0; i < qsobj.length; i++) {
            var p = qsobj[i].split('=');
            if (!p[1]) continue;
            switch (p[0].toLowerCase()) {
                case "sort":
                    if (p[1] == "1") hash2 += "cS=nycsort";
                    else if (p[1] != "distance") hash2 += "cS=" + p[1];
                    // exclude distance because there is no distance sort in ajax mode
                    break;
                case "name": hash += "&nf=" + escape(p[1]); break;
                case "area": hash += "&lc=" + p[1]; break;
                case "int1": switch (p[1]) {
                        case "1436": hash += "&lS=1"; break;
                        case "1439": hash += "&lS=2"; break;
                        case "1442": hash += "&lS=3"; break;
                        case "1445": hash += "&lS=4"; break;
                        case "1448": hash += "&lS=5"; break;
                    };
                    break;
                case "star": hash += "&lS=" + p[1].split('/')[0]; break;
                case "int2":
                case "bookbrands": hash += "&bdid=" + p[1]; break;
                case "bookfeature": hash += "&ft=" + p[1]; break;
            }
        }

        var idpf = "#" + $(".hsFilters select")[0].id.substring(0, $(".hsFilters select")[0].id.lastIndexOf("_") + 1);
        qs += "&currency=" + $(idpf + "bookCurrency").val();

        qs = Hresform.getTravelInfo() + qs + "#" + hash.substring(1) + "||" + hash2;

        location.href = "findhs.aspx?" + qs.substring(1);

        return false;
    },

    refineSearch: function() {
        // used in search results
        // check date
        if (!Hresform.dateRangeCheck()) return false;
        // check age
        if (!Hresform.childAgeCheck()) return false;

        var qs = "?secid=4&israte=1";

        if (location.search.indexOf("ismap=1") >= 0) qs += "&ismap=1";

        qs += Hresform.getSearchOptions();
        qs += Hresform.getTravelInfo();
        var idpf = "#" + $(".hsFilters select")[0].id.substring(0, $(".hsFilters select")[0].id.lastIndexOf("_") + 1);
        var ppc = $(idpf + "ppctext").val();
        if (ppc) qs += "&ppc=" + ppc;

        var ba = location.search.match(/(?:bookareas|otherloc)=([^&]*)/i);
        if (ba) qs += "&isnyc=0&otherloc=" + ba[1];
        else qs += "&isnyc=1";

        LoadingMask.show();

        location.href = qs;

        return false;
    },

    searchRoom: function(val, isnotroomsearch) {
        // used in detail page
        // check date
        if (!Hresform.dateRangeCheck()) return false;
        // check age
        if (!Hresform.childAgeCheck()) return false;

        var qs = Hresform.getValues(!isnotroomsearch);

        // 10/09/2009, if search from home/section page, switch to affiliate page of travelnow
        if (isnotroomsearch && !Hresform.isInHouse) {
            var loc = "http://hotel.nyc.com/hotel/searchresults?cid=4092&searchType=DESTINATION&searchParam=572b0850-4e3f-469b-87b2-c17ed3ea049b";
            qs = qs.toQueryParams();
            var ci = qs.checkin.split('/');
            var co = qs.checkout.split('/');
            var checkin = new Date(ci[2], parseInt(ci[0]) - 1, ci[1]);
            var checkout = new Date(co[2], parseInt(co[0]) - 1, co[1]);
            var checkdiff = Math.floor((checkout - checkin) / 3600000 / 24);
            var roomsinfo = [];
            for (var i = 1; i < 9; i++) {
                var a = qs["r" + i + "a"]; var ca = qs["r" + i + "ca"];
                if (a) roomsinfo.push(a + (ca ? "," + ca : ""));
            }
            var cur = qs.currency ? qs.currency.split('-') : ["EN", "USD"];
            if (cur.length > 1) {
                // has locale
                cur = "&currencyCode=" + cur[1] + "&locale=" + cur[0];
            } else {
                cur = "&currencyCode=" + cur[0] + "&locale=EN";
            }
            loc += cur + "&travelDetail=[" + checkin.format("yyyyMMdd") + "-" + checkdiff + "]" + roomsinfo.join("-");
            location.href = loc;
        } else {
            // 10/14/2009, if isAjax is overriden, switch to ajax or non-ajax result accordingly
            if (val && !Hresform.isAjax) {
                val = "/search/findhsna.aspx";
            }

            location.href = (val ? val : "") + "?" + qs;
        }

        return false;
    },

    getTravelInfo: function() {
        var qs = [];
        //dates
        var dates = $("table[name=hresform]:eq(0) input[type=text]:lt(2)");
        qs.push("&checkin="); qs.push(escape(dates[0].value));
        qs.push("&checkout="); qs.push(escape(dates[1].value));
        // rooms
        var roomsel = $("table[name=hroomstbl]:eq(0) tbody tr:gt(0) select")
        var rooms = escape(roomsel.eq(0).val());
        qs.push("&rooms="); qs.push(rooms);
        // adults children
        var adultsel = roomsel.filter(":gt(0):even");
        var childsel = roomsel.filter(":gt(0):odd");
        var childtrs = $("table[name=hchildtbl]:eq(0) tbody tr");

        for (var i = 0; i < rooms; i++) {
            qs.push("&r" + (i + 1) + "a="); qs.push(adultsel.eq(i).val());
            var cn = childsel.eq(i).val();
            qs.push("&r" + (i + 1) + "c="); qs.push(cn);

            var idx = Hresform.childRoomIdx(i + 1);
            var sels = childtrs.filter(":gt(" + (-idx - 1) + "):lt(2)").find("select");
            // child ages
            if (cn > 0) {
                qs.push("&r" + (i + 1) + "ca="); qs.push(sels.eq(0).val());
                for (var j = 1; j < cn; j++) {
                    qs.push("," + sels.eq(j).val());
                }
            }
        }
        return qs.join('');
    },


    getValues: function(isRoomSearch) {
        var el = document.forms[0] ? document.forms[0].elements : {};
        var qs = [];
        // regular parameters
        qs.push("israte=1&isnew=1");
        if (el["hotelid"] != null) qs.push("&hotelid=" + el["hotelid"].value);
        if (el["spt"] != null) qs.push("&spt=" + el["spt"].value);

        qs.push(Hresform.getTravelInfo());

        if (el["currency"]) {
            qs.push("&currency=");
            if (el["currency"].options)
                qs.push(el["currency"].options[el["currency"].selectedIndex].value);
            else
                qs.push(escape(el["currency"].value));
        }
        qs.push("&secid=4");

        if (isRoomSearch) qs.push("#recordtitle");
        else if (el["searchHash"] != null) qs.push("#" + el["searchHash"].value);
        return qs.join('');
    },

    setValues: function(qstr) {
        if (!qstr)
            qstr = location.href.match(/^([^\?#]*)\??([^#]*)#?(.*)/)[2]; // 1=path, 2=qs, 3=hash
        var qs = qstr.split('&');
        for (var i = 0; i < qs.length; i++) {
            // get to find the rooms first
            if (qs[i].toLowerCase().indexOf("rooms=") === 0) {
                var p = qs[i].split('=');
                if (p[1] != "" && p[1] != "0") {
                    Hresform.roomChanged(p[1]);
                }
                qs.splice(i, 1);
                break;
            }
        }
        for (var i = 0; i < qs.length; i++) {
            // then get the room child number
            var m = qs[i].match(/^r(\d)c=(\d*)$/i); // 1=room num, 2=child num
            if (m) {
                Hresform.childChanged(m[2], m[1]);
                qs.splice(i, 1);
                i--;
            }
        }
        Hresform.childText(); // child text label
        for (var i = 0; i < qs.length; i++) {
            var p = qs[i].split('=');
            if (p.length < 2) continue;
            switch (p[0].toLowerCase()) {
                case "checkin":
                    $("table[name=hresform] input[type=text]:even").val(unescape(p[1]));
                    break;
                case "checkout":
                    $("table[name=hresform] input[type=text]:odd").val(unescape(p[1]));
                    break;
                case "r1a": case "r2a": case "r3a": case "r4a":
                case "r5a": case "r6a": case "r7a": case "r8a":
                    Hresform.adultChanged(p[1], p[0].charAt(1));
                    break;
                case "r1ca": case "r2ca": case "r3ca": case "r4ca":
                case "r5ca": case "r6ca": case "r7ca": case "r8ca":
                    var ca = p[1].split(',');
                    for (var j = 0; j < ca.length; j++) {
                        Hresform.childAgeChanged(ca[j], j, p[0].charAt(1));
                    }
                    break;
            }
        }

    },

    setDefaultCheckin: function() {
        var d = new Date();
        d.setDate(d.getDate() + 21);
        Hresform.checkinChange((d.getMonth() + 1) + "/" + d.getDate() + "/" + d.getFullYear());
    },

    checkinChange: function(date) {
        var newToDate = new Date(date);

        newToDate.setDate(newToDate.getDate() + 2);

        //sync checkin date    
        $("table[name=hresform] input[type=text]:even").val(date);

        // sync checkout date
        $("table[name=hresform] input[type=text]:odd").val(
	        parseInt(newToDate.getMonth() + 1) + "/" + newToDate.getDate() + "/" + newToDate.getFullYear());
    },

    checkoutChange: function(date) {
        // sync checkout date
        $("table[name=hresform] input[type=text]:odd").val(date);
    },

    dateRangeCheck: function() {
        var sels = $("table[name=hresform]:eq(0) input[type=text]:lt(2)");
        var checkin = sels[0];
        var checkout = sels[1];
        var fromDate = new Date(checkin.value);
        var toDate = new Date(checkout.value);
        var now = new Date();

        //Set 1 day in milliseconds
        var one_day = 1000 * 60 * 60 * 24;

        var diff = Math.ceil((toDate.getTime() - fromDate.getTime()) / one_day);
        var daysAhead = Math.ceil((toDate.getTime() - now.getTime()) / one_day);

        if (diff > 0) {
            if (daysAhead > 330) {
                alert("We cannot reserve hotel stays for more than 330 days ahead.\nPlease make sure your check-in and check-out dates have the proper month and year selected.");
                return false;
            } else if (diff > 30) {
                alert("We cannot reserve hotel stays for longer than 30 days.\nPlease make sure your check-in and check-out dates have the proper month and year selected.");
                return false;
            }
        } else {
            alert("The check-out date cannot be before the check-in date.\nPlease make sure your check-in and check-out dates have the proper dates selected.");
            return false;
        }

        return true;
    },

    childAgeCheck: function() {
        var roomsel = $("table[name=hroomstbl]:eq(0) tbody tr:gt(0) select");
        // first one is the room num, then adult#1 children#1 adult#2 children#2 etc..
        var numrooms = roomsel.eq(0).val();

        var childsel = roomsel.filter(":gt(0):odd");
        var childtrs = $("table[name=hchildtbl]:eq(0) tbody tr");

        var failed = false;
        childsel.each(function(i) {
            if (!failed && this.value > 0) { // have children
                var idx = Hresform.childRoomIdx(i + 1);
                var sels = childtrs.filter(":gt(" + (-idx - 1) + "):lt(2)").find("select");
                for (var i = 0; i < this.value; i++) {
                    if (sels[i].selectedIndex == 0) {
                        alert("Please specify the ages of all children.");
                        failed = true;
                        return false;
                    }
                }
            }
        });
        return !failed;
    },

    childRoomIdx: function(roomnum, tbl) {
        var tbl = tbl || $("table[name=hchildtbl]");
        var sib = tbl.eq(0).find("tbody tr:gt(2)");

        // find out whether the current room is here
        var insIdx = 2;
        sib.each(function(i) {
            var r = $(this).children(":eq(0)").html().substring(5);
            if (r != "") {
                if (r > roomnum) return false;
                else if (r == roomnum) { insIdx = -(++insIdx); return false; }
                insIdx = i + 4;
            }
        });
        // negative when it is there, index to tr in hchildtbl
        // positive is the position to append
        return insIdx;
    },

    childRemove: function(roomnum, tbl) {
        var tbl = tbl || $("table[name=hchildtbl]");
        var sib = tbl.eq(0).find("tbody tr:gt(2)");

        var insIdx = this.childRoomIdx(roomnum, tbl);

        // < 0 then, it is there
        if (insIdx < 0) {
            tbl.each(function() {
                $(this).find("tbody tr:nth(" + (-insIdx) + ")").hide().find("select").each(function() {
                    this.selectedIndex = 0;
                }).end().next().hide().find("select").each(function() {
                    this.selectedIndex = 0;
                });
            });
        }
        // hide the table if there are no more children rows
        if (sib.filter(":not(:hidden)").length == 0) tbl.hide();
    },

    childText: function(tbl) {
        // find out the maximum children dll needed
        var max = 0;
        $("table[name=hroomstbl]:eq(0) tr:gt(0) td:nth-child(4) select").each(function() {
            if (max < this.value) max = this.value;
        });

        tbl = tbl || $("table[name=hchildtbl]");
        // no child, so hide the text
        if (max == 0) tbl.find("tr").eq(0).hide();
        else tbl.find("tr").eq(0).show();

        tbl.each(function() {
            var trs = $(this).find("tbody tr:gt(0):lt(2)");
            trs.eq(0).children(":lt(" + (max + 1) + ")").show()
				.end().children(":gt(" + max + ")").hide();
            if (max > 3) {
                trs.eq(1).show().children(":lt(" + (max - 2) + ")").show()
					.end().children(":gt(" + (max - 3) + ")").hide();
            } else {
                trs.eq(1).hide();
            }
        });
    },

    childAgeChanged: function(age, idx, roomnum) {
        var ridx = Hresform.childRoomIdx(roomnum);
        $("table[name=hchildtbl]").each(function() {
            $(this).find("tr:gt(" + (-ridx - 1) + "):lt(2) select:eq(" + idx + ")").val(age);
        });
    },

    childChanged: function(childnum, roomnum) {
        var tbl = $("table[name=hchildtbl]");
        var sib = tbl.eq(0).find("tbody tr:gt(2)");

        // find out whether the current room is here
        var insIdx = this.childRoomIdx(roomnum, tbl);

        // make sure all instances get the child num
        $("table[name=hroomstbl]").each(function() {
            $(this).find("tr:eq(" + roomnum + ") td:eq(3) select").val(childnum);
        });

        if (childnum == 0) {
            // hide the row
            this.childRemove(roomnum, tbl);
        } else {
            if (insIdx < 0) {
                // it is already there, make it visible
                tbl.each(function() {
                    var r1 = $(this).find("tbody tr:nth(" + (-insIdx) + ")").show();
                    r1.children(":gt(0)").hide().filter(":lt(" + childnum + ")").show();
                    var r2 = r1.next();
                    if (childnum > 3) {
                        r2.show().children(":gt(0)").hide().filter(":lt(" + (childnum - 3) + ")").show();
                    } else {
                        r2.hide();
                    }
                });
            } else {
                // insert the child rows
                var h = this.cChildHTML(roomnum, childnum);
                tbl.each(function() {
                    $(this).find("tbody tr:nth(" + insIdx + ")").after(h);
                });
            }

            tbl.show();
        }

        this.childText(tbl); // show child text
    }, // end childChanged

    cChildHTML: function(roomnum, numchild) {
        var h = [];
        var r2 = numchild > 3 ? numchild - 3 : 0; // row 2
        var r1 = r2 > 0 ? 3 : numchild; // row 1		
        h.push("<tr><td>Room " + roomnum + "</td>");
        for (var i = 0; i < 3; i++) {
            if (i < r1) h.push("<td>"); else h.push("<td style='display:none'>");
            h.push("<select onchange='Hresform.childAgeChanged(this.value," + i + "," + roomnum + ")'>");
            h.push("<option value='-1'>-?-</option>");
            h.push("<option value='0'><1</option>");
            h.push("<option value='1'>1</option>");
            h.push("<option value='2'>2</option>");
            h.push("<option value='3'>3</option>");
            h.push("<option value='4'>4</option>");
            h.push("<option value='5'>5</option>");
            h.push("<option value='6'>6</option>");
            h.push("<option value='7'>7</option>");
            h.push("<option value='8'>8</option>");
            h.push("<option value='9'>9</option>");
            h.push("<option value='10'>10</option>");
            h.push("<option value='11'>11</option>");
            h.push("<option value='12'>12</option>");
            h.push("<option value='13'>13</option>");
            h.push("<option value='14'>14</option>");
            h.push("<option value='15'>15</option>");
            h.push("<option value='16'>16</option>");
            h.push("<option value='17'>17</option>");
            h.push("</select></td>");
        }

        if (r2 > 0) h.push("</tr><tr><td></td>"); else h.push("</tr><tr style='display:none'><td></td>");
        for (var i = 0; i < 3; i++) {
            if (i < r2) h.push("<td>"); else h.push("<td style='display:none'>");
            h.push("<select onchange='Hresform.childAgeChanged(this.value," + (i + 3) + "," + roomnum + ")'>");
            h.push("<option value='-1'>-?-</option>");
            h.push("<option value='0'><1</option>");
            h.push("<option value='1'>1</option>");
            h.push("<option value='2'>2</option>");
            h.push("<option value='3'>3</option>");
            h.push("<option value='4'>4</option>");
            h.push("<option value='5'>5</option>");
            h.push("<option value='6'>6</option>");
            h.push("<option value='7'>7</option>");
            h.push("<option value='8'>8</option>");
            h.push("<option value='9'>9</option>");
            h.push("<option value='10'>10</option>");
            h.push("<option value='11'>11</option>");
            h.push("<option value='12'>12</option>");
            h.push("<option value='13'>13</option>");
            h.push("<option value='14'>14</option>");
            h.push("<option value='15'>15</option>");
            h.push("<option value='16'>16</option>");
            h.push("<option value='17'>17</option>");
            h.push("</select></td>");
        }
        h.push("</tr>");
        return h.join('');
    }, // end cChildHTML

    adultChanged: function(num, roomnum) {
        $("table[name=hroomstbl]").each(function() {
            var tbl = $(this);
            var sel = tbl.find("select:gt(0):even:eq(" + (roomnum - 1) + ")");
            sel.val(num);
        });
    },

    roomChanged: function(roomnum) {
        if (roomnum >= 9) {
            window.location = "http://nyc.hotelplanner.com/GroupForm.cfm";

            return;
        }

        $("table[name=hroomstbl]").each(function() {
            var tbl = $(this);
            var sib = tbl.find("tr:gt(0)");
            // show the room 1 label if there is more than 1 room
            if (roomnum > 1) sib.eq(0).children(":eq(1)").children().show(); else sib.eq(0).children(":eq(1)").children().hide();

            // set the room number, to make sure all instances have it
            sib.eq(0).find("select:eq(0)").val(roomnum);

            // there is more than needed
            if (sib.length > roomnum) {
                // how many exceeded
                sib.filter(":gt(" + (roomnum - 1) + ")").remove();
                // remove all child rows regardless
                var i = roomnum;
                for (i++; i <= Hresform.maxRooms; i++) {
                    Hresform.childRemove(i);
                }

            } else if (sib.length < roomnum) {
                // how many more rooms needed
                var diff = roomnum - sib.length;
                // if only 1 room, then choose room 1 as the pointer, otherwise,
                // choose the last one
                var lroom = sib.eq(sib.length - 1);
                // for each room needed
                for (var i = 0; i < diff; i++) {
                    var r = Hresform.cRoomHTML(sib.length + i + 1);
                    lroom = lroom.after(r).next();
                }
            }
        });
    }, // end roomChanged

    cRoomHTML: function(num) {
        var h = [];
        h.push("<tr><td></td><td>Room ");
        h.push(num); h.push("</td><td>");
        h.push("<select onchange='Hresform.adultChanged(this.value," + num + ")'>");
        //h.push("<option value='0'>0</option>");
        h.push("<option value='1'>1</option>");
        h.push("<option value='2' selected='selected'>2</option>");
        h.push("<option value='3'>3</option>");
        h.push("<option value='4'>4</option>");
        h.push("</select></td><td>");
        h.push("<select onchange='Hresform.childChanged(this.value," + num + ")'>");
        h.push("<option value='0'>0</option>");
        h.push("<option value='1'>1</option>");
        h.push("<option value='2'>2</option>");
        h.push("<option value='3'>3</option>");
        //        h.push("<option value='4'>4</option>");
        //        h.push("<option value='5'>5</option>");
        //        h.push("<option value='6'>6</option>");
        h.push("</select></td>");
        h.push("</tr>");
        return h.join('');
    },

    // if the hotel is GDS, set the max rooms to 4
    setGDS: function() {
        // make sure this is not called more than once.
        if (Hresform.maxRooms != 4) {
            Hresform.maxRooms = 4;
            $("table[name=hroomstbl]").each(function() {
                $(this).find("select:eq(0) option:gt(3)").remove();
            });
        }
    }, // end setGDS

    enterResForm: function(qs) {
        var form = document.createElement('FORM');
        form.action = Hresform.hotelresurl ? Hresform.hotelresurl : "https://" + location.host + "/secure/hotelres.aspx";
        form.method = 'post';

        var body = document.body;
        body.appendChild(form);

        var parts = qs.split('&');

        for (var i = 0; i < parts.length; i++) {
            var namevalue = parts[i].split('=');
            var input = document.createElement('INPUT');
            input.type = 'hidden';
            input.name = namevalue[0];
            input.value = namevalue[1].replace(/%2f/g, '/');
            form.appendChild(input);
        }

        var ref = document.createElement('INPUT');
        ref.type = 'hidden';
        ref.name = 'referrer';
        ref.value = location.pathname + location.search + location.hash;
        form.appendChild(ref);

        //alert( form.innerHTML );
        form.submit();

        return false;
    }, // end enterResForm

    enterResForm2: function(qs) {
        var searchqs = escape(location.pathname + location.search + location.hash);
        
        return Hresform.enterResForm(qs + "&sra=" + searchqs);
    }
};                    // end Hresform


// Compare hotels tool method:
// AJAX call to store selected hotel to session        
var HsresCompare = {
    toolTipText : "Click here to add <b>REPLACE</b> to your personal compare list"
                    + "<br /><br />When you have selected the hotels you wish to compare, click "
                    + "on the button that appears on the top right of your screen",
    toolTipText_Un : "Click here to remove <b>REPLACE</b> from your personal compare list",
        
	select2Compare : function(checkbox) {
	    $.post( "post.nyc", 
	        { _ns:"Hotels", _m:"CompareBoxChanged", _a:1, v:checkbox.value, c:checkbox.checked },
	        function(data) {
				var compareButton = $("#compareBtn")[0];
				if ( eval(data) > 0 ) {
					compareButton.value = "Click to Compare " + data + " Hotel" + (data == "1" ? "" : "s");
                    compareButton.style.display = "inline";
                } else {
                    compareButton.style.display = "none";
                }
			});
		return false;
	},
	
	checkBoxMouseover : function(checkbox, hotelname) {
		if (checkbox.checked)
			ddrivetip( HsresCompare.toolTipText_Un.replace(/REPLACE/g, hotelname) );
		else
			ddrivetip( HsresCompare.toolTipText.replace(/REPLACE/g, hotelname) );
	},
	
	compareHotels : function() {
	    $.post( "post.nyc", 
	        { _ns:"Hotels", _m:"SelectedHotelsCount", _a:1 },
	        function( data) {
			    if ( eval(data) > 0)
                    window.location = "/search/hotelcompare.aspx";
                else
                    alert("Please select hotels to compare!");
		});
	}
}; // end HsresCompare

var HUtils = {
    popHotelPhoto : function(hotelid) {
        window.open("/hotels/images.aspx?h=" + hotelid, "hotelphoto", "height=550,width=500");
        return false;
    },
    
    
    openSecureServerWindow : function() {
        var url = "/secure/secureserver.htm";
        var topTitle = "NYC.com Uses Industry Leading Security Measures";
        var icon = "/image/hotels/lock_black.jpg";
        NycHotelPopup.popup(null,url,topTitle,650,null,icon);
    }	
    
}; // end HUtils


// Right Floating Box
var HpnlFloat = {
    floatTblId : "tblHsRightFloat",
    floatTbl : null,
    
    render : function() {
        HpnlFloat.floatTbl = $.createElement("table", { id:HpnlFloat.floatTblId });
        
	    var html = [];
        html.push("<tbody><tr valign='middle'><td>");
            html.push("<div id='hsRightFloat'>");
                html.push("<div class='title'>Top Five Reasons to Book with NYC.com</div>");
                html.push("<div class='point'>\
                        Guaranteed Lowest Rates\
                    </div>");
                html.push("<div class='point'>No NYC.com Change or Cancel Fee</div>");
                html.push("<div class='point'>\
                        New York Hotel Experts Available 24 Hours a Day\
                        Toll-Free: 1.888.847.4869<br />\
                        Direct: +1.817.333.5124\
                    </div>");
                html.push("<div class='point'>The Official New York Hotel Guide</div>");
                html.push("<div class='point'>We Know New York!</div>");
            html.push("</div>");
        html.push("</td></tr></tbody>");
        HpnlFloat.floatTbl.append(html.join(''));
        
        $("#nycBody").append(HpnlFloat.floatTbl);
        
        HpnlFloat.updatePosition();
        
        if (window.addEventListener) {
            window.addEventListener('resize', HpnlFloat.updatePosition, false);
            window.addEventListener('scroll', HpnlFloat.updatePosition, false);
        } else if (window.attachEvent) {
            window.attachEvent('onresize', HpnlFloat.updatePosition);
            window.attachEvent('onscroll', HpnlFloat.updatePosition);
        }
        
        return false;
	},
	
	updatePosition : function() {
        var dimension = [630,460];
        var scrollTop = HpnlFloat.getScrollTop();
        dimension = document.viewport.getDimensions();
        
        HpnlFloat.floatTbl.css("height", dimension.height + "px");
        HpnlFloat.floatTbl.css("top", scrollTop + "px");
    },
    
    getScrollTop : function() {
        var ScrollTop = document.viewport.getScrollOffsets()["y"];
        
        return ScrollTop - 200;
    }
}; // end HpnlFloat
﻿var offsetxpoint=-10; //Customize x offset of tooltip
var offsetypoint=20; //Customize y offset of tooltip
var ie=document.all;
var ns6=document.getElementById && !document.all;
var enabletip=false;
var tipobj=null;

function dhtmlEffectOnLoad() {
    tipobj = document.createElement("DIV");
    tipobj.id = "dhtmltooltip";
    document.body.appendChild( tipobj );
}

function ietruebody(){
    return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
}

function ddrivetip(thetext, thecolor, thewidth){
	if ( tipobj == null ) {
		tipobj = document.createElement("DIV");
		tipobj.id = "dhtmltooltip";
		document.body.appendChild( tipobj );		
	}
    if (ns6||ie){
        if (typeof thewidth!="undefined") tipobj.style.width=thewidth+"px";
        if (typeof thecolor!="undefined" && thecolor!="") tipobj.style.backgroundColor=thecolor;
        tipobj.innerHTML=thetext;
        enabletip=true;
        return false;
    }
}

function positiontip(e){
    if (enabletip){
        var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
        var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
        //Find out how close the mouse is to the corner of the window
        var rightedge=ie&&!window.opera? ietruebody().clientWidth-event.clientX-offsetxpoint : window.innerWidth-e.clientX-offsetxpoint-20;
        var bottomedge=ie&&!window.opera? ietruebody().clientHeight-event.clientY-offsetypoint : window.innerHeight-e.clientY-offsetypoint-20;

        var leftedge=(offsetxpoint<0)? offsetxpoint*(-1) : -1000;
        
        //if the horizontal distance isn't enough to accomodate the width of the context menu
        if (rightedge<tipobj.offsetWidth)
        //move the horizontal position of the menu to the left by it's width
        tipobj.style.left=ie? ietruebody().scrollLeft+event.clientX-tipobj.offsetWidth+"px" : window.pageXOffset+e.clientX-tipobj.offsetWidth+"px";
        else if (curX<leftedge)
        tipobj.style.left="5px";
        else
        //position the horizontal position of the menu where the mouse is positioned
        tipobj.style.left=curX+offsetxpoint+"px";

        //same concept with the vertical position
        if (bottomedge<tipobj.offsetHeight)
        tipobj.style.top=ie? ietruebody().scrollTop+event.clientY-tipobj.offsetHeight-offsetypoint+"px" : window.pageYOffset+e.clientY-tipobj.offsetHeight-offsetypoint+"px";
        else
        tipobj.style.top=curY+offsetypoint+"px";
        tipobj.style.visibility="visible";
    }
}

function hideddrivetip(){
    if (ns6||ie){
        enabletip=false;
        tipobj.style.visibility="hidden";
        tipobj.style.left="-1000px";
        tipobj.style.backgroundColor='';
        tipobj.style.width='';
    }
}

document.onmousemove=positiontip;

function getposOffset(overlay, offsettype){
var totaloffset=(offsettype=="left")? overlay.offsetLeft : overlay.offsetTop;
var parentEl=overlay.offsetParent;
while (parentEl!=null){
totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}

function overlay(curobj, subobjstr, opt_position){
if (document.getElementById){
var subobj=document.getElementById(subobjstr);
subobj.style.display=(subobj.style.display!="block")? "block" : "none";
var xpos=getposOffset(curobj, "left")+((typeof opt_position!="undefined" && opt_position.indexOf("right")!=-1)? -(subobj.offsetWidth-curobj.offsetWidth) : 0); 
var ypos=getposOffset(curobj, "top")+((typeof opt_position!="undefined" && opt_position.indexOf("bottom")!=-1)? curobj.offsetHeight : 0);
subobj.style.left=xpos+"px";
subobj.style.top=ypos+"px";
return false;
}
else
return true;
}

function overlayclose(subobj){
document.getElementById(subobj).style.display="none";
}

var __monthslong=["January","February","March","April","May","June","July","August","September","October","November","December"];var __monthsshort=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];var __calImgPath="/image/calendar/";var __calendars=new Array();var __calDivId="nycCal";function Calendar(arrayID,uniqueName,dateFrom,dateTo){this.currDate=new Date();this.uniqueName=uniqueName;this.arrayID=arrayID;this.products=new Array();this.selectedDays=new Array();this.prodDesc="";this.dateFrom=dateFrom;this.dateTo=dateTo;this.startTally=new Array();this.maxDays=1;this.bottomMsg="Select a date from the calendar above";this.posDateColor="#808080"}Calendar.prototype.drawCal=function(nudgeMonth,alreadyLoaded){this.currDate.setMonth((this.currDate.getMonth()+nudgeMonth));var tmpNextMo=new Date(this.currDate.getFullYear(),(this.currDate.getMonth()+1),1);var calStr='<table cellpadding="0" cellspacing="0" border="0"><tr><td style="background:url('+__calImgPath+'ul.gif) no-repeat; height:6px;"></td><td style="background:url('+__calImgPath+'ur.gif) right top no-repeat; height:6px; width:6px;"></td></tr><tr><td style="background:url('+__calImgPath+'ml.gif) left top repeat-y; text-align:center; font-family:Tahoma; font-size:9pt; color:#808080; overflow:auto; padding-left:6px;" id="__calMessage"><table cellpadding="0" cellspacing="0" border="0"><tr><td width="100%" colspan="2" align="middle" style="padding-bottom:5px;"><table cellpadding="0" cellspacing="0" border="0" width="100%"><tr><td align="left" style="font-size:9pt; color:#000000; text-align:left; cursor:pointer;" onClick="__calendars['+this.arrayID+'].drawCal((-1), true);"><img border=0 src="'+__calImgPath+'_left.gif"></td><td width="50%" align="left" style="padding:0px 16px 0px 0px; font-size:9pt; color:#000000; text-align:center; cursor:default;"><b><nobr>'+__monthslong[this.currDate.getMonth()]+" "+this.currDate.getFullYear()+'</nobr></b></td><td width="50%" align="right" style="padding:0px 0px 0px 16px; font-size:9pt; color:#000000; text-align:center; cursor:default;"><b><nobr>'+__monthslong[tmpNextMo.getMonth()]+" "+tmpNextMo.getFullYear()+'</nobr></b></td><td align="right" style="font-size:9pt; color:#000000; text-align:right; cursor:pointer;" onClick="__calendars['+this.arrayID+'].drawCal(1, true);"><img border=0 src="'+__calImgPath+'_right.gif"></td></tr></table></td></tr><tr><td valign="top"><table cellpadding="0" cellspacing="0" border="0"><tr><td align="middle" style="background:#EEEEEE url('+__calImgPath+'lightgray-gradient-ee.gif) bottom repeat-x; padding:1px; font-family:Tahoma; font-size:8pt; color:#000000; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; border-top:1px solid #EEEEEE; text-align:center; cursor:default;">S</td><td align="middle" style="background:#EEEEEE url('+__calImgPath+'lightgray-gradient-ee.gif) bottom repeat-x; padding:1px; font-family:Tahoma; font-size:8pt; color:#000000; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; border-top:1px solid #EEEEEE; text-align:center; cursor:default;">M</td><td align="middle" style="background:#EEEEEE url('+__calImgPath+'lightgray-gradient-ee.gif) bottom repeat-x; padding:1px; font-family:Tahoma; font-size:8pt; color:#000000; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; border-top:1px solid #EEEEEE; text-align:center; cursor:default;">T</td><td align="middle" style="background:#EEEEEE url('+__calImgPath+'lightgray-gradient-ee.gif) bottom repeat-x; padding:1px; font-family:Tahoma; font-size:8pt; color:#000000; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; border-top:1px solid #EEEEEE; text-align:center; cursor:default;">W</td><td align="middle" style="background:#EEEEEE url('+__calImgPath+'lightgray-gradient-ee.gif) bottom repeat-x; padding:1px; font-family:Tahoma; font-size:8pt; color:#000000; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; border-top:1px solid #EEEEEE; text-align:center; cursor:default;">T</td><td align="middle" style="background:#EEEEEE url('+__calImgPath+'lightgray-gradient-ee.gif) bottom repeat-x; padding:1px; font-family:Tahoma; font-size:8pt; color:#000000; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; border-top:1px solid #EEEEEE; text-align:center; cursor:default;">F</td><td align="middle" style="background:#EEEEEE url('+__calImgPath+'lightgray-gradient-ee.gif) bottom repeat-x; padding:1px; font-family:Tahoma; font-size:8pt; color:#000000; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; border-top:1px solid #EEEEEE; text-align:center; cursor:default;">S</td></tr><tr>';this.currDate.setDate(1);var pMonth=new Date();pMonth.setFullYear(this.currDate.getFullYear(),this.currDate.getMonth(),(this.currDate.getDate()-1));var dCount=new Date();dCount.setFullYear(this.currDate.getFullYear(),(this.currDate.getMonth()+1),(this.currDate.getDate()-1));var dayCounter=0;for(var pMo=1;pMo<=this.currDate.getDay();pMo++){calStr+='<td align="middle" style="padding:2px; font-family:Tahoma; font-size:9pt; color:#AAAAAA; border-bottom:1px solid #CCCCCC; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; text-align:center; cursor:default;">&nbsp;</td>';dayCounter++}for(var cMD=0;cMD<dCount.getDate();cMD++){var validFrom=true;if(typeof(this.dateFrom)!="undefined"){if(this.dateFrom.getTime()>(new Date((this.currDate.getMonth()+1)+"/"+(this.currDate.getDate()+cMD)+"/"+this.currDate.getFullYear())).getTime()){validFrom=false}}var validTo=true;if(typeof(this.dateTo)!="undefined"){if(this.dateTo.getTime()<(new Date((this.currDate.getMonth()+1)+"/"+(this.currDate.getDate()+cMD)+"/"+this.currDate.getFullYear())).getTime()){validTo=false}}var dayInList=false;for(var dInd=0;dInd<this.selectedDays.length;dInd++){if(this.selectedDays[dInd][0]==this.currDate.getFullYear()&&this.selectedDays[dInd][1]==this.currDate.getMonth()&&this.selectedDays[dInd][2]==(this.currDate.getDate()+cMD)){dayInList=true}}if(validFrom==false||validTo==false){calStr+='<td align="middle" style="padding:2px; font-family:Tahoma; background:#EFEFEF; font-size:9pt; color:#808080; border-bottom:1px solid #CCCCCC; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; text-align:center; cursor:default;'}else{calStr+='<td id="__cal'+this.arrayID+"__"+this.currDate.getFullYear()+"-"+this.currDate.getMonth()+"-"+(this.currDate.getDate()+cMD)+'" align="middle" style="padding:2px; font-family:Tahoma; font-size:9pt; border-bottom:1px solid #CCCCCC; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; text-align:center; cursor:pointer;';if(dayInList){calStr+=" background:#006699; color:#FFFFFF;"}else{calStr+=" background:#FFFFFF; color:"+this.posDateColor+";"}}if(validFrom==false||validTo==false){calStr+=" text-decoration:line-through;"}if(validFrom==true&&validTo==true){calStr+='" onMouseOver="__calendars['+this.arrayID+"].toggleDayHilight(["+this.currDate.getFullYear()+","+this.currDate.getMonth()+","+(this.currDate.getDate()+cMD)+'], this, true);" '}if(validFrom==true&&validTo==true){calStr+='" onMouseOut="__calendars['+this.arrayID+"].toggleDayHilight(["+this.currDate.getFullYear()+","+this.currDate.getMonth()+","+(this.currDate.getDate()+cMD)+'], this, false);" onMouseDown="__calendars['+this.arrayID+"].toggleDay(["+this.currDate.getFullYear()+","+this.currDate.getMonth()+","+(this.currDate.getDate()+cMD)+"], this, 'down');\" onMouseUp=\"__calendars["+this.arrayID+"].toggleDay(["+this.currDate.getFullYear()+","+this.currDate.getMonth()+","+(this.currDate.getDate()+cMD)+"], this, 'up');\">"+(this.currDate.getDate()+cMD)+"</td>"}else{calStr+='">'+(this.currDate.getDate()+cMD)+"</td>"}dayCounter++;if((dayCounter%7)==0){calStr+="</tr>";if(cMD!=dCount.getDate()){"<tr>"}}}for(var eMo=1;eMo<=(6-dCount.getDay());eMo++){calStr+='<td align="middle" style="padding:2px; font-family:Tahoma; font-size:9pt; color:#AAAAAA; border-bottom:1px solid #CCCCCC; border-right:1px solid #CCCCCC; border-left:1px solid #FFFFFF; text-align:center; cursor:default;">&nbsp;</td>';dayCounter++}calStr+='</table></td><td valign="top" style="padding-left:5px;"><table cellpadding=0 cellspacing=0 border=0><tr><td align="middle" style="background:#EEEEEE url('+__calImgPath+'lightgray-gradient-ee.gif) bottom repeat-x; padding:1px; font-family:Tahoma; font-size:8pt; color:#000000; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; border-top:1px solid #EEEEEE; text-align:center; cursor:default;">S</td><td align="middle" style="background:#EEEEEE url('+__calImgPath+'lightgray-gradient-ee.gif) bottom repeat-x; padding:1px; font-family:Tahoma; font-size:8pt; color:#000000; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; border-top:1px solid #EEEEEE; text-align:center; cursor:default;">M</td><td align="middle" style="background:#EEEEEE url('+__calImgPath+'lightgray-gradient-ee.gif) bottom repeat-x; padding:1px; font-family:Tahoma; font-size:8pt; color:#000000; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; border-top:1px solid #EEEEEE; text-align:center; cursor:default;">T</td><td align="middle" style="background:#EEEEEE url('+__calImgPath+'lightgray-gradient-ee.gif) bottom repeat-x; padding:1px; font-family:Tahoma; font-size:8pt; color:#000000; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; border-top:1px solid #EEEEEE; text-align:center; cursor:default;">W</td><td align="middle" style="background:#EEEEEE url('+__calImgPath+'lightgray-gradient-ee.gif) bottom repeat-x; padding:1px; font-family:Tahoma; font-size:8pt; color:#000000; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; border-top:1px solid #EEEEEE; text-align:center; cursor:default;">T</td><td align="middle" style="background:#EEEEEE url('+__calImgPath+'lightgray-gradient-ee.gif) bottom repeat-x; padding:1px; font-family:Tahoma; font-size:8pt; color:#000000; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; border-top:1px solid #EEEEEE; text-align:center; cursor:default;">F</td><td align="middle" style="background:#EEEEEE url('+__calImgPath+'lightgray-gradient-ee.gif) bottom repeat-x; padding:1px; font-family:Tahoma; font-size:8pt; color:#000000; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; border-top:1px solid #EEEEEE; text-align:center; cursor:default;">S</td></tr><tr>';this.currDate.setMonth((this.currDate.getMonth()+1),1);var pMonth=new Date();pMonth.setFullYear(this.currDate.getFullYear(),this.currDate.getMonth(),(this.currDate.getDate()-1));var dCount=new Date();dCount.setFullYear(this.currDate.getFullYear(),(this.currDate.getMonth()+1),(this.currDate.getDate()-1));var dayCounter=0;for(var pMo=1;pMo<=this.currDate.getDay();pMo++){calStr+='<td align="middle" style="padding:2px; font-family:Tahoma; font-size:9pt; color:#AAAAAA; border-bottom:1px solid #CCCCCC; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; text-align:center; cursor:default;">&nbsp;</td>';dayCounter++}for(var cMD=0;cMD<dCount.getDate();cMD++){var validFrom=true;if(typeof(this.dateFrom)!="undefined"){if(this.dateFrom.getTime()>(new Date((this.currDate.getMonth()+1)+"/"+(this.currDate.getDate()+cMD)+"/"+this.currDate.getFullYear())).getTime()){validFrom=false}}var validTo=true;if(typeof(this.dateTo)!="undefined"){if(this.dateTo.getTime()<(new Date((this.currDate.getMonth()+1)+"/"+(this.currDate.getDate()+cMD)+"/"+this.currDate.getFullYear())).getTime()){validTo=false}}var dayInList=false;for(var dInd=0;dInd<this.selectedDays.length;dInd++){if(this.selectedDays[dInd][0]==this.currDate.getFullYear()&&this.selectedDays[dInd][1]==this.currDate.getMonth()&&this.selectedDays[dInd][2]==(this.currDate.getDate()+cMD)){dayInList=true}}if(validFrom==false||validTo==false){calStr+='<td align="middle" style="padding:2px; font-family:Tahoma; background:#EFEFEF; font-size:9pt; color:#808080; border-bottom:1px solid #CCCCCC; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; text-align:center; cursor:default;'}else{calStr+='<td id="__cal'+this.arrayID+"__"+this.currDate.getFullYear()+"-"+this.currDate.getMonth()+"-"+(this.currDate.getDate()+cMD)+'" align="middle" style="padding:2px; font-family:Tahoma; font-size:9pt; border-bottom:1px solid #CCCCCC; border-right:1px solid #CCCCCC; border-left:1px solid #EEEEEE; text-align:center; cursor:pointer;';if(dayInList){calStr+=" background:#006699; color:#FFFFFF;"}else{calStr+=" background:#FFFFFF; color:"+this.posDateColor+";"}}if(validFrom==false||validTo==false){calStr+=" text-decoration:line-through;"}if(validFrom==true&&validTo==true){calStr+='" onMouseOver="__calendars['+this.arrayID+"].toggleDayHilight(["+this.currDate.getFullYear()+","+this.currDate.getMonth()+","+(this.currDate.getDate()+cMD)+'], this, true);" '}if(validFrom==true&&validTo==true){calStr+='" onMouseOut="__calendars['+this.arrayID+"].toggleDayHilight(["+this.currDate.getFullYear()+","+this.currDate.getMonth()+","+(this.currDate.getDate()+cMD)+'], this, false);" onMouseDown="__calendars['+this.arrayID+"].toggleDay(["+this.currDate.getFullYear()+","+this.currDate.getMonth()+","+(this.currDate.getDate()+cMD)+"], this, 'down');\" onMouseUp=\"__calendars["+this.arrayID+"].toggleDay(["+this.currDate.getFullYear()+","+this.currDate.getMonth()+","+(this.currDate.getDate()+cMD)+"], this, 'up');\">"+(this.currDate.getDate()+cMD)+"</td>"}else{calStr+='">'+(this.currDate.getDate()+cMD)+"</td>"}dayCounter++;if((dayCounter%7)==0){calStr+="</tr>";if(cMD!=dCount.getDate()){"<tr>"}}}for(var eMo=1;eMo<=(6-dCount.getDay());eMo++){calStr+='<td align="middle" style="padding:2px; font-family:Tahoma; font-size:9pt; color:#AAAAAA; border-bottom:1px solid #CCCCCC; border-right:1px solid #CCCCCC; border-left:1px solid #FFFFFF; text-align:center; cursor:default;">&nbsp;</td>';dayCounter++}calStr+='</table></td></tr><tr><td colspan=2 id="__cal'+this.arrayID+'__message" align="left" style="font-family:Tahoma; color:#000000; font-size:9pt; padding:2px;">'+this.bottomMsg+'</td></tr></table></td><td style="background:url('+__calImgPath+'mr.gif) right top repeat-y; height:6px;"><img width="1" height="6" border=0 src="_blank.gif"></td></tr><tr><td style="background:url('+__calImgPath+'bl.gif) no-repeat; height:6px;"><img width="1" height="6" border=0 src="_blank.gif"></td><td style="background:url('+__calImgPath+'br.gif) right top no-repeat; height:6px; width:6px;"><img width="6" height="6" border=0 src="_blank.gif"></td></tr></table>';this.currDate.setMonth((this.currDate.getMonth()-1));if(typeof(alreadyLoaded)!="undefined"&&alreadyLoaded==true){document.getElementById(this.uniqueName).innerHTML=calStr}else{return'<div id="'+this.uniqueName+'">'+calStr+"</div>"}};Calendar.prototype.toggleDay=function(day,divBlock,buttonEvent){var dayInList=(-1);for(var dInd=0;dInd<this.selectedDays.length;dInd++){if(this.selectedDays[dInd][0]==day[0]&&this.selectedDays[dInd][1]==day[1]&&this.selectedDays[dInd][2]==day[2]){dayInList=dInd}}if(dayInList==(-1)&&this.startTally.length==0&&buttonEvent=="down"){if(this.selectedDays.length>=1){var oldDivBlock=document.getElementById("__cal"+this.arrayID+"__"+this.selectedDays[0][0]+"-"+this.selectedDays[0][1]+"-"+this.selectedDays[0][2]);if(oldDivBlock!=null){oldDivBlock.style.background="#FFFFFF";oldDivBlock.style.color=this.posDateColor}this.selectedDays=new Array();this.startTally=new Array()}divBlock.style.background="#006699";divBlock.style.color="#FFFFFF";this.selectedDays.push(day);this.startTally=day;this.toggleDayHilight(day,divBlock,true);this.selectedDays.sort(function(a,b){return(new Date(a[0],a[1],a[2])).getTime()-(new Date(b[0],b[1],b[2])).getTime()})}else{if(this.startTally.length>0&&buttonEvent=="up"){var countDays=1;var tallyDest=new Date(day[0],(parseInt(day[1])+0),day[2]);var tallyNew=new Date(this.startTally[0],(parseInt(this.startTally[1])+0),this.startTally[2]);var tallyPivot=new Date(this.startTally[0],(parseInt(this.startTally[1])+0),this.startTally[2]);while(tallyNew.getFullYear()!=tallyDest.getFullYear()||tallyNew.getMonth()!=tallyDest.getMonth()||tallyNew.getDate()!=tallyDest.getDate()){countDays++;if(tallyNew.getTime()<tallyDest.getTime()){tallyNew.setDate(tallyNew.getDate()+1)}else{tallyNew.setDate(tallyNew.getDate()-1)}var newDayInList=false;for(var dInd=0;dInd<this.selectedDays.length;dInd++){if(this.selectedDays[dInd][0]==tallyNew.getFullYear()&&this.selectedDays[dInd][1]==tallyNew.getMonth()&&this.selectedDays[dInd][2]==tallyNew.getDate()){newDayInList=true}}var newDivBlock=document.getElementById("__cal"+this.arrayID+"__"+tallyNew.getFullYear()+"-"+tallyNew.getMonth()+"-"+tallyNew.getDate());if(!newDayInList&&countDays<=this.maxDays&&newDivBlock){this.selectedDays.push([tallyNew.getFullYear(),tallyNew.getMonth(),tallyNew.getDate()]);this.selectedDays.sort(function(a,b){return(new Date(a[0],a[1],a[2])).getTime()-(new Date(b[0],b[1],b[2])).getTime()});newDivBlock.style.background="#006699";newDivBlock.style.color="#FFFFFF"}else{if(!newDayInList&&newDivBlock){newDivBlock.style.background="#FFFFFF";newDivBlock.style.color=this.posDateColor}}}this.startTally=new Array()}else{if(buttonEvent=="up"){var tallyNew=new Date(day[0],(parseInt(day[1])+0),day[2]);var tallyPrev=new Date(day[0],(parseInt(day[1])+0),day[2]);tallyPrev.setDate(tallyPrev.getDate()-1);var prevDayInList=false;var remDayInList=true;var remDayInListInd=(-1);for(var dInd=0;dInd<this.selectedDays.length;dInd++){if(this.selectedDays[dInd][0]==tallyPrev.getFullYear()&&this.selectedDays[dInd][1]==tallyPrev.getMonth()&&this.selectedDays[dInd][2]==tallyPrev.getDate()){prevDayInList=true}}if(!prevDayInList){while(remDayInList){tallyNew.setDate(tallyNew.getDate()+1);var newDivBlock=document.getElementById("__cal"+this.arrayID+"__"+tallyNew.getFullYear()+"-"+tallyNew.getMonth()+"-"+tallyNew.getDate());remDayInList=false;for(var rdInd=0;rdInd<this.selectedDays.length;rdInd++){if(this.selectedDays[rdInd][0]==tallyNew.getFullYear()&&this.selectedDays[rdInd][1]==tallyNew.getMonth()&&this.selectedDays[rdInd][2]==tallyNew.getDate()){remDayInListInd=rdInd;remDayInList=true}}if(remDayInList){this.selectedDays.splice(remDayInListInd,1);this.selectedDays.sort(function(a,b){return(new Date(a[0],a[1],a[2])).getTime()-(new Date(b[0],b[1],b[2])).getTime()});this.toggleDayHilight([tallyNew.getFullYear(),tallyNew.getMonth(),tallyNew.getDate()],newDivBlock,false)}}}if(dayInList!=(-1)){this.selectedDays.splice(dayInList,1);this.selectedDays.sort(function(a,b){return(new Date(a[0],a[1],a[2])).getTime()-(new Date(b[0],b[1],b[2])).getTime()});this.toggleDayHilight(day,divBlock,false)}this.startTally=new Array()}}}window.setTimeout("document.getElementById(__calDivId).style.display = 'none'",500)};Calendar.prototype.toggleDayHilight=function(day,divBlock,toggle){var dayInList=false;for(var dInd=0;dInd<this.selectedDays.length;dInd++){if(this.selectedDays[dInd][0]==day[0]&&this.selectedDays[dInd][1]==day[1]&&this.selectedDays[dInd][2]==day[2]){dayInList=true}}if(toggle){divBlock.style.background="#008FD6";divBlock.style.color="#FFFFFF"}else{if(dayInList){divBlock.style.background="#006699";divBlock.style.color="#FFFFFF"}else{divBlock.style.background="#FFFFFF";divBlock.style.color=this.posDateColor}}};var HotelCalendar={div:null,isInit:false,dateFrom:(parseInt((new Date()).getMonth())+1)+"/"+(new Date()).getDate()+"/"+(new Date()).getFullYear(),dateTo:(parseInt((new Date()).getMonth())+1)+"/"+(new Date()).getDate()+"/"+((new Date()).getFullYear()+1),curCalIdx:0,curInput:null,hideCalTO:null,init:function(){var me=this;this.div=document.getElementById(__calDivId);if(this.div==null){this.div=document.createElement("div");this.div.id=__calDivId;this.div.style.position="absolute";this.div.style.padding="8px";this.div.style.display="none";this.div.style.width="auto";this.div.style.height="auto";document.body.appendChild(this.div)}var isHotel=false;if($("input[name=checkin]").length>0){var newDateTo=new Date();var one_day=1000*60*60*24;newDateTo.setTime(newDateTo.getTime()+(one_day*330));this.dateTo=newDateTo.format("MM/dd/yyyy");isHotel=true}__calendars.push(new Calendar(0,"_checkinCal",new Date(this.dateFrom),new Date(this.dateTo)));__calendars.push(new Calendar(1,"_checkoutCal",new Date(this.dateFrom),new Date(this.dateTo)));if(isHotel){__calendars[0].bottomMsg="Select your Check-In Date Above";__calendars[1].bottomMsg="Select your Check-Out Date Above"}__calendars[0].posDateColor="#003366";__calendars[1].posDateColor="#003366";this.div.onmouseup=function(){if(__calendars[me.curCalIdx].selectedDays!=null&&__calendars[me.curCalIdx].selectedDays.length>0){var date=(parseInt(__calendars[me.curCalIdx].selectedDays[0][1])+1)+"/"+__calendars[me.curCalIdx].selectedDays[0][2]+"/"+__calendars[me.curCalIdx].selectedDays[0][0];if(me.curInput!=null){me.curInput.value=date;if(me.curInput.onchange){me.curInput.onchange()}}}};this.div.onmouseout=function(){eval("HotelCalendar.closeOnTimeout()")};this.div.onmouseover=function(){eval("HotelCalendar.clearTimeout()")};this.isInit=true},showCal:function(input,calIdx){if(!this.isInit){this.init()}var inputDate=new Date(input.value);if(inputDate.toString()=="Invalid Date"||inputDate.toString()=="NaN"){inputDate=new Date()}if(__calendars[calIdx].selectedDays==null||__calendars[calIdx].selectedDays.length==0){__calendars[calIdx].selectedDays[0]=new Array()}this.curCalIdx=calIdx;this.curInput=input;__calendars[calIdx].currDate=inputDate;__calendars[calIdx].selectedDays[0][0]=inputDate.getFullYear();__calendars[calIdx].selectedDays[0][1]=inputDate.getMonth();__calendars[calIdx].selectedDays[0][2]=inputDate.getDate();if(this.div.style.display!="none"){overlayclose(__calDivId)}if(this.div.style.display=="none"){overlay(input,__calDivId,"bottom");if(calIdx==1&&__calendars[0].selectedDays[0]!=null){__calendars[calIdx].dateFrom=new Date((parseInt(__calendars[0].selectedDays[0][1])+1)+"/"+__calendars[0].selectedDays[0][2]+"/"+__calendars[0].selectedDays[0][0])}this.div.innerHTML=__calendars[calIdx].drawCal(0)}this.div.innerHTML+="<!--[if lte IE 6.5]><iframe src='/secure/ok.aspx' class='cal-select-free'></iframe><![endif]-->";this.clearTimeout();this.hideCalTO=null},closeOnTimeout:function(){this.hideCalTO=window.setTimeout("HotelCalendar.closeCal()",1000)},clearTimeout:function(){if(this.hideCalTO!=null){window.clearTimeout(this.hideCalTO)}this.hideCalTO=null},closeCal:function(){if(document.getElementById(__calDivId)!=null){overlayclose(__calDivId)}}};jQuery.extend({historyCurrentHash:undefined,historyCallback:undefined,historyIframeSrc:undefined,historyNeedIframe:jQuery.browser.msie&&(jQuery.browser.version<8||document.documentMode<8),historyInit:function(callback,src){jQuery.historyCallback=callback;if(src){jQuery.historyIframeSrc=src}var current_hash=location.hash.replace(/\?.*$/,"");jQuery.historyCurrentHash=current_hash;if(jQuery.historyNeedIframe){if(jQuery.historyCurrentHash==""){jQuery.historyCurrentHash="#"}jQuery("body").prepend('<iframe id="jQuery_history" style="display: none;" src="javascript:false;"></iframe>');var ihistory=jQuery("#jQuery_history")[0];var iframe=ihistory.contentWindow.document;iframe.open();iframe.close();iframe.location.hash=current_hash}else{if(jQuery.browser.safari){jQuery.historyBackStack=[];jQuery.historyBackStack.length=history.length;jQuery.historyForwardStack=[];jQuery.lastHistoryLength=history.length;jQuery.isFirst=true}}jQuery.historyCallback(current_hash.replace(/^#/,""));setInterval(jQuery.historyCheck,100)},historyAddHistory:function(hash){jQuery.historyBackStack.push(hash);jQuery.historyForwardStack.length=0;this.isFirst=true},historyCheck:function(){if(jQuery.historyNeedIframe){var ihistory=jQuery("#jQuery_history")[0];var iframe=ihistory.contentDocument||ihistory.contentWindow.document;var current_hash=iframe.location.hash.replace(/\?.*$/,"");if(current_hash!=jQuery.historyCurrentHash){location.hash=current_hash;jQuery.historyCurrentHash=current_hash;jQuery.historyCallback(current_hash.replace(/^#/,""))}}else{if(jQuery.browser.safari){if(jQuery.lastHistoryLength==history.length&&jQuery.historyBackStack.length>jQuery.lastHistoryLength){jQuery.historyBackStack.shift()}if(!jQuery.dontCheck){var historyDelta=history.length-jQuery.historyBackStack.length;jQuery.lastHistoryLength=history.length;if(historyDelta){jQuery.isFirst=false;if(historyDelta<0){for(var i=0;i<Math.abs(historyDelta);i++){jQuery.historyForwardStack.unshift(jQuery.historyBackStack.pop())}}else{for(var i=0;i<historyDelta;i++){jQuery.historyBackStack.push(jQuery.historyForwardStack.shift())}}var cachedHash=jQuery.historyBackStack[jQuery.historyBackStack.length-1];if(cachedHash!=undefined){jQuery.historyCurrentHash=location.hash.replace(/\?.*$/,"");jQuery.historyCallback(cachedHash)}}else{if(jQuery.historyBackStack[jQuery.historyBackStack.length-1]==undefined&&!jQuery.isFirst){if(location.hash){var current_hash=location.hash;jQuery.historyCallback(location.hash.replace(/^#/,""))}else{var current_hash="";jQuery.historyCallback("")}jQuery.isFirst=true}}}}else{var current_hash=location.hash.replace(/\?.*$/,"");if(current_hash!=jQuery.historyCurrentHash){jQuery.historyCurrentHash=current_hash;jQuery.historyCallback(current_hash.replace(/^#/,""))}}}},historyLoad:function(hash){var newhash;hash=decodeURIComponent(hash.replace(/\?.*$/,""));if(jQuery.browser.safari){newhash=hash}else{newhash="#"+hash;location.hash=newhash}jQuery.historyCurrentHash=newhash;if(jQuery.historyNeedIframe){var ihistory=jQuery("#jQuery_history")[0];var iframe=ihistory.contentWindow.document;iframe.open();iframe.close();iframe.location.hash=newhash;jQuery.lastHistoryLength=history.length;jQuery.historyCallback(hash)}else{if(jQuery.browser.safari){jQuery.dontCheck=true;this.historyAddHistory(hash);var fn=function(){jQuery.dontCheck=false};window.setTimeout(fn,200);jQuery.historyCallback(hash);location.hash=newhash}else{jQuery.historyCallback(hash)}}}});