var ONE_SECOND = 1000;
var ONE_MINUTE = 60 * ONE_SECOND;
var ONE_HOUR = 60 * ONE_MINUTE;
var ONE_DAY = 24 * ONE_HOUR;
var ONE_WEEK = 7 * ONE_DAY;

(function() {

var slideSpeed = 20;
var slideInterval = 0;

var defaultPage = null;
var currentPage = null;
var currentDialog = null;
var currentWidth = 0;
var currentHash = location.hash;
var hashPrefix = "#_";
var pageHistory = [];
var newPageCount = 0;
var checkTimer;
var globalCancelSlideEffect = false;

// *************************************************************************************************

window.iui =
{
    showPage: function(page, backwards)
    {
        //alert('showPage: START');
        if (page)
        {
            if (currentDialog)
            {
                currentDialog.removeAttribute("selected");
                currentDialog = null;
            }

            if (hasClass(page, "dialog"))
                showDialog(page);
            else
            {
                var fromPage = currentPage;
                currentPage = page;

                if (fromPage) {
                    //alert('fromPage != null, calling setTimeout');
                    setTimeout(slidePages, 0, fromPage, page, backwards);
                }
                else
                {
                    //alert('fromPage is undefined, calling updatePage');
                    updatePage(page, fromPage);
                }
            }
        } else {
            //alert('showPage: page is undefined.  returning.');
        }
    },

    showPageById: function(pageId)
    {
        var page = $(pageId);
        if (page)
        {
            //alert('showPageById: page != null, calling showPage');
            var index = pageHistory.indexOf(pageId);
            var backwards = index != -1;
            if (backwards)
                pageHistory.splice(index, pageHistory.length);

            iui.showPage(page, backwards);
        } else {
            //alert('showPageById: page is undefined for pageId=' + pageId);
        }
    },

    showPageByHref: function(href, args, method, replace, cb)
    {
        var req = new XMLHttpRequest();
        req.onerror = function()
        {
            if (cb)
                cb(false);
        };
        
        req.onreadystatechange = function()
        {
            if (req.readyState == 4)
            {
                if (replace)
                    replaceElementWithSource(replace, req.responseText);
                else
                {
                    var frag = document.createElement("div");
                    frag.innerHTML = req.responseText;
                    iui.insertPages(frag.childNodes);
                }
                if (cb)
                    setTimeout(cb, 1000, true);
            }
        };

        if (args)
        {
            req.open(method || "GET", href, true);
            req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            req.setRequestHeader("Content-Length", args.length);
            req.send(args.join("&"));
        }
        else
        {
            req.open(method || "GET", href, true);
            req.send(null);
        }
    },
    
    insertPages: function(nodes)
    {
        var targetPage;
        for (var i = 0; i < nodes.length; ++i)
        {
            var child = nodes[i];
            if (child.nodeType == 1)
            {
                if (!child.id)
                    child.id = "__" + (++newPageCount) + "__";

                var clone = $(child.id);
                if (clone)
                    clone.parentNode.replaceChild(child, clone);
                else
                    document.body.appendChild(child);

                if (child.getAttribute("selected") == "true" || !targetPage)
                    targetPage = child;
                
                --i;
            }
        }

        if (targetPage)
            iui.showPage(targetPage);    
    },

    getSelectedPage: function()
    {
        for (var child = document.body.firstChild; child; child = child.nextSibling)
        {
            if (child.nodeType == 1 && child.getAttribute("selected") == "true")
                return child;
        }    
    }    
};

// *************************************************************************************************

addEventListener("load", function(event)
{
    var page = iui.getSelectedPage();
    if (page)
        iui.showPage(page);

    setTimeout(preloadImages, 0);
    setTimeout(checkOrientAndLocation, 0);
    checkTimer = setInterval(checkOrientAndLocation, 300);
}, false);
    
addEventListener("click", function(event)
{
    //alert('in click event listener...');
    var link = findParent(event.target, "a");
    if (link)
    {
        function unselect() { link.removeAttribute("selected"); }
        
        if (link.href != null && link.href.indexOf('javascript:') > -1) {
            var textToEval = link.href.substr(11, link.href.length);
            //alert('executing javascript: ' + textToEval);
            eval(textToEval);
        }
        else if (link.href && (link.href.indexOf('tel:') > -1))
        {
            //alert('telephone link');
            return;
        }
        else if (link.href && link.hash && link.hash != "#")
        {
            //alert('showPage=' + $(link.hash.substr(1)).value + ', link.href=' + link.href + ', link.hash=' + link.hash);
            link.setAttribute("selected", "true");
            iui.showPage($(link.hash.substr(1)));
            setTimeout(unselect, 500);
        }
        else if (link == $("backButton"))
            history.back();
        else if (link.getAttribute("type") == "submit")
            submitForm(findParent(link, "form"));
        else if (link.getAttribute("type") == "cancel")
            cancelDialog(findParent(link, "form"));
        else if (link.target == "_replace")
        {
            link.setAttribute("selected", "progress");
            iui.showPageByHref(link.href, null, null, link, unselect);
        }
        else if (!link.target)
        {
            link.setAttribute("selected", "progress");
            iui.showPageByHref(link.href, null, null, null, unselect);
        }
        else
        {
            //alert('default action');
            return;
        }
        
        event.preventDefault();        
    }
}, true);

addEventListener("click", function(event)
{
    var div = findParent(event.target, "div");
    if (div && hasClass(div, "toggle"))
    {
        div.setAttribute("toggled", div.getAttribute("toggled") != "true");
        event.preventDefault();        
    }
}, true);

function checkOrientAndLocation()
{
    if (window.innerWidth != currentWidth)
    {   
        currentWidth = window.innerWidth;
        var orient = currentWidth == 320 ? "profile" : "landscape";
        document.body.setAttribute("orient", orient);
        setTimeout(scrollTo, 100, 0, 1);
    }

    if (location.hash != currentHash)
    {
        var pageId = location.hash.substr(hashPrefix.length)
        iui.showPageById(pageId);
    }
}

function showDialog(page)
{
    currentDialog = page;
    page.setAttribute("selected", "true");
    
    if (hasClass(page, "dialog") && !page.target)
        showForm(page);
}

function showForm(form)
{
    form.onsubmit = function(event)
    {
        event.preventDefault();
        submitForm(form);
    };
    
    form.onclick = function(event)
    {
        if (event.target == form && hasClass(form, "dialog"))
            cancelDialog(form);
    };
}

function cancelDialog(form)
{
    form.removeAttribute("selected");
}

function updatePage(page, fromPage)
{
    if (!page.id)
        page.id = "__" + (++newPageCount) + "__";

    if (page.getAttribute("default") == null || page.getAttribute("default") != "true")
    {
        
        
        //alert('adding to page history, page.id=' + page.id + ', location.href=' + location.href);
    }
    location.href = currentHash = hashPrefix + page.id;
    pageHistory.push(page.id);
    
    var logo = $("logo");
    var pageTitle = $("pageTitle");
    var homeButton = $("homeButton");
    var defaultTbGreenButton = $("defaultTbGreenButton");
    var roomsFormUpdateTbGreenButton = $("roomsUpdateTbGreenButton");
    var optFilterFormUpdateTbGreenButton = $("optFilterUpdateTbGreenButton");
    if (homeButton) {
        if (page.getAttribute("showHomeButton") == "true")
        {
            homeButton.style.display = "block";
        }
        else
        {
            homeButton.style.display = "none";
        }
    }
    if (defaultTbGreenButton) {
        if (page.getAttribute("showDefaultTbButton") == "true")
        {
            defaultTbGreenButton.style.display = "block";
        }
        else
        {
            defaultTbGreenButton.style.display = "none";
        }
    }
    if (roomsFormUpdateTbGreenButton) {
        if (page.getAttribute("showRoomsFormUpdateTbButton") == "true")
        {
            roomsFormUpdateTbGreenButton.style.display = "block";
        }
        else
        {
            roomsFormUpdateTbGreenButton.style.display = "none";
        }
    }
    if (optFilterFormUpdateTbGreenButton) {
        if (page.getAttribute("Showoptfilterupdatetbbutton") == "true")
        {
            optFilterFormUpdateTbGreenButton.style.display = "block";
        }
        else
        {
            optFilterFormUpdateTbGreenButton.style.display = "none";
        }
        
    }
    if (page.id && page.id != 'home') 
    {
        logo.style.display = "none";
        pageTitle.innerHTML = page.title;
    }
    else
    {
        pageTitle.innerHTML = '';
        logo.style.display = "block";
        if (defaultTbGreenButton) {
            defaultTbGreenButton.style.display = "none";
        }
    }

    if (page.localName.toLowerCase() == "form" && !page.target)
        showForm(page);
        
    var backButton = $("backButton");
    if (backButton)
    {
        var prevPage = $(pageHistory[pageHistory.length-2]);
        //alert('prevPage=' + prevPage + ', hideBackButton=' + page.getAttribute("hideBackButton") + ', showBackButton=' + page.getAttribute("showBackButton"));
        if ((page.getAttribute("showBackButton") == "true") || (prevPage && !page.getAttribute("hideBackButton")))
        {
            backButton.style.display = "inline";
            if (page.getAttribute("backButtonText"))
            {
                //backButton.innerHTML = "Back";
                backButton.innerHTML = page.getAttribute("backButtonText");
            }
            else
            {
                if (prevPage)
                {
                    //backButton.innerHTML = "Back";
                    backButton.innerHTML = prevPage.title ? prevPage.title : defaultHcom.backButton;
                }
                else
                {
                    backButton.innerHTML = defaultHcom.backButton;
                }
            }
        }
        else
            backButton.style.display = "none";
    }    
}

function slidePages(fromPage, toPage, backwards)
{        
    var axis = (backwards ? fromPage : toPage).getAttribute("axis");
    if (axis == "y")
        (backwards ? fromPage : toPage).style.top = "100%";
    else
        toPage.style.left = "100%";

    toPage.setAttribute("selected", "true");
    scrollTo(0, 1);
    clearInterval(checkTimer);
    
    var percent = 100;
    
    if (globalCancelSlideEffect || toPage.getAttribute("slideEffect") == "false" || fromPage.getAttribute("slideEffect") == "false") {
        //percent = 0;
        
    }
    slide();
    var timer = setInterval(slide, slideInterval);

    function slide()
    {
        percent -= slideSpeed;
        if (percent <= 0)
        {
            percent = 0;
            if (!hasClass(toPage, "dialog"))
                fromPage.removeAttribute("selected");
            clearInterval(timer);
            checkTimer = setInterval(checkOrientAndLocation, 300);
            setTimeout(updatePage, 0, toPage, fromPage);
        }
    
        if (axis == "y")
        {
            backwards
                ? fromPage.style.top = (100-percent) + "%"
                : toPage.style.top = percent + "%";
        }
        else
        {
            fromPage.style.left = (backwards ? (100-percent) : (percent-100)) + "%"; 
            toPage.style.left = (backwards ? -percent : percent) + "%"; 
        }
    }
}

function preloadImages()
{
    var preloader = document.createElement("div");
    preloader.id = "preloader";
    document.body.appendChild(preloader);
}

function submitForm(form)
{
    iui.showPageByHref(form.action || "POST", encodeForm(form), form.method);
}

function encodeForm(form)
{
    function encode(inputs)
    {
        for (var i = 0; i < inputs.length; ++i)
        {
            if (inputs[i].name)
                args.push(inputs[i].name + "=" + escape(inputs[i].value));
        }
    }

    var args = [];
    encode(form.getElementsByTagName("input"));
    encode(form.getElementsByTagName("select"));
    return args;    
}

function findParent(node, localName)
{
    while (node && (node.nodeType != 1 || node.localName.toLowerCase() != localName))
        node = node.parentNode;
    return node;
}

function hasClass(self, name)
{
    var re = new RegExp("(^|\\s)"+name+"($|\\s)");
    return re.exec(self.getAttribute("class")) != null;
}

function replaceElementWithSource(replace, source)
{
    var page = replace.parentNode;
    var parent = replace;
    while (page.parentNode != document.body)
    {
        page = page.parentNode;
        parent = parent.parentNode;
    }

    var frag = document.createElement(parent.localName);
    frag.innerHTML = source;

    page.removeChild(parent);

    while (frag.firstChild)
        page.appendChild(frag.firstChild);
}

function $(id) { return document.getElementById(id); }
function ddd() { console.log.apply(console, arguments); }

})();

