/*
 *  navigation list item auto-resizing
 *  Copyright (c) 2007 Traction Corporation.  All Rights Reserved
 *  http://www.tractionco.com/
 *
 *  edited 12/15 to contain livescribe navbar prototype code
 */


var kTopLevelWidth = 900;   // width of top-level template elements
var boxAmt = 1;             // amount of horizontal padding, border, margin in the top nav li's

window.is_livescribe_desktop = false;
if(document.cookie.match(/(^|;\s*)ldinfo=./)) {
    window.is_livescribe_desktop = true;
}

function tnavAdjustWidths() {

    var navItems = $$('.headnav');
    var ret_changed = false;

    if(navItems.length <= 0) {
        ; // no changes
    }
    else {
        var realItemWidth = kTopLevelWidth/navItems.length;
        var lowItemWidth = Math.floor(realItemWidth);
        var remainder = kTopLevelWidth - (lowItemWidth * navItems.length)

        navItems.each(function(el) {
            var thisWidth = lowItemWidth;
            if(remainder) {
                thisWidth += 1;
                remainder -= 1;
            }

            var thisPx = (thisWidth - boxAmt) + 'px';
            Element.setStyle(el,{ width: thisPx });

            // last one has an extra pixel?
        });

        ret_changed = true;
    }

    return ret_changed;
}

function tnavAccountLinks() {
    if(document.cookie.match(/li=1/i)) {
        $$('.if-logged-in').invoke('show');
    }
}


function updateGlobalCountrySelector(use_locale) {

    var select_element = $('selected_country');

    if(select_element) {
        $$(".intl_dropdown a." + use_locale + ", .intl_dropdown_LD a." + use_locale).each(function(matched) {
            $('selected_country').innerHTML = $(matched).innerHTML;
            $('selected_country').addClassName(use_locale);
        });//each
    }

    var context = getContextInfo();

    if( ("undefined" != typeof context['no_localization']) &&
        (context['no_localization'])) {
        if($('intl_selector_LD')) {
            Element.remove($('intl_selector_LD'));
        }

        if($('intl_selector')) {
            Element.remove($('intl_selector'));
        }
    }

    if("undefined" != typeof context['localize_landing']) {

        $$(".intl_dropdown a, .intl_dropdown_LD a").each(function(el) {
            var localize_target = $(el).readAttribute('href');
            var landing_param = context.localize_landing;
            $(el).writeAttribute('href', localize_target + '&continue=' + landing_param);
        })

    }
}

function tnavInit() {

    var checkfor = document.getElementById('noscriptnav');

    if(!checkfor){
        tnavAdjustWidths();
        tnavAccountLinks();
    }
}

function tableSummation(theArr){
    var tableSum = 0;
    for(j=0;j<theArr.length;j++) {
        tableSum += theArr[j];
    }
    return tableSum;
}


function getContextInfo() {

    var ret = {};

    if("undefined" != typeof window['CONTEXT_INFO']) {
        ret = window.CONTEXT_INFO;
    }

    return ret;
}

// Every time you call this function, you make
// me shed a single, crystal tear. Please find another way.
function setContextInfo(key, value) {

    if("undefined" == typeof window['CONTEXT_INFO']) {
        window.CONTEXT_INFO = {};
    }

    window.CONTEXT_INFO[key] = value;
}

