function getDimensions(elm) {
    var box =
   {
       x: 0, y: 0, w: 0, h: 0
   }
   ;
    if (document.getBoxObjectFor) {
        var boxRef = document.getBoxObjectFor(elm);
        box.x = boxRef.x;
        box.y = boxRef.y;
        box.w = boxRef.width;
        box.h = boxRef.height;
    }
    else if (elm.getBoundingClientRect) {
        var rxIE50 = /MSIE 5\.0/g;
        var boxRef = elm.getBoundingClientRect();
        box.x = boxRef.left;
        box.y = boxRef.top;
        box.w = (boxRef.right - boxRef.left);
        box.h = (boxRef.bottom - boxRef.top);
        if (document.compatMode && document.compatMode != 'BackCompat') {

            box.x += document.documentElement.scrollLeft - 2;
            box.y += document.documentElement.scrollTop - 2;
        }
        else if (!gClientIsIE5) {
            box.x += document.body.scrollLeft - 2;
            box.y += document.body.scrollTop - 2;
        }
    }
    else {
        box.w = elm.offsetWidth;
        box.h = elm.offsetHeight;
        while (elm) {
            box.x += elm.offsetLeft;
            box.y += elm.offsetTop;
            if (elm.offsetParent)
                elm = elm.offsetParent;
            else
                break;
        }
    }
    var cc;
    if (cc = document.getElementById('bodyconstraint'))
        box.x -= cc.offsetLeft;
    return box;
}

var DOM =
{
    isParentOf: function (parentElm, contextElm) {
        while (contextElm && (contextElm != parentElm))
            contextElm = contextElm.parentNode;
        return (contextElm == parentElm);
    }
   ,
    getParentOrSelf: function (contextElm, nodeName) {
        nodeName = nodeName.toLowerCase();
        while (contextElm.nodeName.toLowerCase() != nodeName && contextElm.parentNode)
            contextElm = contextElm.parentNode;
        return contextElm;
    }
   ,
    addClass: function (elm, className) {
        elm.className += ' ' + className;
    }
   ,
    removeClass: function (elm, className) {
        var classMatch = new RegExp('\\b' + className + '\\b', 'g');
        if (classMatch.test(elm.className))
            elm.className = elm.className.replace(classMatch, ' ');
    }
}
;

var gClientIsGecko = (window.controllers) ? true : false;
var gClientIsOpera = (window.opera) ? true : false;
var gClientIsIE = (document.all && !gClientIsOpera) ? true : false;
var gClientIsIE5 = (gClientIsIE && / MSIE 5\.0 /.test(navigator.appVersion)) ? true : false;
var gClientIsMac = (/Mac/.test(navigator.appVersion)) ? true : false;

function SloppyRegExp(matchOn, mods) {
    var cm, matched, upper, i, realMatch = '', sub = b25.Bkhtl.sub;
    for (var c = 0; c < matchOn.length; c++) {
        matched = false;
        upper = isUpperCase(matchOn.charAt(c));
        cm = matchOn.charAt(c).toLowerCase();
        for (i in sub) {
            if (sub[i].indexOf(cm) != -1) {
                cm = '[' + sub[i] + ']';
                matched = true;
                break;
            }
        }
        if (upper)
            cm = cm.toUpperCase();
        realMatch += cm + ' ?';
    }
    return new RegExp('(' + realMatch + ')', mods);
}

function isUpperCase(text) {
    return (text == text.toUpperCase());
}


function highlightSloppy(text, matchOn) {
    var sloppyMatch = SloppyRegExp(matchOn, 'i');
    if (sloppyMatch.test(text)) {
        var hlss = sloppyMatch.exec(text)[1];
        return text.replace(sloppyMatch, hlss);
    }
    else
        return text;
}