function submitSearchForm() {
    var f1 = document.forms["myform"];
    if (f1)
    {
        if (f1.chooseAlternateDestination) {
            f1.chooseAlternateDestination.value = 'false';
        }
        calcSearchFormYears();
        if (f1.searchType && f1.searchType.value == 'address') {
            if (f1.street1 && f1.street2) {
                if (f1.street2.value != '') {
                    f1.submit();
                } else if (f1.street2.value == '') {
                    alert('Please enter City + State or ZipCode');
                }
            } else {
                alert('Please fill out the Street Address');
            }
        } else if (f1.destination) {
            //alert('submitting, f1.destination=' + f1.destination.value);
            if (f1.destination.value == 'usertyped') {
                if (f1.usertypedcity) {
                    if (f1.usertypedcity.value != '') {
                        //alert('submitting, f1.usertypedcity=' + f1.usertypedcity.value);
                        f1.submit();
                    } else {
                        alert('Please enter a City, Landmark or Airport.');
                    }
                } else if (f1.pointName && f1.pointName != '') {
                    f1.submit();
                }
            } else {
                f1.submit();
            }
        } else if (f1.addressID) {
            f1.submit();
        } else if (f1.pointName) {
            f1.submit();
        } else {
            alert('error: destination is undefined');
        }
    } else {
        alert('f1 is null');
    }
}

