﻿
function beginHotelNameSearch(parEl, locId, firstCharsInputted) {
    var locationId = locId.value;
    var firstChars = firstCharsInputted.value;
    if (parEl && (locationId && locationId > 0) && (firstChars && firstChars.length >= 3)) {
        if (typeof (hns) === 'undefined') { hns = new hotelNameSearch('hns'); }
        hns.beginRequest(parEl, parseInt(locationId), firstChars);
    } else if (typeof (hns) != 'undefined') {
        hns.hideDisplay(true);
    }   
}

function hotelNameSearch(instanceName) {    

    this.ajaxObj = null;
    this.parentElement = null;
    this.locationNodeId = null;
    this.firstCharacters = null;
    this.hotelsArray = null;
    this.instanceName = instanceName;

    this.beginRequest = function(parentElement, locationNodeId, firstCharacters) {
        this.parentElement = parentElement;
        this.attachOnBlurEvent();
        if (locationNodeId > 0 && firstCharacters.length > 0) {
            if ((this.firstCharacters === null) || this.firstCharacters.substr(0, 3) != firstCharacters.substr(0, 3)) {
                //SUBMIT INITIAL REQUEST *OR* RESUBMIT AJAX REQUEST AS FIRST 3 CHARS HAVE CHANGED                
                this.locationNodeId = locationNodeId;
                this.firstCharacters = firstCharacters;
                this.sendAjaxChildRequest();
            } else {
                //FILTER hotelsArray BASED ON MORE SPECIFIC SEARCH CHARACTERS RATHER THAN MAKING ADDITIONAL DB CALLS
                this.locationNodeId = locationNodeId;
                this.firstCharacters = firstCharacters;
                this.addHotelsToDOM()
            }
        }
    }

    this.endRequest = function() {
        this.ajaxObj = null;
        CollectGarbage()
    }

    this.attachOnBlurEvent = function() {
        var instance = this;
        $('hotelname').onblur = function() { instance.hideDisplay(); }        
    }

    this.sendAjaxChildRequest = function() {
        this.ajaxObj = this.createAjaxObj();
        var instance = this;
        this.ajaxObj.onreadystatechange = function() {
            var hotels = null;
            if (this.readyState === 4) {
                if (this.status === 200) {
                    if (this.responseXML) {
                        hotels = this.responseXML.getElementsByTagName('Hotel');
                        instance.hotelsArray = null;
                        instance.hotelsArray = new Array();
                        for (var i = 0; i < hotels.length; i++) {
                            var hotelName = hotels[i].firstChild.nodeValue;
                            var globalPropertyNodeId = hotels[i].getAttribute('GlobalPropertyNodeId');
                            instance.hotelsArray.push(hotelName + '|' + globalPropertyNodeId);
                        }
                    }
                    instance.addHotelsToDOM();
                }
            }
        }
        this.ajaxObj.open('GET', '/utility/hotelnamesearch.aspx?locationnodeid=' + this.locationNodeId + '&firstcharacters=' + this.firstCharacters + '&cachekiller=' + this.cacheKiller(), true);
        this.ajaxObj.send('');
    }

    /*UTILITY FUNCTIONS*/
    this.addHotelsToDOM = function() {
        var instance = this;
        if (this.hotelsArray != null) {
            var filteredArray = new Array();
            filteredArray = this.hotelsArray.filter(
            //THIS INLINE FUNCTION IS PASSED INTO filter AS A PARAMETER AND RETURNS
            //A BOOLEAN DICTATING WHICH ITEMS TO RETURN IN TO THE filteredArray
                function(hotel) {
                    var len = instance.firstCharacters.length;
                    if (hotel.substr(0, len).toUpperCase() === instance.firstCharacters.toUpperCase()) {
                        return hotel;
                    }
                }
            );
            if (filteredArray.length > 0) {
                this.clearListItems();
                for (var i = 0; i < filteredArray.length; i++) {
                    var hotelName = filteredArray[i].split('|')[0];
                    var globalPropertyNodeId = filteredArray[i].split('|')[1];
                    var aId = 'propertyid_' + (i + 1);
                    var liId = (i + 1);
                    var aElement = this.addAnchor('/hotels/hoteldescription.aspx?globalpropertyid=' + globalPropertyNodeId, hotelName, aId)
                    var liElement = this.addPageElement(this.parentElement, 'li', '', aElement, 'lipropertyid_' + liId);
                    aElement.setAttribute('onfocus', this.instanceName + '.hightlightRow(' + liId + ', ' + globalPropertyNodeId + ')');
                    aElement.setAttribute('onblur', this.instanceName + '.unHightlightRow(' + liId + ', ' + globalPropertyNodeId + ')');
                }
                if (this.parentElement) {
                    this.parentElement.style.display = 'block';
                }
            } else {
                instance.hideDisplay();
            }
        }
    }

    this.addPageElement = function(parent, tagName, text, value, id) {
        var element = document.createElement(tagName);
        if (value.length > 0) {
            element.innerHTML = text;
            element.value = value;
        } else {
            element.appendChild(value);
        }
        if (id && id.length > 0) {
            element.setAttribute('id', id)
        }
        parent.appendChild(element);
        return element;
    }

    this.clearListItems = function() {
        this.parentElement.innerHTML = '';
    }

    this.addAnchor = function(url, linkText, id) {
        var element = document.createElement('a');
        if (id.length > 0) {
            element.setAttribute('id', id);            
        }
        element.href = url;
        element.innerHTML = linkText;
        return element;
    }
    
    this.createAjaxObj = function() {
        if (window.XMLHttpRequest) {
            return new XMLHttpRequest();
        } else if (window.ActiveXObject) {
            return new ActiveXObject('Microsoft.XMLHTTP');
        } else {
            return;
        }
    }
    
    this.cacheKiller = function() {
        var now = new Date();
        return now.getMilliseconds();
    }

    this.hideDisplay = function(overrideBrowserDetection) {
        if (overrideBrowserDetection || (BrowserDetect && BrowserDetect.browser === 'Explorer' && BrowserDetect.version === 8)) {
            if (document.activeElement.id.substr(0, 11) != 'propertyid_') {
                this.parentElement.innerHTML = '';
                this.parentElement.style.display = 'none';
            }
        }        
    }

    this.highlightHotel = function(globalPropertyNodeId) {
        if (getElement('prop_' + globalPropertyNodeId)) {
            getElement('prop_' + globalPropertyNodeId).style.backgroundColor = '#ffebd6';
            getElement('prop_' + globalPropertyNodeId).style.border = 'solid 1px #ffb261';
        }
    }

    this.unHighlightHotel = function(globalPropertyNodeId) {
        if (getElement('prop_' + globalPropertyNodeId)) {
            getElement('prop_' + globalPropertyNodeId).style.backgroundColor = 'transparent';
            getElement('prop_' + globalPropertyNodeId).style.border = 'solid 1px #fff';
        }
    }

    this.hightlightRow = function(liId, globalPropertyNodeId) {
        $('lipropertyid_' + liId).style.backgroundColor = '#ffd1aa';
        this.highlightHotel(globalPropertyNodeId);
    }
    this.unHightlightRow = function(liId, globalPropertyNodeId) {
        $('lipropertyid_' + liId).style.backgroundColor = 'white';
        this.hideDisplay();
        this.unHighlightHotel(globalPropertyNodeId);
    }

    if (!Array.prototype.filter) {
        //CHECKS FOR EXISTENCE OF AND PROTOTYPES .filter() FUNCTION TO Array OBJECT
        Array.prototype.filter = function(fun /*, thisp*/) {
            //THE filter FUNCTION LOOPS THROUGH EACH ITEM IN THE ARRAY AND RETURNS 
            //AN ARRAY OF ITEMS RETURNING TRUE FROM THE FUNCTION PARAMETER fun.
            var len = this.length;
            if (typeof fun != 'function') {
                throw new TypeError();
            }
            var res = new Array();
            var thisp = arguments[1];
            for (var i = 0; i < len; i++) {
                if (i in this) {
                    var val = this[i]; // in case fun mutates this
                    if (fun.call(thisp, val, i, this)) {
                        res.push(val);
                    }
                }
            }
            return res;
        }
    }
    if (window.addEventListener) {
        //window.addEventListener('load', function() { this.init(); }, false);
        window.addEventListener('unload', function() { this.endRequest(); }, false);
    } else if (window.attachEvent) {
        //window.attachEvent('onload', this.init);
        window.attachEvent('onunload', this.endRequest);
    } else {
        //window.onload = function() { this.init() };
        window.onunload = function() { this.endRequest(); };
    }    
}

function $() {
    var elements = new Array();
    for (var i = 0; i < arguments.length; i++) {
        var element = arguments[i];
        if (typeof element === 'string')
            element = document.getElementById(element);
        if (arguments.length === 1)
            return element;
        elements.push(element);
    }
    return elements;
}