﻿if(typeof(Pathfinder) == 'undefined') Pathfinder = {};

Pathfinder.setEvent = function(element, name, delegate, detaching){
    if(element && (element == window || element.nodeType) && typeof(delegate) == 'function'){
	    if(element.attachEvent) return element[!detaching ? 'attachEvent' : 'detachEvent'](name, delegate);
	    if(element.addEventListener) return element[!detaching ? 'addEventListener' : 'removeEventListener'](name.replace(/^on/, ''), delegate, false);
            
	    element[name] = !detaching ? delegate : null;                    
    }
}

Pathfinder.getElementFromEventArgs = function(eventArgs){
    if(!eventArgs) return null;
    
    var element = null;
    
    if(eventArgs.srcElement) element = eventArgs.srcElement;
    if(eventArgs.target) element = eventArgs.target;
    
    return element;
}


Pathfinder.LeftNavigation = new function() {
    var _this = this;

    this.initialize = initialize;

    function initialize() {
        setEvents(false);
        hideLinksWhenSignedOut();
    }

    function dispose() {
        setEvents(true);

        _this = null;
    }

    function hideLinksWhenSignedOut() {
        var link = document.getElementsByTagName('a');
        for (var i = 0; i < link.length; i++) {
            if (link[i].getAttribute('showWhenSignedIn') == 'true') {
                link[i].parentNode.className = 'hideOnSignedOut';
            }
        }
    }

    function setEvents(disposing) {
        Pathfinder.setEvent(window, 'onunload', dispose, disposing);

        var menuItems = document.getElementById('leftNavGroupedItems');
        if (!menuItems) return;

        var items = menuItems.getElementsByTagName('a');

        for (var i = 0, link; link = items[i]; i++) {
            if (link.href != 'javascript:;') continue;

            if (link.getAttribute('level') == '2') Pathfinder.setEvent(link, 'onclick', onLevel2Click, disposing);
            if (link.getAttribute('level') == '3') Pathfinder.setEvent(link, 'onclick', onLevel3Click, disposing);

            Pathfinder.setEvent(link, 'onmouseover', onSetWindowStatus, disposing);
            Pathfinder.setEvent(link, 'onmouseout', onClearWindowStatus, disposing);
        }
    }

    function onLevel2Click(e) {
        updateLevelLinkParent(e, { 'level2': 'level2 off', 'level2 off': 'level2', 'level2Selected': 'level2Selected off', 'level2Selected off': 'level2Selected' });
    }

    function onLevel3Click(e) {
        updateLevelLinkParent(e, { 'level3 contracted off': 'level3 expanded on', 'level3 expanded on': 'level3 contracted off' });
    }

    function updateLevelLinkParent(e, options) {
        var link = Pathfinder.getElementFromEventArgs(e);
        if (!link) return;

        link.parentNode.className = options[link.parentNode.className];
        link.blur();
    }

    function onSetWindowStatus(e) {
        var element = Pathfinder.getElementFromEventArgs(e);
        if (!element) return;

        window.status = element.innerHTML;

        return true;
    }

    function onClearWindowStatus(e) {
        var element = Pathfinder.getElementFromEventArgs(e);
        if (!element) return;

        window.status = '';

        return true;
    }
}

Pathfinder.OM = new function(){    
    var _omForm;
    var _omPath;
    
    this.initialize = initialize;
    this.submit = submit;
   
    function initialize(omPath){
        setEvents(false);
        
        _omForm = document.forms['OMForm'];
        if(!_omForm) return;
        
        var storeId = _omForm.StoreID ? _omForm.StoreID.value : '';
        var localeCode = _omForm.Localecode ? _omForm.Localecode.value : '';
        var newTrans = _omForm.NewTrans ? _omForm.NewTrans.value : '';
        
        _omPath = omPath;
        _omForm.action = String.format('{0}?storeid={1}&localecode={2}&newtrans={3}', _omPath, storeId, localeCode,  newTrans);
    }
    
    function setEvents(disposing){
        Pathfinder.setEvent(window, 'onunload', dispose, disposing); 
    }
  
    function dispose(){
        setEvents(true);
        
        _omForm = _omPath = null;      
    }  
    
    function submit(){
        if(!_omForm) throw '_omForm not initialized';
        
        _omForm.submit();
    }
}

