// JavaScript for Honeywell's Job Search Settings


//////////////////////////////////////////
// relational menu code 
//////////////////////////////////////////

// represents the entire system
function JobSearchBoxes(values)
{
    this.values = values; // array
    this.loaded = 0;
    this.category = null;
    this.countrycode = "";

    // Debugging method returns text
    this.GetText = function()
    {
        var txt = '';
        for(var i=0; i<values.length; i++) {
            txt += values[i].name + '\n';
            txt += values[i].GetText() + '\n';
        }
        alert(txt);
    }

    // Method to populate first box
    this.Populate = function()
    {
        for(var i=0; i<this.values.length; i++) {
            var frm = document.getElementById(this.values[i].fname);
            frm.options[i+1] = new Option(this.values[i].name, this.values[i].name, false, false);
        }
    }

    // Method to populate second box
    this.PopulateSecond = function(val)
    {
        if(val) {
            for(var i=0; i<this.values.length; i++) {
                if(val == this.values[i].name)
                    this.values[i].Populate();
            }
        } else {
            // Clear the Select box
            var frm = document.getElementById(this.values[0].langs[0].fname);
            this.values[0].langs[0].Clear(frm);
        }
    }


    // Store the info
    this.storeCookie = function(val)
    {
        var cName = 'jss_prefs';
        var val1 = document.getElementById(this.values[0].fname).value;
        var val2 = document.getElementById(this.values[0].langs[0].fname).value;

        if(cookie_enabled == 1)
        {
            if(val1 && val2) {
                jssDelCookie(cName);
                var values = val1 + ':' + val2;
                var tcValues = "";

                // Make sure the cookie gets set
                var i = 0;
                while(tcValues != values) {
                    jssSetCookie(cName, values, 90);
                    tcValues = getCookie(cName);
                    i++;
                    if(i > 100) {
                        alert('Unable to save your settings. Please verify that cookies are enabled.');
                        break;
                    }
                }
                // Only show the popup and reload page if the cookie was successful
                if(i < 100) {
                    newwin = popWindow('jobsearch_pop.html',295,245,0);
                    var pname = rtrim(window.location.href, '?');
                    window.location.href = pname; 
                }
            } else {
                alert('Please select both a region and a language.');                
            }

        } else {
            alert('Cookies are disabled in your browser. Please enable cookies in order to save your Job Search Settings.');
            var pname = rtrim(window.location.href, '?');
            val1 = url_encode(val1);
            val2 = url_encode(val2); 
            window.location.href = pname + '?lo=' + val1 + '&la=' + val2;
        }
    }


    // Get stored info
    this.getValues = function()
    {
        var cName = 'jss_prefs';
        var cValues = '';
        // defaults
        var country = this.values[0].name;
        var language = this.values[0].langs[0].name;
        // Get values from query string 
        var urlValues = parseUrlArgs('parent');
        var lo = getUrlArg(urlValues, "lo");
        var la = getUrlArg(urlValues, "la");
        var cc = getUrlArg(urlValues, "code");
        this.countrycode = (cc) ? cc : "";


        // Get values from cookie, unless there are values on the querystring
        if(cookie_enabled == 1 && !lo) {
            cValues = jssGetCookie(cName);
            cValues = (cValues != null) ? cValues : country+':'+language;
            cValues = cValues.split(":");
            this.values[0].active = cValues[0];
            this.values[0].langs[0].active = cValues[1];
        } else {
            this.values[0].active = (lo) ? lo : country;
            this.values[0].langs[0].active = (la) ? la : language;
        } 

    }

    // Write the preferences
    this.writePrefs = function()
    {
        var country = this.values[0].active;
        var language = this.values[0].langs[0].active;
        var txt = "<div style=\"margin:6px 12px;\">\n" +
                  "Your job search preferences are currently set to jobs in <b>"+ country + "</b> in <b>"+ language +"</b>.<br>\n" +
                  "</div>\n" +
                  "<div style=\"margin:6px 12px;\">\n" +
                  "Click below to change your preferences.\n" +
                  "</div>\n";
        document.write(txt);
    }
    
    // Write the preferences in the popup
    this.writePrefsPopup = function()
    {
        var country = this.values[0].active;
        var language = this.values[0].langs[0].active;
        var txt = "<p>Your job search preferences have been saved. " +
                  "Your default job search will now be jobs in <b>" + country + "</b> in <b>" + language + "</b>. " +
                  "Use the job search settings box on the right to view jobs in other regions/languages.</p>\n";
        document.write(txt);
    }

    // Redirect the Iframe to the Taleo search
    this.redirect = function()
    {
        // get active values
        var country = this.values[0].active;
        var language = this.values[0].langs[0].active;
        // get link values
        var coun_num = this.getCurrent(this.values, country);
        var lang_num = this.getCurrent(this.values[coun_num].langs, language);
        var code = this.values[coun_num].code;   //'e';
        var key = (this.countrycode) ? 'en' : this.values[coun_num].langs[lang_num].key; //'en'; 
        var cat = (this.category) ? '&category='+this.category : '';
        var loc = (this.countrycode) ? '&location='+this.countrycode : '';
        // write the link
        var taleo = 'https://honeywell.taleo.net/servlets/CareerSection?art_ip_action=FlowDispatcher&flowTypeNo=13&pageSeq=1&art_servlet_language=' + key + '&csNo=' + code + cat + loc;
        jobsearch.location.href = taleo;
        //document.write('<a href="'+taleo+'">TALEO LINK</a>');
    }

    // Find the active Region and Language
    this.getCurrent = function(myColl, val)
    {
        for(var i=0; i<myColl.length; i++) {
            if(myColl[i].name == val)
                return i;
        }
        return -1;
    }

    // Write the job search header
    this.writeHeader = function()
    {
        // Get values from cookie
        var country = this.values[0].active;
        var language = this.values[0].langs[0].active;
        // Get values from query string 
        var urlValues = parseUrlArgs('parent');
        var lo = getUrlArg(urlValues, "lo");
        var la = getUrlArg(urlValues, "la");
        // Query string location overrides cookie
        if(lo != "") 
            country = lo;
        if(la != "") 
            language = la;

        var txt = ' - ' + country + ' (' + language + ')';
        document.write(txt); 
    }

} // end class
        