function updateFromMainForm() {
    //alert('updateFromMainForm');
    var f1 = document.forms["myform"];
    var f2 = document.forms["mainSearchForm"];
    if (f1 && f2) {
        //alert('before:main-f2.usertypedcity=' + f2.usertypedcity.value + ', hidden-f1.usertypedcity=' + f1.usertypedcity.value);
        f1.destination.value = f2.destination.value;
        f1.usertypedcity.value = f2.usertypedcity.value;
        
        f1.street1.value = f2.street1.value;
        f1.street2.value = f2.street2.value;
        
        f1.CIMonth.value = f2.CIMonth.value;
        f1.CIDay.value = f2.CIDay.value;
        f1.CIYear.value = f2.CIYear.value;
        f1.COMonth.value = f2.COMonth.value;
        f1.CODay.value = f2.CODay.value;
        f1.COYear.value = f2.COYear.value;
        
        //alert('after:main-f2.CIMonth=' + f2.CIMonth.value + ', hidden-f1.CIMonth=' + f1.CIMonth.value);
        
        if (f1.elements["adults[0]"] != null && f2.elements["adults[0]"] != null) {
            f1.elements["adults[0]"].value = f2.elements["adults[0]"].value;
            //alert('after:main-f2.usertypedcity=' + f2.usertypedcity.value + ', hidden-f1.usertypedcity=' + f1.usertypedcity.value);
        }
        if (f1.elements["child[0]"] != null && f2.elements["child[0]"] != null) {
            f1.elements["child[0]"].value = f2.elements["child[0]"].value;
            //alert('after:main: child[0]=' + f1.elements["child[0]"].value);
        }
        if (f1.elements["OIdx[0].CAIdx[0]"] != null && f2.elements["OIdx[0].CAIdx[0]"] != null) {
            f1.elements["OIdx[0].CAIdx[0]"].value = f2.elements["OIdx[0].CAIdx[0]"].value;
            //alert('after:main: OIdx[0].CAIdx[0]=' + f1.elements["OIdx[0].CAIdx[0]"].value);
        }
        //alert('finished updating myform from mainSearchForm');
    } else {
        alert('f1 is null');
    }
}

function updateMyformFromMainFormForProperty() {
    //alert('updateMyformFromMainFormForProperty');
    var f1 = document.forms["myform"];
    var f2 = document.forms["mainSearchForm"];
    if (f1 && f2) {
        f1.CIMonth.value = f2.CIMonth.value;
        f1.CIDay.value = f2.CIDay.value;
        f1.CIYear.value = f2.CIYear.value;
        f1.COMonth.value = f2.COMonth.value;
        f1.CODay.value = f2.CODay.value;
        f1.COYear.value = f2.COYear.value;
        
        //alert('after:main-f2.CIMonth=' + f2.CIMonth.value + ', hidden-f1.CIMonth=' + f1.CIMonth.value);
        
        if (f1.elements["adults[0]"] != null && f2.elements["adults[0]"] != null) {
            f1.elements["adults[0]"].value = f2.elements["adults[0]"].value;
            //alert('after:main-f2.usertypedcity=' + f2.usertypedcity.value + ', hidden-f1.usertypedcity=' + f1.usertypedcity.value);
        }
        if (f1.elements["child[0]"] != null && f2.elements["child[0]"] != null) {
            f1.elements["child[0]"].value = f2.elements["child[0]"].value;
            //alert('after:main: child[0]=' + f1.elements["child[0]"].value);
        }
        if (f1.elements["OIdx[0].CAIdx[0]"] != null && f2.elements["OIdx[0].CAIdx[0]"] != null) {
            f1.elements["OIdx[0].CAIdx[0]"].value = f2.elements["OIdx[0].CAIdx[0]"].value;
            //alert('after:main: OIdx[0].CAIdx[0]=' + f1.elements["OIdx[0].CAIdx[0]"].value);
        }
        //alert('finished updating myform from mainSearchForm');
    } else {
        alert('f1 is null');
    }
}