Pathfinder.DropDown = function(listId) {
    var _innerDropDown;
    var _id = listId;

    this.dispose = dispose;
    this.isLoaded = isLoaded;
    this.add = add;
    this.clear = clear;
    this.setOnChange = setOnChange;
    this.setOnLoad = setOnLoad;
    this.currentText = currentText;
    this.currentValue = currentValue;
    this.currentOptions = currentOptions;
    this.setSelection = setSelection;
    this.setWidth = setWidth;

    initialize();

    function initialize() {
        _innerDropDown = document.getElementById(_id);
    }

    function dispose() {
        _innerDropDown = _id = null;
    }

    function isLoaded() {
        return _innerDropDown != null;
    }

    function add(text, value) {
        if (!_innerDropDown) return;

        _innerDropDown.options[_innerDropDown.options.length] = new Option(text, value);
    }

    function clear() {
        if (_innerDropDown) _innerDropDown.options.length = 0;
    }

    function setOnChange(delegate, disposing) {
        Pathfinder.setEvent(_innerDropDown, 'onchange', delegate, disposing);
    }

    function setOnLoad(delegate, disposing) {
        Pathfinder.setEvent(_innerDropDown, 'onload', delegate, disposing);
    }

    function currentText() {
        return (_innerDropDown && _innerDropDown.options.length > 0) ? _innerDropDown.options[_innerDropDown.selectedIndex].text : '';
    }

    function currentValue() {
        return (_innerDropDown && _innerDropDown.options.length > 0) ? _innerDropDown.options[_innerDropDown.selectedIndex].value : '';
    }

    function currentOptions() {
        return _innerDropDown ? _innerDropDown.options : null;
    }

    function setSelection(byText, selection) {
        if (!_innerDropDown) return;

        var found = false;

        for (var i = 0, option; option = _innerDropDown.options[i]; i++) {
            var search = option[byText ? "text" : "value"];

            if (!selection.equals(search)) continue;

            _innerDropDown.selectedIndex = i;
            found = true;

            break;
        }

        if (!found) _innerDropDown.selectedIndex = 0;
    }

    function setWidth(width) {
        if (_innerDropDown) _innerDropDown.style.width = width;
    }
}

Pathfinder.ControlState = function(inputId){
    var _innerInput;
    var _id = inputId;
    
    this.dispose = dispose;
    this.getValue = getValue;
    this.setValue = setValue;
    
    initialize();
    
    function initialize(){
        _innerInput = document.getElementById(_id);
    }
    
    function dispose(){
        _innerInput = _id = null;
    }
    
    function getValue(){
        return _innerInput ? _innerInput.value : '';
    }
    
    function setValue(value){
        if(_innerInput) _innerInput.value = value;
    }   
}