// represents the region box
function Region(fname, name, code, langs)
{
    this.fname = fname;     // string, first HTML element name
    this.name = name;       // string
    this.code = code;       // string
    this.langs = langs;     // array
    this.active = "";       // string

    // Debugging method returns text
    this.GetText = function() 
    {
        var txt = '';
        for(var i=0; i<this.langs.length; i++) {
            txt += '_' + this.langs[i].name + '\n';
        } 
        return txt;
    }

    // Method to populate the second box
    this.Populate = function()
    {
        if(this.langs)
        {
            // Clear the Select box
            var frm = document.getElementById(this.langs[0].fname);
            this.langs[0].Clear(frm);

            // Populate new options
            for(var i=0; i<this.langs.length; i++) {
                frm.options[i+1] = new Option(this.langs[i].name, this.langs[i].name, false, false);
            } 

        }
    } 
} // end class



// represents the language box
function Language(fname, name, key)
{
    this.fname = fname; // string, HTML element name
    this.name = name;   // string
    this.key = key;     // string
    this.active = "";   // string

    // Method to clear the select box
    this.Clear = function(frm)
    {
        var selLen = frm.options.length;
        for(var i=1; i<selLen; i++)
            frm.options[i] = null;
        frm.options.length = 1;
    }

} // end class



// get a cookie's value
function jssGetCookie(name)
{
    var re = new RegExp(name + "=([^;]+)");
    var value = re.exec(document.cookie);
    return (value != null) ? unescape(value[1]) : null;
}

// set a cookie's name and value
function jssSetCookie(name, value, numDays)
{
    if(numDays==null || numDays==0)
        numDays = 1;
    var today = new Date();
    var expire = new Date();
    expire.setTime(today.getTime() + 3600000*24*numDays);
    document.cookie = name+"="+escape(value) + ";expires="+expire.toGMTString();
}

// delete a cookie
function jssDelCookie(name)
{
    var oldDate = new Date(1970, 1, 1);
    document.cookie = name + "=0;expires=" + oldDate.toGMTString();
}

// see if cookies are enabled
function jssCheckCookies()
{
    // returns '1' if cookies are set
    jssDelCookie('test');
    var value = 0;
    jssSetCookie('test',1,0);
    value = jssGetCookie('test');
    jssDelCookie('test');
    return value;
}


// Function to open links in a new window
var newwin='';

