// JavaScript Document

// -- ----------------------------------------------------------------------------------------
function getHTTPObject() {
    var xmlhttp;
    /*@cc_on
    @if (@_jscript_version >= 5)
        try {
            xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (E) {
                    xmlhttp = false;
            }
        }
    @else
        xmlhttp = false;
    @end @*/
    if (!xmlhttp && typeof XMLHttpRequest != undefined) {
        try {
            xmlhttp = new XMLHttpRequest();
        } catch (e) {
            xmlhttp = false;
        }
    }
    return xmlhttp;
}

function httpSend(sUrl, obj){
    if(obj.http.readyState != 0) obj.http.abort();
    obj.http.open("GET", sUrl, true);
    obj.http.onreadystatechange = function(){
        if(obj.http.readyState == 4){
            obj._processResponse(unescape(obj.http.responseText));
        }
    }
    obj.http.send(null);
}

function httpCheck(sUrl, obj){
    if(obj.http.readyState != 0) obj.http.abort();
    obj.http.open("GET", sUrl, true);
    obj.http.onreadystatechange = function(){
        bStatusCheck = obj.http.readyState;
        if(obj.http.readyState == 4){
            obj._processResponseCheck(obj.http.responseText);
        }
    }
    obj.http.send(null);
}

// -- ----------------------------------------------------------------------------------------
var BrowserDetect = {
    init: function () {
        var browser = {name : this.searchString(this.dataBrowser) || "An unknown browser",
        version : this.searchVersion(navigator.userAgent)
            || this.searchVersion(navigator.appVersion)
            || "an unknown version",
        OS : this.searchString(this.dataOS) || "an unknown OS"};
        return browser;
    },
    searchString: function (data) {
        for (var i=0;i<data.length;i++)	{
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
    },
    dataBrowser: [
        { 	
            string: navigator.userAgent,
            subString: "OmniWeb",
            versionSearch: "OmniWeb/",
            identity: "OmniWeb"
        },
        {
            string: navigator.vendor,
            subString: "Apple",
            identity: "Safari"
        },
        {
            prop: window.opera,
            identity: "Opera"
        },
        {
            string: navigator.vendor,
            subString: "iCab",
            identity: "iCab"
        },
        {
            string: navigator.vendor,
            subString: "KDE",
            identity: "Konqueror"
        },
        {
            string: navigator.userAgent,
            subString: "Firefox",
            identity: "Firefox"
        },
        {
            string: navigator.vendor,
            subString: "Camino",
            identity: "Camino"
        },
        {   // for newer Netscapes (6+)
            string: navigator.userAgent,
            subString: "Netscape",
            identity: "Netscape"
        },
        {
            string: navigator.userAgent,
            subString: "MSIE",
            identity: "Explorer",
            versionSearch: "MSIE"
        },
        {
            string: navigator.userAgent,
            subString: "Gecko",
            identity: "Mozilla",
            versionSearch: "rv"
        },
        {   // for older Netscapes (4-)
            string: navigator.userAgent,
            subString: "Mozilla",
            identity: "Netscape",
            versionSearch: "Mozilla"
        }
    ],
    dataOS : [
        {
            string: navigator.platform,
            subString: "Win",
            identity: "Windows"
        },
        {
            string: navigator.platform,
            subString: "Mac",
            identity: "Mac"
        },
        {
            string: navigator.platform,
            subString: "Linux",
            identity: "Linux"
        }
    ]

};


function alternativeScrollIntoView(parentDiv, elementIntoDiv){
    var principal = parentDiv;
//    principal.scrollTop = 0;
    
    var rects = principal.getClientRects()[0];
    var topFinal = rects.top;
    var bottomFinal = rects.bottom;
    var bottomActual = elementIntoDiv.getClientRects()[0].bottom;
    
    if (bottomActual == 0){
        return;
    }
    while(bottomActual > bottomFinal || bottomActual < topFinal){
        var direction="down";
        
        if(bottomActual < topFinal){
            direction = "up";
        }
        principal.doScroll(direction);
        bottomActual = elementIntoDiv.getClientRects()[0].bottom;
    }
}

// -- ----------------------------------------------------------------------------------------
function vSelector(){
    if(arguments.lenght <= 1) return;
        
    this.field = document.getElementById(arguments[0]);
    this.label = document.getElementById(arguments[0]+'Disp');
    this.browser = BrowserDetect.init();
    
    this.optList = new Array();
    for (var i = 1; i < arguments.length; i++) {
        this.optList.push(arguments[i]);
    }
    this.itemM = this.optList.length;
    
    this._createList = function(){
        if (this.optList.length > 0){
            this.layer = document.createElement('ul');
            this.layer.className = 'suggestedOptions';
            this.layer.style.position = 'absolute';
            this.layer.id = this.field.id + 'Layer';
            this.layer.style.visibility = 'hidden';
            this.layer.style.left = getAbsoluteLeft(this.label.id) + 'px';
            this.layer.style.top = getAbsoluteTop(this.label.id) + this.label.offsetHeight + 'px';
            this.layer.style.width = (this.label.offsetWidth - 2) + 'px';
            
            // Setting the doScroll function
            if(this.browser.name == 'Firefox' && this.browser.version == 3){
                this.layer.doScroll = function(dirc){
                    switch(dirc){
                        case 'up':
                            this.scrollTop -= 31;
                            break;
                        case 'down':
                            this.scrollTop += 31;
                            break;
                    }
                }
            }
            
            //Filling the layer
            var activeBg = false;
            for (var i = 0; i < this.optList.length && i < this.itemM; i++){
                var opt = this.optList[i];
                opt.value = (!opt.value) ? '': opt.value;
                
                if(opt.disp){
                    var li = document.createElement('li');
                    li.id = opt.value
                    li.className = activeBg ? 'on' : '';
                    activeBg = activeBg ? false : true;
                    
                    addEvent(li, 'mousedown', vSelector_setOption, false);
                    
                    var text = document.createTextNode(opt.disp);
                    
                    li.appendChild(text);
                    
                    this.layer.appendChild(li);
                }
            }
            this.label.parentNode.appendChild(this.layer);
        }
    }
    this.saveSelect = function(pos){
        var opt;
        if(pos){
            opt = this.layer.getElementsByTagName('li')[pos - 1]
            this.setOption(opt);
        }
    }
    this.selectNext = function(){
        if (this.selected < this.optList.length){
            //Removing preview selection
            this.clearSelection();
            
            this.selected++;
            this.chose(this.selected);
        }
    }
    this.selectPreview = function(){
        if(this.selected > 1){
            //Removing preview selection
            this.clearSelection();
            
            //New selection
            this.selected--;
            this.chose(this.selected);
        }
    }
    this.chose = function(i){
        var elem = this.layer.getElementsByTagName('li')[i - 1];
        elem.className += ' selected';
        if(this.browser.name == 'Firefox' && this.browser.version == 2){
            elem.scrollIntoView(false);
        }else{
            alternativeScrollIntoView(elem.parentNode, elem);
        }
    }
    this.selectSelected = function(){
        for (var i = 0; i < this.optList.length; i++){
            if (this.optList[i].value == this.field.value){
                this.selected = i + 1;
                break;
            }
        }
        if(this.selected){
            this.chose(this.selected);
        }
    }
    this.clearSelection = function(){
        for(var i = 0; i < this.optList.length; i++){
            var elem = this.layer.getElementsByTagName('li')[i];
            elem.className = elem.className.replace(/\bselected\b/g, '');
        }
    }
    this.showOptions = function(){
        //this.selected = 0;
        if (!this.layer) this._createList();
        if (this.layer && this.layer.style.visibility == 'hidden'){
            if(document.activeSelector){
                removeEvent(document.activeSelector.label, 'keydown', vSelector_keys);
                document.activeSelector.hideOptions();
            }
            document.activeSelector = this;
            document.activeSelector.clearSelection();
            document.activeSelector.selectSelected();
            this.layer.style.visibility = 'visible';
            addEvent(this.label, 'keydown', vSelector_keys, false);
        }
    }
    this.hideOptions = function (){
        if(this.layer){
            if(this.selected){
                //Removing preview selection
                this.clearSelection();
            }
            this.layer.style.visibility = 'hidden';
        }
    }
    this.setOption = function(opt){
        this.field.value = opt.id;
        this.label.value = opt.innerHTML;
        this.hideOptions();
        this.callInfantsList(this.field.id, this.field.value);
    }
    this.callInfantsList = function(sTypePax, iNbPax) {
        if (sTypePax == "Adults") {
            InfantsSelector.setInfantsList(sTypePax, iNbPax);
        }
    }
    this.setInfantsList = function (sTypePax, iNbPax){
        if (this.field.value > iNbPax) {
            this.field.value = iNbPax;
            this.label.value = iNbPax;
        }
    }
}

function vSelector_keys(e){
    var evt = window.event ? window.event : e ? e : null;
    var target = evt ? evt.srcElement ? evt.srcElement : evt.target ? evt.target : null : null;
    
    if(document.activeSelector){
        switch(evt.keyCode){
            case 8: // backspace
                break;
            case 9: // tab
                if (document.activeSelector.selected) {
                    document.activeSelector.saveSelect(document.activeSelector.selected);
                } else {
                    document.activeSelector.selectNext();
                    document.activeSelector.saveSelect(document.activeSelector.selected);
                }
                break;
            case 13: // enter
                document.activeSelector.saveSelect(document.activeSelector.selected);
                break;
            case 17: // ctrl
                break;
            case 18: // alt
                break;
            case 20: // capslock
                break;
            case 27: // escape
                document.activeSelector.hideOptions();
                break;
            case 35: // end
                break;
            case 36: // home
                break;
            case 37: // keyleft
                break;
            case 38: // keyup
                document.activeSelector.selectPreview();
                break;
            case 39: // keyright
                break;
            case 40: // keydown
                if(document.activeSelector.layer.style.visibility == 'hidden'){
                    document.activeSelector.showOptions();
                }else{
                    document.activeSelector.selectNext();
                }
                break;
            case 45: // insert
                break;
            case 46: // delete
                break;
            case 144: // numlock
                break;
        }
    }
    void(0);
}

function vSelector_setOption(e){
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (!target) return;
    
    if(document.activeSelector){
        document.activeSelector.setOption(target);
    }
}

// -- ----------------------------------------------------------------------------------------
function vDynamicSelector(Options){
    if(!Options.id) return;
        
    this.Options = Options;
    
    this.Options.minLength = (this.Options.min1) ? this.Options.min1 : 3;
    this.Options.min2Length = (this.Options.min2) ? this.Options.min2 : this.Options.minLength;
    this.Options.overflowControl = (this.Options.overflowControl) ? this.Options.overflowControl : 10;
    this.lastSearch = '';
    this.flagtrace = '';
        
    this.http = getHTTPObject();
    this.browser = BrowserDetect.init();
    
    //methods definition
    this._createList = function(optList){
        if (optList.length > 0){
            var labelId = this.Options.id + 'Disp';
            if (!this.layer){
                this.layer = document.createElement('ul');
                this.layer.className = 'suggestedOptions';
                this.layer.style.position = 'absolute';
                this.layer.id = this.Options.id + 'Layer';
                this.layer.style.visibility = 'hidden';
                this.layer.style.left = getAbsoluteLeft(labelId) + 'px';
                this.layer.style.top = getAbsoluteTop(labelId) + document.getElementById(labelId).offsetHeight + 'px';
            }
            
            // Setting the doScroll function
            if(this.browser.name == 'Firefox' && this.browser.version == 3){
                this.layer.doScroll = function(dirc){
                    switch(dirc){
                        case 'up':
                            this.scrollTop -= 31;
                            break;
                        case 'down':
                            this.scrollTop += 31;
                            break;
                    }
                }
            }
            
            //Removin old Content
            if (this.layer.hasChildNodes()) {
                var x = this.layer.childNodes;
                while(x.length){
                    var node = x.item(0);
                    this.layer.removeChild(node);
                }
            }
            //Overflow control
            if (optList.length > this.Options.overflowControl){
                this.layer.style.height = '200px';
                switch(this.browser.name){
                    case 'Opera':
                        this.layer.style.overflow = 'auto';
                        break
                    case 'Explorer':
                        switch(this.browser.version){
                            case 6:
                                this.layer.style.overflowY = 'scroll';
                                break
                            default:
                                this.layer.style.overflowY = 'scroll';
                                this.layer.style.overflowX = 'hidden';
                        }
                        break
                    default:
                        this.layer.style.overflowY = 'scroll';
                        this.layer.style.overflowX = '';
                }
            } else {
                this.layer.style.height = '';
                this.layer.style.overflow = '';
                this.layer.style.overflowY = '';
                this.layer.style.overflowX = '';
            }
            //Filling the layer
            var activeBg = false;
            for (var i = 0; i < optList.length; i++){
                 optList[i].value = (! optList[i].value) ? '':  optList[i].value;
                
                if (optList[i].disp) {
                    var li = document.createElement('li');
                    li.id =  optList[i].value
                    li.className = activeBg? 'on': '';
                    activeBg = activeBg? false : true;
                    
                    addEvent(li, 'mousedown', vSelector_setOption, false);
                    
                    var text = document.createTextNode( optList[i].disp);
                    
                    li.appendChild(text);
                    
                    this.layer.appendChild(li);
                }
            }
            document.getElementById(labelId).parentNode.appendChild(this.layer);
            this.selectNext();
        }
    }
    this._processResponse = function(strResponse){
        if (strResponse != '' && strResponse != 'KO'){
            this.Options.reaRseult = strResponse;
            var lines = strResponse.split('\n');
            for (var i = 0; i < lines.length; i++){
                var line = lines[i].split('|');
                var data = {value:line[0], disp:line[1]}
                lines[i] = data;
            }
            if (lines.length > 0){
                this._createList(lines);
                this.showOptions();
            }
        }
    }
    this._processResponseCheck = function(strResponse){
        if (strResponse != '' && strResponse != 'KO'){
            var aLines = strResponse.split('\n');
            if (aLines.length == 1) {
                sResultCheck = aLines[0];
            } else {
                sResultCheck = '';
            }
        }
    }
    this.saveSelect = function(pos){
        var opt;
        if(!pos) {
            this.selectNext();
            pos = this.selected;
        }
        if(pos){
            opt = this.layer.getElementsByTagName('li')[pos-1]
            this.setOption(opt);
        }
    }
    this.search = function(strLine){
        if (strLine.length >= this.Options.minLength){
            var fUn = 0;
            if (strLine.length == this.Options.minLength && this.Options.minLength <= this.Options.min2Length) {
                fUn = 1;
            }
            if (strLine != this.getLastSearch()){
                var sUrl = this.Options.urlC + "&fLb=" + strLine + "&fUn=" + fUn;
                this.setLastSearch(strLine);
                httpSend(sUrl, this);
            }
        } else if (strLine.length == 0){
            this.hideOptions();
        }
    }
    this.setLastSearch = function(sContent){
        this.lastSearch = sContent;
    }
    this.getLastSearch = function(){
        return this.lastSearch;
    }
    this.setFlagTrace = function(sContent){
        this.flagtrace = sContent;
    }
    this.getFlagTrace = function(){
        return this.flagtrace;
    }
    this.searchCode = function(sDsp, sVal) {
        var oOpt = this.Options;
        var sDsp = document.getElementById(oOpt.id + 'Disp');
        var sVal = document.getElementById(oOpt.id);
        var sUrl = this.Options.urlC + "&fLb=";
        
        if (sVal.length == 3) {
            sUrl += sVal + "&fQr=cod";
            this.lastSearch = sVal;
            httpCheck(sUrl, this);
        } else {
            var aDsp = sDsp.value.split(", ");
            if (aDsp.length == 3) {
                if (aDsp[1].length == 3) {
                    sUrl += "&fLb=" + aDsp[1] + "&fQr=cod";
                    this.lastSearch = aDsp[1];
                    httpCheck(sUrl, this);
                }
            }
        }
    }
    this.selectNext = function(){
        if(this.selected == undefined) this.selected = 0;
        if(this.selected < this.layer.childNodes.length){
            if(this.selected){
                //Removing preview selection
                var preview = this.layer.getElementsByTagName('li')[this.selected - 1];
                preview.className = preview.className.replace(/\bselected\b/g, '');
            }
            this.selected++;
            var next = this.layer.getElementsByTagName('li')[this.selected - 1];
            next.className += ' selected';
            
            if(this.browser.name == 'Firefox' && this.browser.version == 2){
                next.scrollIntoView(false);
            }else{
                alternativeScrollIntoView(next.parentNode, next);
            }
        }
    }
    this.selectPreview = function(){
        if(this.selected > 1){
            //Removing preview selection
            var preview = this.layer.getElementsByTagName('li')[this.selected - 1];
            preview.className = preview.className.replace(/\bselected\b/g, '');
            
            //New selection
            this.selected--;
            var next = this.layer.getElementsByTagName('li')[this.selected - 1];
            next.className += ' selected';
            
            if(this.browser.name == 'Firefox' && this.browser.version == 2){
                next.scrollIntoView(false);
            }else{
                alternativeScrollIntoView(next.parentNode, next);
            }
        }
    }
    this.showOptions = function(){
        this.selected = 0;
        if(this.layer && this.layer.style.visibility == 'hidden'){
            if(document.activeSelector){
                document.activeSelector.hideOptions();
            }
            document.activeSelector = this;
            this.layer.style.visibility = 'visible';
            addEvent(document, 'mousedown', vDynamicSelector_AutoHide, false);
            addEvent(document.getElementById(this.Options.id + 'Disp'), 'keydown', vSelector_keys, false);
        }
    }
    this.hideOptions = function(){
        if(this.layer){
            if(this.selected){
                //Removing preview selection
                var preview = this.layer.getElementsByTagName('li')[this.selected - 1];
                preview.className = preview.className.replace(/\bselected\b/g, '');
                this.selected = 0;
            }
            this.layer.style.visibility = 'hidden';
            removeEvent(document, 'mousedown', vDynamicSelector_AutoHide);
            removeEvent(document.getElementById(this.Options.id + 'Disp'), 'keydown', vSelector_keys);
            document.activeSelector = null;
        }
    }
    this.setOption = function(opt){
        this.lastSearch = opt.innerHTML;
        document.getElementById(this.Options.id).value = opt.id;
        document.getElementById(this.Options.id + 'Disp').value = opt.innerHTML;
        this.hideOptions();
    }
}

function vDynamicSelector_AutoHide(e){
    var target = window.event ? window.event.srcElement : e ? e.target : null;
    if (!target) return;
    
    if(document.activeSelector != null){
        var t = true;
        while(target != null){
            oParent = target;
            if(oParent.id == document.activeSelector.layer.id){
                return false;
                break;
            }
            target = oParent.parentNode;
        }
        if(t == true){
            document.activeSelector.hideOptions();
        }
    }
}