Pathfinder.GeographySelections = new function(){
    var _countryList;
    var _regionList;
    var _regionState;
    var _regionStartup;
    
    this.initialize = initialize;
    
    function initialize(countryListId, regionListId, regionStateId){
        _countryList = new Pathfinder.DropDown(countryListId);
        _regionList = new Pathfinder.DropDown(regionListId);
        _regionState = new Pathfinder.ControlState(regionStateId);
        
        var selectedRegion = _regionState.getValue();
        setEvents(false);
        
        if(_countryList.currentValue() == '-1') return;

        _regionStartup = function(){
            _regionState.setValue(selectedRegion);
            _regionList.setSelection(false, selectedRegion);
        }
        
        onCountryListChange();
    }
    
    function setEvents(disposing){
        Pathfinder.setEvent(window, 'onunload', dispose, disposing);
        
        _countryList.setOnChange(onCountryListChange, disposing);
        _regionList.setOnChange(onRegionListChange, disposing);
    }
    
    function dispose(){
        setEvents(true);
        
        _countryList.dispose();
        _regionList.dispose();
        
        _countryList = _regionList = _regionState = _regionStartup = null;
    }
    
    function onCountryListChange(){    
        if(!_countryList.isLoaded() || !_regionList.isLoaded()) return;
             
        var countryCode = _countryList.currentValue();

        _regionList.clear();
        
        load(String.format('/support/geographyhandler.ashx?country={0}', encodeURIComponent(countryCode)), loadRegions);
        function loadRegions(responseText){
            try{
                _regionList.add('Select Region', '-1');
                
                var regions = eval(responseText);
                if(!regions || !regions.Geographies) return;
                
                for(var i = 0, region; region = regions.Geographies[i]; i++){
                    _regionList.add(region.name, region.code);
                }

		        onRegionListChange();
            }
            catch(e){/* debugger; throw e; */}
        }
    }
    
    function onRegionListChange(){
        if(!_regionList.isLoaded()) return;
      
        _regionState.setValue(_regionList.currentValue());
        
        if(_regionStartup){
	        _regionStartup();
	        _regionStartup = null;
        }
    }
}

Pathfinder.ShipMethodInfo = function(code, title, message){
    this.code = code;
    //this.title = title;
    this.message = message;
    this.dispose = dispose;
    
    function dispose(){
        this.code = this.title = this.message = null;
    }
}

Pathfinder.ShipMethods = new function(){
    var _shipMethodList;
    var _title;
    var _message;
    var _methods;
    
    this.initialize = initialize;
    this.add = add;
    this.apply = apply;
    
    function initialize(shipMethodListId){
        _shipMethodList = new Pathfinder.DropDown(shipMethodListId);
       // _title = document.getElementById('ShipMethodTitleLabel');
        _message = document.getElementById('ShipMethodMessageLabel');
        _methods = {};
        
        _methods['none'] = new Pathfinder.ShipMethodInfo('none', '', 'No ship method description available');
        
        setEvents(false);
    }
    
    function add(code, title, message){
        _methods[code.toLowerCase()] = new Pathfinder.ShipMethodInfo(code.toLowerCase(), title, message);
    }
    
    function apply(){
        onShipMethodListChange(null);
    }
    
    function dispose(){
        setEvents(true);
        
        if(_shipMethodList) _shipMethodList.dispose();
        
        for(var i = 0, method; method = _methods[i]; i++){
            method.dispose();
        }

        //_shipMethodList = _title = _message = _methods = null;
        _shipMethodList = _message = _methods = null;
    }
    
    function setEvents(disposing){
        Pathfinder.setEvent(window, 'onunload', dispose, disposing);
        
        _shipMethodList.setOnChange(onShipMethodListChange, disposing);
    }
    
    function onShipMethodListChange(e){
        //if((!_shipMethodList.isLoaded()) || (!_title) || (!_message)) return;
        if ((!_shipMethodList.isLoaded())  || (!_message)) return;
        
        var code = _shipMethodList.currentValue().toLowerCase();
        var methodInfo = _methods[code] || _methods['none'];
        //var title = methodInfo.title;
        var message = methodInfo.message;

        //_title.innerHTML = unescape(title);
        _message.innerHTML = unescape(message);
    }
}