function updateSearchFormFromRoomSubForm() {
    //alert('in updateSearchFormFromRoomSubForm');
    var mainHiddenForm = document.forms["myform"];
    var roomSubForm = document.forms["roomsSubForm"];
    if (mainHiddenForm && roomSubForm) {
        //alert('getting roomWidgetLinkElem...'); 
        var roomWidgetLinkElem = document.getElementById("mainSearchRoomWidgetLink");
        var numRooms = roomsSubFormNumRoomsSelected();
        //alert('numRooms=' + numRooms);
        var numTotalAdults = getTotalNumOfAdults();
        //alert('numTotalAdults=' + numTotalAdults);
        var numTotalChildren = getTotalNumOfChildren();
        //alert('numTotalChildren=' + numTotalChildren);
        
        // Update the Hidden Form
        var mainNumRooms = mainHiddenForm["numrooms"];
        if (mainNumRooms) {
            mainNumRooms.value = numRooms;
        } else {
            alert('ERROR: unable to find mainHiddenForm.numrooms');
        }
        
        // Update the Adult & Child info
        for (roomNum = 0; roomNum < numRooms; roomNum++) {
            var roomSubFormNumAdults = eval("document.getElementById('roomsSubFormAdultroom" + roomNum + "')");
            var hiddenFormNumAdults = eval("document.getElementById('hidden-adultroom" + roomNum + "')");
            
            if (roomSubFormNumAdults && !isNaN(roomSubFormNumAdults.value) && hiddenFormNumAdults) {
                hiddenFormNumAdults.value = roomSubFormNumAdults.value;
            } else {
                alert('ERROR: could not element=roomsSubFormAdultroom' + roomNum);
            }
            
            var roomSubFormNumChildren = eval("document.getElementById('roomsSubFormChildroom" + roomNum + "')");
            var hiddenFormNumChildren = eval("document.getElementById('hidden-childroom" + roomNum + "')");
            if (roomSubFormNumChildren && !isNaN(roomSubFormNumChildren.value) && hiddenFormNumChildren) {
                hiddenFormNumChildren.value = roomSubFormNumChildren.value;
            } else {
                alert('ERROR: could not element=roomsSubFormChildroom' + roomNum);
            }
            
            // child ages
            for (childNum = 0; childNum < 3; childNum++) {
                var roomSubFormChildAge = eval("document.getElementById('roomsSubFormOIdx[" + roomNum + "].CAIdx[" + childNum + "]')");
                var hiddenFormNumChildAge = eval("document.getElementById('hidden-OIdx[" + roomNum + "].CAIdx[" + childNum + "]')");
                if (roomSubFormChildAge && !isNaN(roomSubFormNumChildren.value) && hiddenFormNumChildAge) {
                    hiddenFormNumChildAge.value = roomSubFormChildAge.value;
                } else {
                    alert('ERROR: could not element=roomSubFormChildAge' + roomNum + ', childNum=' + childNum);
                }
            }
        }
        // Update the Link Text
        if (roomWidgetLinkElem) {
            roomWidgetLinkElem.innerHTML = numRooms + ' Room(s), ' + numTotalAdults + ' Adults(s), ' + numTotalChildren + ' Children';
        } else {
            alert('ERROR: could not find element=' + mainSearchRoomWidgetLink);
        }
        
    } else {
        alert('ERROR: could not find a form');
    }
}

function updateFromFilterSubForm() {
    //alert('in updateFromFilterSubForm');
    var f1 = document.forms["myform"];
    var f2 = document.forms["searchFilterSubForm"];
    if (f1 != null && f2 != null) {
        var updateOptionalFilterWidgetLink = document.getElementById("optionalFiltersLink");
        if (updateOptionalFilterWidgetLink) {
            var newOptionalFilterWidgetHtml = '';
            if (f1.hotelName != null && f2.hotelName != null) {
                //alert('f1.hotelName.value=' + f1.hotelName.value + ', f2.hotelName.value=' + f2.hotelName.value);
                f1.hotelName.value = f2.hotelName.value;
                if (f2.hotelName.value == '') {
                    newOptionalFilterWidgetHtml = 'Optional Filters [None Selected]';
                } else {
                    newOptionalFilterWidgetHtml = 'Optional Filters [' + f1.hotelName.value + ']:';
                }
                //alert('newOptionalFilterWidgetHtml=' + newOptionalFilterWidgetHtml);
                updateOptionalFilterWidgetLink.innerHTML = newOptionalFilterWidgetHtml;
            } else {
                //alert('f1.hotelName=' + f1.hotelName + ', f2.hotelName=' + f2.hotelName);
            }
        } else {
            //alert('error: updateOptionalFilterWidgetLink == null');
        }
    } else {
        alert('error: f1=' + f1 +', f2=' + f2);
    }
}

function PhotoDetail(url, thumbnailUrl, width, height, caption) {
    this.url = url;
    this.thumbnailUrl = thumbnailUrl;
    this.width = width;
    this.height = height;
    this.caption = caption;
}

var currentPhotoId = 0;
var maxPhotoWidth = 300;

function showPhotoById(id, propPhotos) {
    //alert('showPhotoById: id=' + id);
    if (id != null) {
        if (propPhotos) {
            //alert('showPhotoById: id=' + id + ', propPhotos.length=' + propPhotos.length);
            if (id >= 0 && id < propPhotos.length) {
                currentPhotoId = parseInt(id);
                //alert('showPhotoById: currentPhotoId=' + currentPhotoId);
                var currentPhoto = propPhotos[id];
                if (currentPhoto) {
                    showImage(currentPhoto.url, currentPhoto.caption, currentPhoto.width, currentPhoto.height);
                    // preload next photo & prev photo
                    postLoadImg(currentPhotoId-1, propPhotos);
                    postLoadImg(currentPhotoId+1, propPhotos);
                } else {
                    alert('showPhotoById: currentPhoto==null');
                }
            } else {
                alert('error: showPhotoById: outOfBounds: id=' + id + ', propPhotos.length=' + propPhotos.length);
            }
        } else {
            alert('error: showPhotoById: propPhotos=null');
        }
    } else {
        alert('error: showPhotoById: id=null');
    }
}

function postLoadImg(id, propPhotos) {
    //alert('postLoadImg: id=' + id);
    if (id != null) {
        if (propPhotos != null) {
            var idToLoad = parseInt(id);
            //alert('idToLoad=' + idToLoad);
            if (id < 0) {
                idToLoad = propPhotos.length-1;
            } else if (id >= propPhotos.length) {
                idToLoad = 0;
            }
            //alert('after id range check: idToLoad=' + idToLoad);
            if (idToLoad >= 0 && idToLoad < propPhotos.length) {
                var currentPhoto = propPhotos[idToLoad];
                if (currentPhoto != null) {
                    if (currentPhoto.url != null) {
                        //alert('calling loadImg: idToLoad=' + idToLoad + ', url=' + currentPhoto.url);
                        setTimeout(loadImg(currentPhoto.url), 0);
                    }
                } else {
                    //alert('error: currentPhoto=null, id=' + idToLoad);
                }
            } else {
                //alert('error: idToLoad is out of range: idToLoad=' + idToLoad);
            }
        } else {
            //alert('propPhotos=null');
        }
    } else {
        //alert('id=null');
    }
}
function loadImg(url) {
    //alert('loadImg: url=' + url);
    var imgHolder = new Image();
    imgHolder.src = url;
}