if (!b25)
    var b25 =
{
}
;
b25.Bkhtl =
{
    sub: [
   'aàáâãäåæaaa',
   'iìíîïiii',
   'eèéêëeeeee',
   'oòóôõöooo',
   'uyùúûüýuuuuu',
   ' ?'
   ]
};
//============== City ajax ==============================
function cityAjax(name, paddingLeft, relPath) {
    //--------- This is also necessary element to find out the object for dynamically create div
    this.padLeft = paddingLeft;
    this.name = name;
    this.BS_URI = "";
    this.showNotFound = true;
    this.msgNotFound = "No matching results.";
    this.allowOthers = false;

    this.BS_TIMEOUT = 100;
    this.BS_INITIALIZED = false;
    this.request = null;
    this.timeout = false;
    this.element = null;
    this.popup = null;
    this.append = null;
    this.popupActive = false;
    this.lastValue = '';
    this.relPath = (relPath ? relPath : "");
    this.showAddNew = true;

    //======== This is hidden element which will take value for selected text id   
    this.valueId = null;

    this.init = function (obj, elm) {
        if (!obj.popup) {
            var contentBody = document.getElementById('bodyconstraint') || document.body;

            var markup = '<table cellspacing="0" cellpadding="0"><tr><td></td></tr></table>';
            if (document.all && !window.opera)
                markup = '<iframe style="position:absolute;width:1000px;height:1000px;" frameborder="0"></iframe>' + markup;
            obj.popup = document.createElement('div');
            obj.popup.className = 'Bkhtl_popup';
            /*added by mohd for setting padding-left*/
            if (this.padLeft && isNaN(this.padLeft) == false) {
                obj.popup.style.paddingLeft = this.padLeft + "px";
            }
            /* till here */
            //obj.popup.setAttribute('id', 'Bkhtl_popup' + obj.name);
            obj.popup.style.display = 'none';
            obj.popup.innerHTML = markup;
            contentBody.appendChild(obj.popup);
            obj.append = obj.popup.getElementsByTagName('td')[0];
        }
        obj.element = elm;
        obj.BS_INITIALIZED = true;
    }

    this.initRequestObject = function (obj) {
        obj.request = null;
        var req;
        try {
            req = new ActiveXObject("Msxml2.XMLHTTP");

        }
        catch (err) {
            try {
                req = new ActiveXObject("Microsoft.XMLHTTP");

            }
            catch (err) {
                req = null;

            }
        }
        if (!req && (typeof (XMLHttpRequest) != "undefined")) {
            req = new XMLHttpRequest();
        }
        obj.request = req;
    }

    this.handleKeyNav = function (obj, evt, isUp) {
        if (gClientIsIE5) return true;
        if (evt.keyCode) {
            switch (evt.keyCode) {
                //Tab              
                case 9:
                    if (obj.popup.selectedBkhtlion)
                        obj.popup.selectedBkhtlion.onmousedown();
                    break;
                //Enter              
                case 13:
                    if (isUp)
                        return false;
                    if (obj.popup.selectedBkhtlion) {
                        obj.popup.selectedBkhtlion.onmousedown();
                        if (evt.preventDefault) evt.preventDefault();

                        //====== Added by me =====
                        obj.element.blur();
                        obj.lastValue = obj.element.value;
                        //========================									 
                        return false;
                    }
                    break;
                //Escape              
                case 27:
                    obj.hidePopup(obj);
                    if (obj.valueId) {
                        if (obj.valueId.value == "" || obj.valueId.value == "0") {
                            obj.valueId.value = 0;
                            obj.element.value = "";
                        }
                    }
                    break;
                //Up arrow              
                case 38:
                    if (obj.popupActive)
                        obj.previousBkhtlion(obj);
                    if (evt.preventDefault) evt.preventDefault();
                    break;

                //Down arrow              
                case 40:
                    if (obj.popupActive)
                        obj.nextBkhtlion(obj);
                    if (evt.preventDefault) evt.preventDefault();
                    break;
                //-left right arrow              
                case 37, 39:
                    break;
                default:
                    return true;
                    break;
            }
        }
    }

    this.handleActivity = function (obj, elm, url, evt) {
        // elm.className = "search_start";
        if (gClientIsIE5) return;
        if (!obj.BS_INITIALIZED)
            obj.init(obj, elm);

        // ------ specify page name ------------
        if (!url)
            return;
        else {
            obj.BS_URI = url;
        }
        //--------------------------------------

        if (elm.value.length <= 2) {
            obj.hidePopup(obj);
            obj.lastValue = elm.value;
            //----------- Clear all old value id also ----------
            if (obj.valueId)
                obj.valueId.value = 0;
            //---------------------------------------------------
        }
        else if (elm.value != obj.lastValue) {
            if (obj.timeout)
                clearTimeout(obj.timeout);

            obj.timeout = setTimeout(function () { obj.requestBkhtlion(obj); }, obj.BS_TIMEOUT);
        }
    }

    this.requestBkhtlion = function (obj) {
        //----------- Clear all old value id also ----------
        if (obj.valueId)
            obj.valueId.value = 0;
        //---------------------------------------------------

        //Show wait image ---------
        DOM.addClass(obj.element, 'inputwait');
        //------------------------

        obj.initRequestObject(obj);
        var req = obj.request;
        var url = obj.BS_URI + (obj.BS_URI.indexOf("?") == -1 ? "?" : "&") + "val=" + encodeURIComponent(obj.element.value);

        req.onreadystatechange = function () { obj.responseHandler(obj); };

        req.open('GET', url, true);
        req.send('');
        obj.lastValue = obj.element.value;
    }

    this.responseHandler = function (obj) {
        if (obj.request.readyState == 4) {
            //----- Reset original class -------
            DOM.removeClass(obj.element, 'inputwait');
            //----------------------------------

            switch (obj.request.status) {
                case 200:
                    obj.parseResponse(obj, obj.request.responseText);
                    break;
                case 404:
                default:
                    window.status = 'Server returned HTTP code ' + obj.request.status;
                    break;
            }
        }
    }

    this.parseResponse = function (obj, response) {
        var append = obj.append,
      elm = obj.element;
        var rl = response.split('\n');

        var spt = '';
        for (var i = 0; rl[i]; i += 1) {
            var idx = rl[i].indexOf(',');
            var txt = trim(rl[i].substring(idx + 1, rl[i].length));
            var val = rl[i].substring(0, idx);

            spt += '<div id="' + val + '" class="Bkhtl_entry" onmouseover="' + obj.name + '.setActiveBkhtlion(' + obj.name + ',this);" onmouseout="' + obj.name + '.unsetActiveBkhtlion(' + obj.name + ',this)" onmousedown="' + obj.name + '.useBkhtlion(' + obj.name + ',this)">';
            spt += txt;
            spt += '</div>';
        }
        if (spt == "" && obj.showNotFound == true) {
            spt += '<div id="-1" class="Bkhtl_entry" onmousedown="' + obj.name + '.useBkhtlion(' + obj.name + ',this)">';

            //---doing some changes for handling add new link ------------
            if (obj.showAddNew == true) {
                var myurl = obj.relPath + "getdestination.aspx?tbid=" + elm.id + "&tbcid=" + (obj.valueId ? obj.valueId.id : "");
                spt += obj.msgNotFound + ",<a href=javascript:showWindow('" + myurl + "',700,300)>Add New City</a>";
            }
            else {
                spt += obj.msgNotFound;
            }
            //------------------------------------------------------------
            spt += '</div>';
        }


        if (spt != "") {
            append.innerHTML = spt;
            obj.showPopup(obj);
            //-------- Hightlight first always --------------                   
            obj.nextBkhtlion(obj);
            //------------------------------------------------        
        }
        else {
            obj.hidePopup(obj);
        }
    }

    this.setActiveBkhtlion = function (obj, elm) {
        if (obj.popup.selectedBkhtlion)
            obj.unsetActiveBkhtlion(obj, obj.popup.selectedBkhtlion);

        DOM.addClass(elm, 'Bkhtl_entry_selected');

        obj.popup.selectedBkhtlion = elm;
    }

    this.unsetActiveBkhtlion = function (obj, elm) {
        DOM.removeClass(elm, 'Bkhtl_entry_selected');
    }

    this.nextBkhtlion = function (obj) {
        if (obj.popup.selectedBkhtlion && obj.popup.selectedBkhtlion.nextSibling)
            var newBkhtlion = obj.popup.selectedBkhtlion.nextSibling;
        else
            var newBkhtlion = obj.append.firstChild;
        obj.setActiveBkhtlion(obj, newBkhtlion);
    }

    this.previousBkhtlion = function (obj) {
        if (obj.popup.selectedBkhtlion && obj.popup.selectedBkhtlion.previousSibling)
            var newBkhtlion = obj.popup.selectedBkhtlion.previousSibling;
        else
            var newBkhtlion = obj.append.lastChild;
        obj.setActiveBkhtlion(obj, newBkhtlion);
    }

    this.useBkhtlion = function (obj, fld) {
        if (fld.id != "" && fld.id != "0" && fld.id != "-1") {
            var str = "";
            if (fld.innerText)
                str = fld.innerText;
            else if (fld.textContent)
                str = fld.textContent;
            else
                str = fld.innerHTML;
            obj.element.value = str;

            if (obj.valueId)
                obj.valueId.value = fld.id;
        }
        else {
            if (obj.valueId)
                obj.valueId.value = 0;

            //------- This line decide that we will allow other city also which we have not
            if (obj.allowOthers == false)
                obj.element.value = "";
        }
        obj.hidePopup(obj);
    }

    this.showPopup = function (obj) {
        if (obj.element.value == '') {
            obj.hidePopup(obj);
            return;
        }
        var elm = obj.element,
      popup = obj.popup;
        var elmPos = getDimensions(elm);
        var left = elmPos.x, top = elmPos.y + (elm.offsetHeight);
        popup.style.left = left + 'px';
        popup.style.top = top + 'px';
        popup.style.display = 'none';
        popup.style.display = 'block';
        obj.popupActive = true;
    }

    this.hidePopup = function (obj) {
        if (gClientIsIE5) return;

        if (obj.popupActive) {
            var hideIt = function () {
                obj.popup.style.display = 'none';
            }
            var timeout = 100;
            if (obj.element.value == "") {
                timeout = 1000;
            }
            setTimeout(hideIt, timeout);
            obj.popupActive = false;
            obj.popup.selectedBkhtlion = null;
        }

        //==== change by ashok
        //obj.lastValue = '';
    }
}
//========================================================