Pathfinder.PrintImage = function(imageId, buttonId, pageTitle) {
    var _image = document.getElementById(imageId);
    var _button = document.getElementById(buttonId);
    var _buttonHover = new Pathfinder.HoverImage(buttonId, 'hover');

    var _imageSrc;
    var _pageTitle;

    initialize();

    function initialize() {
        if (!_image || !_button) throw "button not set";
        
        _imageSrc = _image.src;
        _pageTitle = pageTitle || "Print";

        setEvents(false);
    }

    function dispose() {
        setEvents(true);

        _image = _imageSrc = _pageTitle = _button = _buttonHover = null;
    }

    function setEvents(disposing) {
        Pathfinder.setEvent(window, 'onunload', dispose, disposing);
        Pathfinder.setEvent(_button, 'onclick', button_onclick, disposing);
    }

    function button_onclick() {
        var printWindow = window.open('about:blank', '_blank');
        printWindow.document.open();
        printWindow.document.write(createPage(_imageSrc, pageTitle));
        printWindow.document.close();
    }

    function createPage(imgSrc, pageTitle) {
        var returnResult = new StringBuilder();

        returnResult.append('<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 3.2//EN">');
        returnResult.append('<html><head><title>View/Print Label</title>');
        returnResult.append('<script>');
        returnResult.append('function step1() { setTimeout(\'step2()\', 100); }\n');
        returnResult.append('function step2() { window.print(); window.close(); }\n');
        returnResult.append('</script>\n</head>\n');
        returnResult.append('<style>');
        returnResult.append('.small_text {font-size: 80%;}');
        returnResult.append('.large_text {font-size: 115%;}');
        returnResult.append('</style>');
        returnResult.append('<body bgcolor="#FFFFFF">');
        returnResult.append('<table border="0" cellpadding="0" cellspacing="0" width="600"><tr>');
        returnResult.append('<td height="410" align="left" valign="top"><B class="large_text">View/Print Label</B>&nbsp;<br />');
        returnResult.append('<ol class="small_text"> <li><b>Print the label:</b> &nbsp;');
        returnResult.append('Select Print from the File menu in this browser window to print the label below.<br><br><li><b>');
        returnResult.append('Fold the printed label at the dotted line.</b> &nbsp;');
        returnResult.append('Place the label in a UPS Shipping Pouch. If you do not have a pouch, affix the folded label using clear plastic shipping tape over the entire label.<br><br><li><b>GETTING YOUR SHIPMENT TO UPS<br>');
        returnResult.append('Customers without a Daily Pickup</b><ul><li>Take this package to any location of The UPS Store®, UPS Drop Box, UPS Customer Center, UPS Alliances (Office Depot® or Staples®) or Authorized Shipping Outlet near you or visit <a href="http://www.ups.com/content/us/en/index.jsx">www.ups.com/content/us/en/index.jsx</a> and select Drop Off.<li>');
        returnResult.append('Air shipments (including Worldwide Express and Expedited) can be picked up or dropped off. To schedule a pickup, or to find a drop-off location, select the Pickup or Drop-off icon from the UPS tool bar.  </ul> <br>');
        returnResult.append('<b>Customers with a Daily Pickup</b><ul><li>');
        returnResult.append('Your driver will pickup your shipment(s) as usual. </ul>');
        returnResult.append('</ol></td></tr></table><table border="0" cellpadding="0" cellspacing="0" width="600">');
        returnResult.append('<tr><td class="small_text" align="left" valign="top">&nbsp;&nbsp;&nbsp;<a name="foldHere">FOLD HERE</a></td></tr>');
        returnResult.append('<tr><td align="left" valign="top"><hr></td></tr></table>');
        returnResult.append('<table><tr><td height="10">&nbsp;</td></tr></table>');
        returnResult.append('<table border="0" cellpadding="0" cellspacing="0" width="650" >');
        returnResult.appendFormat('<tr><td align="left" valign="top"><IMG SRC="{0}" height="392" width="651"></td></tr></table>', imgSrc);
        returnResult.append('</body></html>');

        return returnResult.toString();
    }
}