function showImage(imageUrl, imageCaption, imageWidth, imageHeight) {
    var imageBlock = document.images["imageBlock"];
    
    if (imageBlock) {
        //alert('showImage, url=' + imageUrl);
        imageBlock.src = '/images/p.gif'; //25x20
        
        var loadingImageBlock = document.images["loadingImageBlock"];
    
        if (loadingImageBlock) {
            loadingImageBlock.width = 25;
            loadingImageBlock.src = '/images/iphone/loading.gif'; //25x20
        } else {
            //alert('loadingImageBlock == null');
        }
        
        var newImg = new Image();
        newImg.src = imageUrl;
        newImg.onload = function() 
        {
            //alert('image finished loading...');
            imageBlock.src = imageUrl;
    
        	if (imageWidth > maxPhotoWidth || imageWidth == 0) {
        		imageBlock.width = maxPhotoWidth;
        		imageBlock.height = (imageHeight / imageWidth) * maxPhotoWidth;
        	} else {
        		imageBlock.width = imageWidth;
        		imageBlock.height = imageHeight;
        	}
        
        	if (imageHeight == 0) {
        		imageBlock.height = '/images/p.gif';
        	}
        	
        	if (imageCaption == "") {
        		imageCaption = "&nbsp;";
        	}
        	
        	if (document.getElementById("imageCaption")) {
        	    document.getElementById("imageCaption").innerHTML = imageCaption;
        	} else {
        	    //alert('imageCaption == null');
        	}
        	
        	if (loadingImageBlock) {
        	    loadingImageBlock.src = '/images/p.gif'; //25x20
        	    loadingImageBlock.width = 1;
        	    //loadingImageBlock.height = 0;
        	}
    	}
    } else {
        //alert('imageBlock == null');
    }
}

function gotoPrevPhoto(propPhotos) {
    if (currentPhotoId != null && propPhotos != null) {
        var photoId = parseInt(currentPhotoId - 1);
        //alert('gotoPrevPhoto: after-1; photoId=' + photoId);
        if (photoId < 0) {
            photoId = parseInt(propPhotos.length - 1);
            //alert('gotoPrevPhoto: reset: photoId=' + photoId);
        }
        //alert('gotoPrevPhoto: calling showPhotoById: photoId=' + photoId);
        showPhotoById(photoId, propPhotos);
    } else {
        alert('error: gotoPrevPhoto: photoId=null');
    }
}

function gotoNextPhoto(propPhotos) {
    if (currentPhotoId != null && propPhotos != null) {
        var photoId = parseInt(currentPhotoId + 1);
        //alert('gotoNextPhoto: after+1; photoId=' + photoId);
        if (photoId > (propPhotos.length - 1)) {
            photoId = parseInt(0);
            //alert('gotoNextPhoto: reset: photoId=' + photoId);
        }
        //alert('gotoNextPhoto: calling showPhotoById: photoId=' + photoId);
        showPhotoById(photoId, propPhotos);
    } else {
        alert('error: gotoNextPhoto: photoId=null');
    }
}

function updateSearchFormDestId(destId) {
    //alert('in updateSearchFormDestId: destId=' + destId);
    var f1 = document.forms["myform"];
    if (f1 != null) {
        if (f1.destination) {
            //alert('updated destination=' + f1.destination.value);
            f1.destination.value = destId;
        }
    } else {
        //alert('could not find form: myform');
    }
}

function updateSearchFormAddressId(addressId) {
    //alert('in updateSearchFormAddressId: addressId=' + addressId);
    var f1 = document.forms["myform"];
    if (f1 != null) {
        if (f1.addressID) {
            //alert('updated addressID=' + f1.addressID.value);
            f1.addressID.value = addressId;
        }
    } else {
        //alert('could not find form: myform');
    }
}

function submitStep1Form(userTypeParam) {
    var f1 = document.forms["bookform"];
    if (f1 != undefined) {
        //alert('found bookform, setting userType=' + userTypeParam);
        f1.userType.value = userTypeParam;
        f1.submit();
    } else {
        alert('bookform is undefined');
    }
}

// Get the previous page of search results
function previous() {
    if (document.myform.paging && document.myform.paging.value > 1) {
        //alert('paging=' + document.myform.paging.value);
        document.myform.paging.value--;
    }
    if (document.myform.chooseAlternateDestination) {
        document.myform.chooseAlternateDestination.value = 'false';
    }
    document.myform.submit();
}

// Get the next page of search results
function next() {
    if (document.myform.paging) {
        //alert('paging=' + document.myform.paging.value);
        document.myform.paging.value++;
    }
    if (document.myform.chooseAlternateDestination) {
        document.myform.chooseAlternateDestination.value = 'false';
    }
    document.myform.submit();
}

// Goto a specific page of search results
function toPage(pageNum) {
    if (document.myform.paging) {
        //alert('paging=' + document.myform.paging.value);
        document.myform.paging.value = pageNum;
    }
    if (document.myform.chooseAlternateDestination) {
        document.myform.chooseAlternateDestination.value = 'false';
    }
    document.myform.submit();
}

function resolveMultipleDestinations() {
    document.myform.chooseAlternateDestination.value = 'true';
    document.myform.submit();
}

// Rooms.js
function getTotalNumOfAdults() {
    var totalNumOfAdults = 0;
    var numOfRooms = roomsSubFormNumRoomsSelected();
    for (roomNum = 0; roomNum < numOfRooms; roomNum++) {
        var numOfAdultsElem = eval("document.getElementById('roomsSubFormAdultroom" + roomNum + "')");
        if (numOfAdultsElem && !isNaN(numOfAdultsElem.value)) {
            totalNumOfAdults += parseInt(numOfAdultsElem.value);
        } else {
            alert('ERROR: could not element=roomsSubFormAdultroom' + roomNum);
        }
    }
    return totalNumOfAdults;
}