// open a popup window
function popWindow(theUrl,width,height,full) {
    // use defaults if width and height were not supplied
    var ismoz = navigator.userAgent.indexOf("Gecko");
    var isie = navigator.userAgent.indexOf("MSIE");
    var default_width = 600;
    var default_height = 450;
    var offset_width = (isie != -1) ? 0 : 0;
    var offset_height = (isie != -1) ? 0 : 0;
    var popType = (full) ? ",scrollbars=yes,resizable=yes,status=yes,toolbar=yes,menubar=yes,location=yes,directories=yes" : ",scrollbars=no,resizable=no,status=no";
    
    var popWidth = (width) ? width + offset_width : default_width + offset_width;
    var popHeight = (height) ? height + offset_height : default_height + offset_height;
    var popLeft = self.screen.availWidth/2 - popWidth/2;
    var popTop = self.screen.availHeight/2 - popHeight/2;
    
    if(theUrl) {
        if(newwin)
            newwin.close();
        newwin = window.open(theUrl,'newwin','left='+popLeft+',top='+popTop+',width='+popWidth+',height='+popHeight+popType);
    }

    return;
}


// take a full or partial path, and return it's last part
function basename(path)
{
    var parts = path.split('/');
    return parts[parts.length-1];
}

// trim a string on the right side
function rtrim(haystack,needle)
{
    var found = haystack.indexOf(needle);
    if(found != -1)
        var result = haystack.substr(0, found);
    else
        var result = haystack;

    return result;
}

// trim a string on the left side
function ltrim(haystack,needle)
{
    var found = haystack.indexOf(needle);
    if(found != -1)
        var result = haystack.substr(found, haystack.length);
    else
        var result = haystack;
    
    return result;
}


// Return any key/value pairs passed in the URL
function parseUrlArgs(target)
{
    var result = Array();

    // allow for different targets
    if(target != null && target != '')
        var base = basename(eval(target).location.href);
    else
        var base = basename(document.location.href);
        
    var startArg = base.indexOf('?');
    // see if there are arguments
    if(startArg != -1)
    {
        // get the arguments
        startArg++;
        var keys = Array()
        var vals = Array();
        var length = (base.length - startArg);
        var args = base.substr(startArg, length);
        // get the key=value pairs
        var parts = args.split('&');
        for(var i=0; i<parts.length; i++)
        {
            var keyval = parts[i].split('=');
            keys[i] = keyval[0];
            vals[i] = keyval[1];
        }

        result = Array(keys, vals);
    }
    return result;
}

function getUrlArg(urlValues, arg)
{
    var result = "";
    if(urlValues.length > 0)
    {
        for(var i=0; i<urlValues.length+1; i++)
        {
            if(urlValues[0][i] == arg) {
                result = urlValues[1][i];
            }
        }
    }
    result = url_decode(result);
    return result;
}

// Encode value for URL
function url_encode(val)
{
    val = val.replace(/\s/g,'+');   // space
    val = val.replace(/&/g,'%26');  // ampersand
    val = val.replace(/=/g,'%3d');  // equals
    val = val.replace(/\?/g,'%3f'); // question 
    val = val.replace(/\//g,'%2f'); // slash
    return val;
}

// Decode value for URL
function url_decode(val)
{
    val = val.replace(/\+/g,' ');   // space
    val = val.replace(/%26/g,'&');  // ampersand
    val = val.replace(/%3d/g,'=');  // equals
    val = val.replace(/%3f/g,'?');  // question 
    val = val.replace(/%2f/g,'/');  // slash
    return val;
}



// VARIABLES

// Language(fname, name, key)
var LangEng = new Language('jss_lang','English','en');
var LangChi = new Language('jss_lang','Simple Chinese','zh-CN');
var LangDut = new Language('jss_lang','Dutch','nl');
var LangFre = new Language('jss_lang','French','fr');
var LangGer = new Language('jss_lang','German','de');

var JobSearch = new JobSearchBoxes(
    new Array(
        new Region('jss_region','North America', '3', new Array(LangEng) ),
        new Region('jss_region','Asia Pacific', '10061', new Array(LangEng,LangChi) ),
        new Region('jss_region','Europe, Middle East & Africa', '10100', new Array(LangDut,LangEng,LangFre,LangGer) )
        )
    );

// If they don't have a cookie yet, test for cookies enabled
var cookie_enabled = "1";
var tmp = jssGetCookie('jss_prefs');
if(!tmp) {
    cookie_enabled = jssCheckCookies();
}