function readCookie(name) {

    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
	var c = ca[i];
	while (c.charAt(0)==' ') c = c.substring(1,c.length);
	if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

// Searches explicit setting in the page, followed by the path.
// DO NOT INCLUDE A SETTING IN STATIC PAGES.
//
// May still return screwball stuff for the locale in a lot of cases
// (i.e. "store")
function readLocale() {
    var default_locale = 'int';
    var use_locale = default_locale;

    var context = getContextInfo();

    if("undefined" != typeof context['xlsLocale']) {
        use_locale = context['xlsLocale'];
    }
    else if ((use_locale = readCookie('locale'))!=null) {
	return use_locale;
    }
    else {

        var locale_match = window.location.pathname.match(/^\/([A-Z0-9-]+)/i);
        if(locale_match)
            use_locale = locale_match[1];
    }


    return use_locale;
}


function insertNavBar() {

    var use_locale = readLocale();

    // TODO REFACTOR, this fn is becoming a generic junk drawer for includes.
    var staticNavBar = "/include/mainnav.html?" + use_locale;
    var staticLdNavBar = "/include/ldnav.html?" + use_locale;
    var staticLdModalNavBar = "/include/ldmodalnav.html?" + use_locale;
    var staticFooter = "/include/footernav.html?" + use_locale;
    var staticPressKit = "/include/presskit.html?" + use_locale;
    var staticPlatformNav = "/include/platformlnav.html?" + use_locale;
    var staticEchoNav = "/include/echolnav.html?" + use_locale;
    var staticPulseNav = "/include/pulselnav.html?" + use_locale;
	var staticStudentPromo = "/include/studentpromo.html?" + use_locale;


    var navspot = $('navMenu') || $('ldNavBar');

    if(navspot) {
        if(window.is_livescribe_desktop) {

            if($('mast')) $('mast').remove();


            $$('#clicktrail a').each(function(el) {
                var old_href = $(el).readAttribute('href');
                if((old_href == '/index.html') ||
                   (old_href == '/')) {
                    $(el).writeAttribute('href', '/cgi-bin/WebObjects/LDApp.woa/wa/default');
                }
            });
            

            new Ajax.Updater(navspot,
                             staticLdNavBar, {
                                 method: "GET",
                                 onComplete: function(_) { updateGlobalCountrySelector(use_locale); }
                             });

        }
        else {
            new Ajax.Updater(navspot,
                             staticNavBar, {
                                 method: "GET",
                                 onComplete: function(transport) {
                                     tnavInit();
                                 }
                             });
        }
    };

    if($('footerMenu') && (! window.is_livescribe_desktop))
        new Ajax.Updater('footerMenu', staticFooter, {
            method: "GET",
            onComplete: function(_) { updateGlobalCountrySelector(use_locale); }
        });

    if($('ldModalNavBar'))
        new Ajax.Updater('ldModalNavBar', staticLdModalNavBar, {
            method: "GET",
            onComplete: function(_) { updateGlobalCountrySelector(use_locale); }
        });

    // TODO should this be here?
    if($('pressKit'))
        new Ajax.Updater('pressKit', staticPressKit , { method: "GET" });

    if($('platformnav'))
        new Ajax.Updater('platformnav', staticPlatformNav , { method: "GET" });

    if($('echonav'))
        new Ajax.Updater('echonav', staticEchoNav , { method: "GET" });

    if($('pulsenav'))
        new Ajax.Updater('pulsenav', staticPulseNav , { method: "GET" });
	
	if($('studentPromo'))
        new Ajax.Updater('studentPromo', staticStudentPromo , { method: "GET" });

}



// TODO: Deploy me only to the home page, or pages that contain me.
// Driver for TOP NAV, HOME PAGE locale selector
function intlselector() {

    // CONFIGURATION

    var special_cases = {
        'e-motion' : function(_ignored) {
            var message = 'Stai per lasciare il sito www.livescribe.com. ' +
                'Clicca "OK" per accedere al sito italiano, oppure premi "cancel" per annullare.\n\n' +
                'You are now leaving www.livescribe.com.  Please click "OK" to go to the Italian site, or click "Cancel" to stay.';

            if(confirm(message)) {
                window.location = 'http://www.livescribe.e-motion.it/';
            }
        }
    };

    var common_case = function(locale_control_value) {
        location.href = "/?locale=" + locale_control_value;
    };

    // LOGIC

    var use_locale = readLocale();
    var form = $('intl_select');

    if(form) {
        var input = form['choose_country'];
        var found = -1;
        var int_index = -1;

        for(var i=0; i < input.length; i++) {
            var locale_selection = input[i].value;

            if(use_locale == locale_selection) {
                found = i;
            }
            else if("int" == locale_selection) {
                int_index = i;
            }
        }

        if(found == -1) {
            found = int_index;
        }

        input.selectedIndex = found;

        $(input).observe('change', function(event){
            var locale_control_value = $F(input);
            if("undefined" == typeof special_cases[locale_control_value]) {
                common_case(locale_control_value);
            }
            else {
                special_cases[locale_control_value](locale_control_value);
            }

            // under most circumstances, we should never arrive here at all...
            input.selectedIndex = found;
        });
    }

}

Event.observe(document, 'dom:loaded', intlselector);
Event.observe(document, 'dom:loaded', insertNavBar);