Pathfinder.Terms = new function() {
    var _panel;
    var _checkboxPanel;
    var _problemTypeList;
    var _privacyLabel;
    var _legalLabel;

    this.initialize = initialize;
    this.toggleTerms = toggleTerms;

    function initialize(panelId, checkboxPanelId, problemTypeListId, privacyLabel, legalLabel) {
        _panel = document.getElementById(panelId);
        _checkboxPanel = document.getElementById(checkboxPanelId);
        _problemTypeList = new Pathfinder.DropDown(problemTypeListId);
        _privacyLabel = document.getElementById(privacyLabel);
        _legalLabel = document.getElementById(legalLabel);

        setEvents(false);
    }

    function dispose() {
        setEvents(true);

        _problemTypeList.dispose();

        _panel = _checkboxPanel = _problemTypeList = _privacyLabel = _legalLabel = null;
    }

    function setEvents(disposing) {
        Pathfinder.setEvent(window, 'onunload', dispose, disposing);

        //    if(_problemTypeList.isLoaded()) _problemTypeList.setOnChange(onProblemTypeListChange, disposing);
    }

    /* function onProblemTypeListChange(e){
    if((!_problemTypeList.isLoaded()) || (!_panel) || (!_checkboxPanel) || (!_privacyLabel) || (!_legalLabel)) return;
        
    var problemCode = _problemTypeList.currentValue();
    var display = problemCode.equals('c09') || problemCode.equals('c47') ? 'block' : 'none';
        
    _panel.style.display = display;
    _checkboxPanel.style.display = display;
    _privacyLabel.style.display = display == 'block' ? 'none' : 'block';
    _legalLabel.style.display = display;
    }*/

    function toggleTerms(display) {
        _panel.style.display = display;
         _checkboxPanel.style.display = display;
         _privacyLabel.style.display = display == 'block' ? 'none' : 'block';
         _legalLabel.style.display = display;
    }
}

Pathfinder.RepairPrice = new function() {
    var _priceLabel;
    var _problemTypeList;
    var _countryList;
    var _productType;
    var _productSerialNumber;

    this.initialize = initialize;

    function initialize(priceLabelId, problemTypeListId, countryListId, productType, productSerialNumber) {
        _priceLabel = document.getElementById(priceLabelId);
        _problemTypeList = new Pathfinder.DropDown(problemTypeListId);
        _countryList = new Pathfinder.DropDown(countryListId);
        _productType = productType;
        _productSerialNumber = productSerialNumber;

        setEvents(false);
    }

    function dispose() {
        setEvents(true);

        _problemTypeList.dispose();
        _countryList.dispose();

        _priceLabel = _problemTypeList = _countryList = _productType = _submitBtn = null;
    }

    function setEvents(disposing) {
        Pathfinder.setEvent(window, 'onunload', dispose, disposing);
        Pathfinder.setEvent(window, 'onload', onListChange, disposing);

        if (_problemTypeList.isLoaded()) _problemTypeList.setOnChange(onListChange, disposing);
        if (_problemTypeList.isLoaded()) _problemTypeList.setOnLoad(onListChange, disposing);

        if (_countryList.isLoaded()) _countryList.setOnChange(onListChange, disposing);
    }

    function onListChange(e) {
        if ((!_priceLabel) || (!_problemTypeList.isLoaded()) || (!_countryList.isLoaded()) || (!_productType)) return true;


        var problemType = encodeURIComponent(_problemTypeList.currentValue());
        var countryCode = encodeURIComponent(_countryList.currentValue());
        var productType = encodeURIComponent(_productType);
        var productSerialNumber = encodeURIComponent(_productSerialNumber);

        _priceLabel.innerHTML = 'Loading...';
        if (problemType == '-1') {
            _priceLabel.innerHTML = '$0.00';
            return true;
        }
        else {
            try {
                var url = String.format('/support/repairprice.ashx?ProblemType={0}&CountryCode={1}&ProductType={2}&ProductSerialNumber={3}', problemType, countryCode, productType, productSerialNumber);
                load(url, onResponse);
            }
            catch (err) {
            }
        }
        
        function onResponse(responseText) {
            _priceLabel.innerHTML = '$' + responseText;
            //if value is 0.00, then T&C should open up...
            if (responseText == '0.00') {
                Pathfinder.Terms.toggleTerms('block');
            }
            else {
                Pathfinder.Terms.toggleTerms('none');
            }
        }
        return true;
    }
}

Pathfinder.EntitlementOffer = function(name){     
    this.name = name;
    this.addShipMethod = addShipMethod;
    this.dispose = dispose;
    this.methods = {};
    
    function addShipMethod(code, text){
        this.methods[code] = text;
    }
    
    function dispose(){
        this.name = this.addShipMethod = this.methods = null;
    }
}