function getTotalNumOfChildren() {
    var totalNumOfChildren = 0;
    var numOfRooms = roomsSubFormNumRoomsSelected();
    for (roomNum = 0; roomNum < numOfRooms; roomNum++) {
        var numOfChildrenElem = eval("document.getElementById('roomsSubFormChildroom" + roomNum + "')");
        if (numOfChildrenElem && !isNaN(numOfChildrenElem.value)) {
            totalNumOfChildren += parseInt(numOfChildrenElem.value);
        } else {
            alert('ERROR: could not element=roomsSubFormChildroom' + roomNum);
        }
    }
    return totalNumOfChildren;
}

function roomsSubFormNumRoomsSelected(){
    var roomsSelected = document.getElementById("roomsSubFormNumRooms").value;
    return roomsSelected;
}

function isGroup() {
    var roomsSelected = document.getElementById("roomsSubFormNumRooms").value;
    return (roomsSelected > totalPossibleRooms);
}

/* Shows the room info lines with titles and inputs for num adults and num children */
function showRooms(roomPrefix) {
    roomsSelected = new Number(roomsSubFormNumRoomsSelected())-1;//make zero-based
    for (row = 0; row < totalPossibleRooms; row++) {
        if (row <= roomsSelected && !isGroup()) {
            eval("document.getElementById('" + roomPrefix + row + "').style.display = ''");
        } else {
            eval("document.getElementById('" + roomPrefix + row + "').style.display = 'none'");
        }
    }
}
function updateRoomsSubFormView() {
    var roomDiv0 = document.getElementById("roomsSubFormRoom0");
    if (roomDiv0) {
        showRooms('roomsSubFormRoom');
        for (var i = 0 ; i < totalPossibleRooms ; ++i) {
            showRoomInfo(i, 'roomsSubFormRoom' + i + 'age');
        }
        //showAgeTitles();
    } else {
        alert('ERROR: could not find divId=adultroom0');
    }
    updateAdultChildDropdowns();
}

/*
    Control the display of the room information. Display the correct title on the row for the specified room.
    Display the child count dropdown. Display the column titles and the room rows in the child age section.
    When I say "display" here, I mean display or don't display depending on varioius conditions.

    @param roomId identifies the room the children belong to (e.g. 1, 2, 3)
    @param ageRowName the age row id/name that for the room (e.g. room1ages, room2ages, etc)
    @param ageItemPrefix the prefix name for each room/age combination (e.g. room1age1 - room1age is the prefix)

*/
function showRoomInfo(roomId, ageItemPrefix) {
    var childBoxPrefix = 'roomsSubFormChildroom';
    //alert('looking for elementId=' + childBoxPrefix + roomId);
    var childSelectedElem = document.getElementById(childBoxPrefix + roomId);

    // turn on/off child age dropdowns
    if (childSelectedElem) {
        showAges(roomId, childBoxPrefix+roomId, ageItemPrefix);
    } else {
        alert('ERROR: could not find ' + childBoxPrefix + roomId);
    }
}

/*
    Displays/hides the age selection for each child in each room

    @param childBoxName the name of the selection box for the number of children for a room (e.g. childRoom1, childRoom2, etc)
    @param ageItemPrefix the prefix name for each room/age combination (e.g. room1age1 - room1age is the prefix)
*/
function showAges(roomId, childBoxName, ageItemPrefix) {
    // get number of children from Child Drop Down
    var childSelected = document.getElementById(childBoxName).value;
    childSelected = new Number(childSelected) - 1; //make zero-based
    
    for (row = 0; row < totalPossibleChildren; row++) {
        var elem = document.getElementById(ageItemPrefix + row);
        if (elem) {
            var ageFormElement = "roomsSubFormOIdx["+roomId+"].CAIdx["+row+"]";
            if (row <= childSelected && roomType == "hotel") {
                elem.style.display = "";
                document.getElementById(ageFormElement).disabled = false;
            } else {
                elem.style.display = "none";
                document.getElementById(ageFormElement).disabled = true;
            }
        }
    }
}

/*    update the numbers in the dropdowns for number of adults and number of children */
function updateAdultChildDropdowns() {
    var adults;
    var children;
    roomsSelected = new Number(roomsSubFormNumRoomsSelected())-1;//make zero-based

    var roomDiv0 = document.getElementById("roomsSubFormRoom0");
    if (roomDiv0) {
        for (j = 0 ; j < totalPossibleRooms ; ++j) {
            adults = document.getElementById("roomsSubFormAdultroom" + j);
            updateAdultDropdown(adults, 1, roomMaxGuests);
            
            children = document.getElementById("roomsSubFormChildroom" + j);
            updateChildDropdown(children, roomMaxChildren);

            if (j <= roomsSelected && !isGroup()) {
                adults.disabled=false;
                children.disabled=false;
            } else {
                adults.disabled=true;
                children.disabled=true;
            }
        }
    }
}

/* update one dropdown for the adult count for one room 
   @param adults the select box form field for which we are changing the options 
   @param limit the highest number allowed in the dropdown (1 is lowest)
*/
function updateAdultDropdown(adults, minimum, limit) {
    if (adults && adults.options.length != limit) {
        var selectedAdult = adults.value;
        if (selectedAdult > limit || selectedAdult < minimum) {
            selectedAdult = minimum * 2;
        }
        var newSelectedIndex = 1;
        adults.options.length = limit-minimum;
        for (i = minimum ; i <= limit; ++i) {
            adults.options[i-minimum] = new Option(i, i);
            if (i == selectedAdult) {
                newSelectedIndex = i-minimum;
            }
        }
        adults.selectedIndex = newSelectedIndex;
    }
}

/* update one dropdown for the children count for one room 
   @param children the select box form field for which we are changing the options 
   @param limit the highest number allowed in the dropdown (0 is lowest)
*/
function updateChildDropdown(children, limit) {
    if (children && children.options.length != limit + 1) {
        var selectedChild = children.selectedIndex;
        if (selectedChild > limit) {
            selectedChild = 0;
        }
        children.options.length = limit + 1;
        for (i = 0 ; i <= limit; ++i) {
            children.options[i] = new Option(i, i);
        }
        children.selectedIndex = selectedChild;
    }
}

