var handleEventMutex = false;
var departureCode = false;
var arrivalCode = false;
var mapReady = false;

/**
 * Precondition: the following variables have been defined (var ...;)
 * pageFormName, departingDropName, arrivingDropName
 */
function handleException(e){
    //alert(e.fileName+":"+e.lineNumber+" : "+e.message);
}

function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
}

//@Deprecated
function setDestinationOnMap(selectControl){
    var list = selectControl.options;
    var index = selectControl.selectedIndex;
    if(list[index].text.match('---+')){
        selectControl.selectedIndex = index-1;
        index--;
    }
    BCFflashmapSetStartTerminal(list[index].innerHTML);
}

//@deprecated
function setArrivalOnMap(selectControl){
    var list = selectControl.options;
    var index = selectControl.selectedIndex;
    BCFflashmapSetEndTerminal(list[index].innerHTML);
}

function updateComboBox(elementName, terminalID, partialSubmit){
    handleEventMutex = true;//Lock and prohibit updates.
    try{
        var select = document.getElementById(elementName);
        if(terminalID == ''){
            select.value = select.options[0].value;
            //select.selectedIndex = 0;
            //partialSubmit = false;
        }else {
            //Lookup the terminal Name from this ID
            var name = getTerminalName(terminalID);
            //alert("About to set "+name);
            for(var i=0, len=select.options.length; i<len; i++){
                if(select.options[i].text == name && select.value != name){
                  //  alert("Match found.  doing select.value=");
                    select.value = select.options[i].value;
                    break;//out of for loop.
                }
            }
        }
        //alert("Value was set");
        if(partialSubmit){
            kickADF(elementName, select.value);
        }
    }catch(e){
        handleException(e);
    }
    handleEventMutex = false;
}

//onchange(..) is not invoked on programatic changes to a <select> so perform action we need.
//Does NOT set value to the provided component.
function kickADF(componentName, value){
    return _submitPartialChange(pageFormName, value, {event: componentName, source: componentName});
}


function getTerminalName(termID){
    for(var key in terminalMap){
        if(terminalMap[key] == termID){
            return key;
        }
    }
}

/**
 * Sets the current end point with the given string from the combo box.
 */
function BCFflashmapSetEndTerminal(value){
    BCFflashmapSetEndTerminalCode(terminalMap[value]);
}

/**
 * Returns true if the Flash Map is ready for use.
 */
function isMapReady(){
	return mapReady;//From this document.	
}

/**
 * Sets the currently selected end point in the Flash map given the terminal code.
 */
function BCFflashmapSetEndTerminalCode(code){
    if(!handleEventMutex){
        var movie = thisMovie("BCF_flash_route_selector");
        if(movie && isMapReady()){
            if(typeof code == 'undefined'){
                code = '';
            }
            movie.flashMapSetEndTerminalById(code);
        }else {//else Flash is NOT installed.
            arrivalCode = code;
        }
    }
}

/**
 * Sets the current start point with the given string from the combo box.
 * @Deprecated do not use.
 */
function BCFflashmapSetStartTerminal(value) {
    BCFflashmapSetStartTerminalCode(terminalMap[value]);
}

/**
 * Sets the currently selected start point in the Flash map given the terminal code.
 */
function BCFflashmapSetStartTerminalCode(code) {
    if(!handleEventMutex){
        var movie = thisMovie("BCF_flash_route_selector");
        if(movie && isMapReady()){
            try{
                if(typeof code == 'undefined'){
                    code = '';
                }
                movie.flashMapSetStartTerminalById(code);
            }catch(e){
                handleException(e);
            }
        }else {//else Flash is NOT installed.
            departureCode = code;
        }
    }
}


function BCFflashmapClearTerminals(){
    if(!handleEventMutex){
        var movie = thisMovie("BCF_flash_route_selector");
        if(movie){
            try{
                movie.flashMapResetMap();
            }catch(e){
                handleException(e);
            }
        }
    }
}


function BCFflashmapCallbackSetStartTerminal(terminalID) {
	setDepartureTerminal(terminalID);
    /*if(terminalID == ''){
        updateComboBox(arrivingDropName, terminalID, false);//clear arriving FIRST!
    }
    updateComboBox(departingDropName, terminalID, true);*/
}

function BCFflashmapCallbackSetEndTerminal(terminalID) {
	setArrivalTerminal(terminalID);
    //updateComboBox(arrivingDropName, terminalID, true);
}

/** 
 * Invoked by Flash when it has finished and is available.
 */
function BCFflashmapCallbackIsReady(){
    mapReady = true;
    if(departureCode != null){
        BCFflashmapSetStartTerminalCode(departureCode);
    }
    if(arrivalCode != null){
        BCFflashmapSetEndTerminalCode(arrivalCode);
    }
}

function BCFflashmapCallbackResetStartTerminal() {
    //alert("Clear departing, ignoring for now.");
}
function BCFflashmapCallbackResetEndTerminal() {
    //alert("Clear arriving, ignoring for now.");
}

/**
 * Updates map on page load so it reflects dropdown values.
 * @DEPREACTED, this will be done by initial page load call.
 */
function fixMapState(departure,arrival){
    if(departure.length > 0){
        if(!isMapReady()){
            departureCode = departure;
        }else {
            BCFflashmapSetStartTerminalCode(departure);
        }
    }
    if(arrival.length > 0){
        if(!isMapReady()){
            arrivalCode = arrival;
        }else {
            BCFflashmapSetEndTerminalCode(arrival);
        }
    }
}

//@Deprecated  no longer required.
function fixSelect(elName){
    var el = document.getElementById(elName);
    return;
    for(var i=0, len = el.options.length; i<len; i++){
        if(el.options[i].text.match('--+')){
            el.options[i].disabled = true;//For firefox disable. IE 6/7 is broken.
            break;
        }
    }
}

function updateHiddenDirector(targetId, value){
    var el = document.getElementById(targetId);
    el.value = value;
}

function redirectTo(target){
    window.location = target;
}

function departureDateUpdated(){
    var el = document.getElementById(dateInputFieldName);//defined globally.
    if(window.updateHidden != null && typeof window.updateHidden == 'function'){
        updateHidden('../travelCenter/SchedulesTab.jsp');
    }
    kickADF(el.id, el.value);
}


/**
 * Creates a popup in a nice way.
 * this method ALWAYS returns false, so it is safe for use in onclick events.
 */
function popitupURL(url, height){
    var h = 750;
    if (height > 0) {
       h = height;
    }
    /*if(url.indexOf('?') != -1){//Ensure uniqueness in URL.  This is less ideal then closing on unload.
        url += '&';
    }else {
        url += '?';
    }
    url +='update='+new Date().getTime();
    */
    window.newwindow = window.open(url, 'schedule', 'height='+h+',width=750,scrollbars=yes,resizable=yes');
    if(window.focus){
        window.newwindow.focus();
    }
    //When this window closes,  close the dialog that was opened as well.  
    window.onunload=function(){
        window.newwindow.close();
        window.newwindow = null;
    }
    return false;
}

/**
 * Attempts to click on the Service Notices tab if present.  Usually defined in TravelInfoRegion
 * 
 */
function clickServiceNotices(followLink){
    if(typeof window.simulateClick == 'function' && typeof window.updateHiddenSelect == 'function'){
        window.updateHiddenSelect('4');
        window.simulateClick('serviceTab');
    }
    if (followLink == true) {
        return true;
    } else {
       return false;
    }
}