Pathfinder.AdvancedExchange = new function(){
    var _yesRadio;
    var _noRadio;
    var _shipMethodList;
    var _standardOffer;
    var _advancedOffer;
    
    this.initialize = initialize;
    
    function initialize(yesRadioId, noRadioId, shipMethodListId, standardOffer, advancedOffer){
        _yesRadio = document.getElementById(yesRadioId);
        _noRadio = document.getElementById(noRadioId);
        _shipMethodList = new Pathfinder.DropDown(shipMethodListId);    
        _standardOffer = standardOffer;
        _advancedOffer = advancedOffer;
        
        setEvents(false);
        
        if(_yesRadio.checked) onYesClick();
        if(_noRadio.checked) onNoClick();
    }
    
    function dispose(){
        setEvents(true);
        
        _shipMethodList.dispose();
        _standardOffer.dispose();
        _advancedOffer.dispose();
        
        _yesRadio = _noRadio = _shipMethodList = _standardOffer = _advancedOffer = null;
    }
    
    function setEvents(disposing){
        Pathfinder.setEvent(window, 'onunload', dispose, disposing);
        Pathfinder.setEvent(_yesRadio, 'onclick', onYesClick, disposing);
        Pathfinder.setEvent(_noRadio, 'onclick', onNoClick, disposing);
    }
    
    function onYesClick(e){
        if(!_shipMethodList.isLoaded()) return;
        
        _shipMethodList.clear();
       
        for(var code in _advancedOffer.methods){
            var text = _advancedOffer.methods[code];
            
            _shipMethodList.add(text, code);
        }
        
        Pathfinder.ShipMethods.apply();
    }
    
    function onNoClick(e){
        if(!_shipMethodList.isLoaded()) return;
        
        _shipMethodList.clear();
       
        for(var code in _standardOffer.methods){
            var text = _standardOffer.methods[code];
            
            _shipMethodList.add(text, code);
        }        
        
        Pathfinder.ShipMethods.apply();
    }
}

Pathfinder.SingleClickButton = function(buttonId, facadeId){
    var _button;
    var _facade;
       
    initialize();
    
    function initialize(){
        _button = document.getElementById(buttonId);
        _facade = document.getElementById(facadeId);
        
        setEvents(false);
    }
    
    function dispose(){
        setEvents(true);
        
        _button = _facade = null;
    }
    
    function setEvents(disposing){
        Pathfinder.setEvent(window, 'onunload', dispose, disposing);
        Pathfinder.setEvent(_button, 'onclick', onButtonClick, disposing);
    }
    
    function onButtonClick(e){
        _button.style.display = 'none';
        _facade.style.display = 'block';
    }
}

Pathfinder.HoverImage = function(imageId, hoverText){
    var _image;
    var _defaultPath;
    var _hoverPath;
    
    initialize();
    
    function initialize(){
        _image = document.getElementById(imageId);
        if(!_image) return;
        
        var source = _image.src;
        var imageStart = source.lastIndexOf('/') + 1;      
        var leftPart = source.substr(0, imageStart);    
        var rightPart = source.substr(imageStart, 50);      
        var parts = rightPart.split('.');
        
        _defaultPath = source;
        _hoverPath = [leftPart, parts[0], hoverText, '.', parts[1]].join('');        
        
        setEvents(false);
    }
    
    function dispose(){
        setEvents(true);
        
        _image = _defaultPath = _hoverPath = null;
    }
    
    function setEvents(disposing){
        Pathfinder.setEvent(window, 'onunload', dispose, disposing);
        Pathfinder.setEvent(_image, 'onmouseover', image_onMouseOver, disposing);
        Pathfinder.setEvent(_image, 'onmouseout', image_onMouseOut, disposing);
    }
    
    function image_onMouseOver(){
        _image.src = _hoverPath;
        _image.style.cursor = 'pointer';
    }
    
    function image_onMouseOut(){
        _image.src = _defaultPath;
        _image.style.cursor = 'default';
    }
}