function updateTermsAgreementStatus() {
    var termsAgreementElem = document.getElementById("termsAgreementToggle");
    var f1 = document.forms["bookform"];
    if (termsAgreementElem) {
        if (f1) {
            if (termsAgreementElem.getAttribute("toggled") == "true") {
                //alert('item is toggled true');
                if (f1.termsAndConditionsAccepted) {
                    //alert('before: f1.termsAndConditionsAccepted.value=' + f1.termsAndConditionsAccepted.value);
                    f1.termsAndConditionsAccepted.value = 'true';
                    //alert('after: f1.termsAndConditionsAccepted.value=' + f1.termsAndConditionsAccepted.value);
                } else {
                    alert('f1.termsAndConditionsAccepted is undefined');
                }
            } else {
                //alert('termsAgreementToggle: toggled==false');
                if (f1.termsAndConditionsAccepted) {
                    //alert('before: f1.termsAndConditionsAccepted.value=' + f1.termsAndConditionsAccepted.value);
                    f1.termsAndConditionsAccepted.value = 'false';
                    //alert('after: f1.termsAndConditionsAccepted.value=' + f1.termsAndConditionsAccepted.value);
                } else {
                    alert('f1.termsAndConditionsAccepted is undefined');
                }
            }
        } else {
            alert('f1 is undefined');
        }
    } else {
        alert('termsAgreementToggle not found');
    }
}

function calcSearchFormYears() {
    //alert('in calcSearchFormYears...');
    var f1 = document.forms["myform"];
    var currentDate = new Date();
    f1.CIYear.value = getYear(f1.CIMonth.value, f1.CIDay.value);
    f1.COYear.value = getYear(f1.COMonth.value, f1.CODay.value);
    //alert('CIYear=' + f1.CIYear.value + ', COYear=' + f1.COYear.value);
}

// Gets year depending on month & day; month & day < today = next year, else this year
// month is 0 based
function getYear(month, day) {
    var year;
    var currentDate = new Date();
    var testDate = new Date();
    testDate.setMonth(month - 1);
    testDate.setDate(day);
    //alert('currentDate=' + currentDate.toString());
    //alert('testDate=' + testDate.toString());
    if (currentDate.getTime() > testDate.getTime()) {
        year = currentDate.getFullYear() + 1;
    } else {
        year = currentDate.getFullYear();
    }
    //alert('year=' + year);
    return year;
}

function autoSelectMainSearchCODate() {
    //alert('in autoSelectMainSearchCODate');
    var f = document.forms["mainSearchForm"];
    if (f) {
        if (f.CIMonth && f.CIDay && f.COMonth && f.CODay) {
            //alert('CIMonth=' + f.CIMonth.value + ', CIDay=' + f.CIDay.value);
            //alert('COMonth=' + f.COMonth.value + ', CODay=' + f.CODay.value);
        }
        if (f.CIMonth.value != '-1' && f.CIDay.value != '-1'&& f.COMonth.value == '-1' && f.CODay.value == '-1') {
            var ciDate = new Date();
            ciDate.setMonth(f.CIMonth.value - 1);
            ciDate.setDate(f.CIDay.value);
            ciDate.setYear(getYear(f.CIMonth.value, f.CIDay.value));
            //alert('mainSearchForm: ciDate=' + ciDate.toString());
            var ciDateInMs = ciDate.getTime();
            var coDateInMs = ciDateInMs + (2 * ONE_DAY);
            var coDate = new Date(coDateInMs);
            //alert('mainSearchForm: coDate=' + coDate.toString());
            setMainSearchCOMonth(coDate.getMonth() + 1);
            setMainSearchCODay(coDate.getDate());
        } else {
            //alert('form is incomplete');
        }
    } else {
        alert('mainSearchForm is undefined');
    }
}

// Month is 1-12 based
function setMainSearchCOMonth(month) {
    //alert('setMainSearchCOMonth: month=' + month);
    var f = document.forms["mainSearchForm"];
    if (f) {
        for (var i = 0; i < f.COMonth.length; i++) {
            if (f.COMonth.options[i].value == month) {
                f.COMonth.options[i].selected = true;
                break;
            }
        }
    }
}

// day is from 1-31
function setMainSearchCODay(day) {
    //alert('setMainSearchCODay: day=' + day);
    var f = document.forms["mainSearchForm"];
    if (f) {
        for (var i = 0; i < f.CODay.length; i++) {
            if (f.CODay.options[i].value == day) {
                f.CODay.options[i].selected = true;
                break;
            }
        }
    }
}

function submitReservationsForm() {
    //alert('in reservationsForm...');
    var f1 = document.forms["reservationsForm"];
    if (f1) {
        if (f1.LoginName && f1.BookingId && f1.ccnumber) {
            //alert('submitting, f1.destination=' + f1.destination.value);
            if (f1.LoginName.value == '') {
                alert('Please enter the Last Name.');
            } else {
                if (f1.BookingId.value == '' && f1.ccnumber.value == '') {
                    alert('Booking # or Credit Card # is missing');
                } else {
                    f1.submit();
                }
            }
        } else {
            alert('error: LoginName or BookingId or ccnumber is undefined');
        }
    } else {
        alert('f1 is null');
    }
}

function resolveMultipleDestinations() {
    if (document.myform && document.myform.chooseAlternateDestination) {
        document.myform.chooseAlternateDestination.value = true;
        document.myform.submit();
    }
}

function setSearchByDestination() {
    //alert('setSearchByDestination');
    var f1 = document.forms["myform"];
    var f2 = document.forms["mainSearchForm"];
    if (f1 && f2 && f1.searchType) {
        f1.searchType.value = '';
        if (f1.street1 && f1.street2 && f2.street1 && f2.street2) {
            f1.street1.value = '';
            f1.street2.value = '';
            f2.street1.value = '';
            f2.street2.value = '';
        }
    }
    var mainSearchDestIntroElem = document.getElementById("mainSearchDestIntro");
    if (mainSearchDestIntroElem != null) {
        mainSearchDestIntroElem.style.display = "block";
    }
    var mainSearchAddressIntroElem = document.getElementById("mainSearchAddressIntro");
    if (mainSearchAddressIntroElem != null) {
        mainSearchAddressIntroElem.style.display = "none";
    }
    var mainSearchFormDestFieldElem = document.getElementById("mainSearchFormDestField");
    if (mainSearchFormDestFieldElem != null) {
        mainSearchFormDestFieldElem.style.display = "block";
    }
    var mainSearchFormStreet1FieldElem = document.getElementById("mainSearchFormStreet1Field");
    if (mainSearchFormStreet1FieldElem != null) {
        mainSearchFormStreet1FieldElem.style.display = "none";
    }
    var mainSearchFormStreet2FieldElem = document.getElementById("mainSearchFormStreet2Field");
    if (mainSearchFormStreet2FieldElem != null) {
        mainSearchFormStreet2FieldElem.style.display = "none";
    }
    var mainSearchFormStreet2TextElem = document.getElementById("mainSearchFormStreet2Text");
    if (mainSearchFormStreet2TextElem != null) {
        mainSearchFormStreet2TextElem.style.display = "none";
    }

}

function setSearchByAddress() {
    //alert('setSearchByAddress');
    var f1 = document.forms["myform"];
    if (f1 && f1.searchType) {
        f1.searchType.value = 'address';
        //alert('f1.searchType.value=' + f1.searchType.value);
    }
    var mainSearchDestIntroElem = document.getElementById("mainSearchDestIntro");
    if (mainSearchDestIntroElem != null) {
        mainSearchDestIntroElem.style.display = "none";
    }
    var mainSearchAddressIntroElem = document.getElementById("mainSearchAddressIntro");
    if (mainSearchAddressIntroElem != null) {
        mainSearchAddressIntroElem.style.display = "block";
    }
    var mainSearchFormDestFieldElem = document.getElementById("mainSearchFormDestField");
    if (mainSearchFormDestFieldElem != null) {
        mainSearchFormDestFieldElem.style.display = "none";
    }
    var mainSearchFormStreet1FieldElem = document.getElementById("mainSearchFormStreet1Field");
    if (mainSearchFormStreet1FieldElem != null) {
        mainSearchFormStreet1FieldElem.style.display = "block";
    }
    var mainSearchFormStreet2FieldElem = document.getElementById("mainSearchFormStreet2Field");
    if (mainSearchFormStreet2FieldElem != null) {
        mainSearchFormStreet2FieldElem.style.display = "block";
    }
    var mainSearchFormStreet2TextElem = document.getElementById("mainSearchFormStreet2Text");
    if (mainSearchFormStreet2TextElem != null) {
        mainSearchFormStreet2TextElem.style.display = "block";
    }
}

function selectDefaultChildAge(roomIndex) {
    var numOfChildrenId = "roomsSubFormChildroom" + roomIndex;
    // get # of children
    var numOfChildrenElem = document.getElementById(numOfChildrenId);
    if (numOfChildrenElem) {
        //alert('numOfChildrenElem.value=' + numOfChildrenElem.value);
        // set the default age to 1 for each child
        var numOfChildren = parseInt(numOfChildrenElem.value);
        //alert('numOfChildren=' + numOfChildren);
        for (var i = 0; i < numOfChildren; i++) {
            var childAgeId = 'roomsSubFormOIdx[' + roomIndex + '].CAIdx[' + i + ']';
            //alert('searching for childAgeId=' + childAgeId);
            var childAgeElem = document.getElementById(childAgeId);
            if (childAgeElem) {
                //alert('found id=' + childAgeId + ', childAgeElem=' + childAgeElem);
                childAgeElem.value = 1;
            }
        }
    }
}

function submitSignInForm(langId) {
    var f1 = document.forms["signInForm"];
    if (f1) {
        if (f1.login && f1.login.value == '') {
            if (langId == 'en') {
                alert('Please enter an Email Address');
            } else {
                alert('Please enter an Email Address');
            }
        } else if (f1.password && f1.password.value == '') {
            if (langId == 'en') {
                alert('Please enter a Password');
            } else {
                alert('Please enter a Password');
            }
        } else {
            f1.submit();
        }
    } else {
        alert('Error: cannot find signInForm');
    }
}

function submitForgotPasswordForm(langId) {
    var f1 = document.forms["forgotPasswordForm"];
    if (f1) {
        if (f1.email && f1.email.value == '') {
            if (langId == 'en') {
                alert('Please enter an Email Address');
            } else {
                alert('Please enter an Email Address');
            }
        } else {
            f1.submit();
        }
    } else {
        alert('Error: cannot find forgotPasswordForm');
    }
}

function selectSortBy(sortByMethod) {
    var f1 = document.forms["myform"];
    if (f1) {
        if (f1.sortBy) {
            f1.sortBy.value = sortByMethod;
        }
        if (document.myform.chooseAlternateDestination) {
            document.myform.chooseAlternateDestination.value = 'false';
        }
        f1.submit();
    }
}

function selectLandmark(landmarkDestId) {
    //alert('landmarkDestId=' + landmarkDestId);
    var f1 = document.forms["myform"];
    if (f1) {
        if (f1.newLandmarkDestID && f1.sortBy) {
            f1.newLandmarkDestID.value = landmarkDestId;
            f1.sortBy.value = 'PROXIMITY';
        }
        if (document.myform.chooseAlternateDestination) {
            document.myform.chooseAlternateDestination.value = 'false';
        }
        f1.submit();
    }
}

function setCountry(country) {

	if (country == null || country.length < 0) {
		return false;
	}        
    var target = window.location.protocol + '//' + window.location.hostname;
    if (window.location.port != null) {
    	target += ':' + window.location.port;
    }
    target += '/?requestedCountry=' + country; 
    window.location = target;
    return true;
}

function setCurrency(currency) {
        
    var target = window.location.href;
    var curIndex = target.indexOf('currency');
	var anchorIndex = target.indexOf('#');
	
	var trailer = '';

    if ( curIndex > 0) 
    {
        if (curIndex + 12 < target.length) {
                trailer = target.substring(curIndex+12);
        }
        target = target.substr(0, curIndex-1);
    } else if ( anchorIndex > 0 ) {
    	trailer = target.substr(anchorIndex);
    	target = target.substr(0, anchorIndex);
    }
    if (target.indexOf('?') > 0) {
        target += '&currency=' + currency;
    } else {
        target += '?currency=' + currency;
    }
    target += trailer;
    window.location = target;
}
