/**
 * @file ec.js
 */
var ec = {
    /**
     * load
     *
     * Loads css and javascript files.
     *
     * @member  ec
     * @param {Array}   fileNames   Array of files to be loaded.
     * @param {String}  type        Type of files to be loaded.
     * @private
     */
    _load: function(fileNames, type) {
        switch(type){
            case 'js':
                for (var i = 0; i < fileNames.length; i++) {
                    this._include(fileNames[i] + '.js', 'js');
                }
                break;
            case 'css':
                for (var i = 0; i < fileNames.length; i++) {
                    this._include(fileNames[i] + '.css', 'css');
                }
                break;
        }
    },
    /**
     * _include
     *
     * Includes css and javascript files into HTML page.
     *
     * @member  ec
     * @param {String}  fileName   Name of file to be included.
     * @param {String}  type       Type of file to be included.
     * @private
     */
    _include: function(fileName, type) {
        var path = this._getPath();
        var head = document.getElementsByTagName("head")[0];
        switch(type){
            case 'js':
                var coreScriptElement = document.createElement('script');
                var src = path + fileName;
                coreScriptElement.src = src;
                coreScriptElement.id = src;
                coreScriptElement.setAttribute('defer', true);
                head.appendChild(coreScriptElement);
                if(ec.isIE()){
                    coreScriptElement.onreadystatechange = function() {
                        if (coreScriptElement.readyState == "complete") {
                            ec.script.cleanup(src);
                        }
                    };
                } else {
                    coreScriptElement.onload = function(){ec.script.cleanup(src)};
                }


                break;
            case 'css':
                var cssNode = document.createElement('link');
                cssNode.type = 'text/css';
                cssNode.rel = 'stylesheet';
                cssNode.href = path + fileName;
                cssNode.media = 'screen';
                head.appendChild(cssNode);
                break;
        }

    },
    /**
     * _getPath
     *
     * Gets path of this file.
     *
     * @member  ec
     * @returns {String}  path  Path of this file.
     * @public
     */
    _getPath: function(){
        // Get path for ec.js, the other components use the same path.
        var scriptElements = document.getElementsByTagName( "script" );

        for (var index in scriptElements) {
            if (scriptElements[index].src && scriptElements[index].src.match(/ec\.js(\?.*)?$/)) {
                var path = scriptElements[index].src.replace(/ec\.js(\?.*)?$/,'');
            }
        }

        return path;
    },
    /**
     * require
     *
     * Loads the needed css and js files for the component passed in.
     *
     * @member  ec
     * @param {String}  component   Name of the componenet that is required.
     * @public
     */
    require: function(component){
        try {
            updateBackImageSize();
        } catch (e){}
        return false;
        switch(component){
            case 'base':
                ec._load(["_base/_utility", 
                          "_base/_dom", 
                          "_base/_ajax", 
                          "_base/_fx",
                          "_base/_modal",
                          "components/local/menu",
                          "config"], 'js');
                ec._load(['components/local/uploader'], 'js');
                ec.run('load', 'window.__uploader');
                break;
            case 'imageManager':
                ec._load(['components/image'], 'js');
                ec._load(['components/local/imageManager'], 'js');
                ec._load(['css/image'], 'css');
                break;
            case 'design':
                ec._load(['components/design'], 'js');
                break;
            case 'leads':
                ec._load(['components/local/leads'], 'js');
                break;
            case 'designSelector':
                ec._load(['components/local/designSelector'], 'js');
                ec._load(['components/local/leads'], 'js');
                ec._load(['components/local/tab'], 'js');
                break;
            case 'editor':
                ec._load(['components/local/editor'], 'js');
                break;
            case 'options':
                ec._load(['components/local/options'], 'js');
                break;
            case 'checkout':
                ec._load(['components/local/checkout'], 'js');
                ec._load(['components/local/promotion'], 'js');
                break;
            case 'promotion':
                ec._load(['components/local/promotion'], 'js');
                ec._load(['css/checkout'], 'css');
                break;
            case 'pricing':
                ec._load(['components/pricing'], 'js');
                break;
            case 'addressList':
                ec._load(['components/local/addressList'], 'js');
                break;
            case 'account':
                ec._load(['components/local/account'], 'js');
                break;
            case 'accountAdmin':
                ec._load(['components/local/accountAdmin'], 'js');
                break;
            case 'ga':
                ec._load(['components/local/ga'], 'js');
                break;
        }
    },
    /**
     * jsonDataStore
     *
     * Array (object) that stores returned json from the API.
     *
     * @member  ec
     * @public
     */
    jsonDataStore: {},
    /**
     * _callApi
     *
     * Loads the needed css and js files for the component passed in.
     *
     * @member  ec
     * @param {String}  urn         Uniform resource name.  Usually follows the convention 'controller/action'.
     * @param {Object}  parameters  Parameters to be passed to the API.  Example: parameters.property = value;
     * @param (String}  callback    Name of function to call when the json is returned.  The json will be the
     * parameter of the callback function.  Example: callbackFunction(returnedJson);
     * @private
     */
    _callApi: function(urn, parameters, callback) {
        if (parameters) {
            var parameterString = '';
            for (var key in parameters) {
                parameterString += '&' + key + '=' + parameters[key];
            }
        }

        var c = new crosstalk();

        c.appendScript(ec.config.apiHost +
                       "/" + urn + "/?key=" +
                       ec.config.apiKey +
                       parameterString +
                       "&format=js&callback=" +
                       callback, urn);
    },
    onload: function(functionCall){
        var oldOnload = window.onload;
        if (typeof window.onload != 'function') {
            window.onload = functionCall;
        } else {
            window.onload = function() {
                if (oldOnload) {
                    oldOnload();
                }
                functionCall();
            }
        }
    },
    run: function(functionName, object, parameters) {
        var newObject = eval(object);
        
        if (typeof parameters == "string") {
            var newParameters = parameters;
        } else {
            var newParameters = parameters;
        }

        if (ec.isReady(newObject)) {
            newObject[functionName](newParameters);
        } else {
            setTimeout(function(){ec.run(functionName, object, parameters);}, 50);
        }
    },
    isReady: function(object) {
        if(typeof(object) === 'object') {
            return true;
        } else {
            return false;
        }
    },
    pause: function(milliSeconds) {
        var date = new Date();
        var currentDate = null;

        do {
            currentDate = new Date();
        } while(currentDate - date < milliSeconds);
    },
    /**
     * getBrowser
     *
     * Returns the name of the browser being used.
     *
     * @member  utility
     * @public
     * @return {String} Name of browser.
     */
    getBrowser: function() {
        if (!!(window.attachEvent && !window.opera)) {
            if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
                var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
                if (ieversion>=8) {
                    return "IE8";
                } else if (ieversion>=7) {
                    return "IE7";
                } else if (ieversion>=6) {
                    return "IE6";
                } else if (ieversion>=5) {
                    return "IE5";
                }
            }
        }
        if (!!window.opera) return "Opera";
        if (navigator.userAgent.indexOf('AppleWebKit/') > -1) return "WebKit";
        if (navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1) return "Gecko";
        if (!!navigator.userAgent.match(/Apple.*Mobile.*Safari/)) return "MobileSafari";
    },
    /**
     * isIE
     *
     * Checks if browser is IE
     *
     * @member  utility
     * @public
     * @return {Boolean}    Returns true if browser is IE.
     */
    isIE: function() {
        var browser = this.getBrowser();
        if (browser.match('IE')) {
            return true;
        } else {
            return false;
        }
    }
}

ec.script = {
    cleanup: function(id) {
        var script = document.getElementById(id);
        var head = document.getElementsByTagName('head')[0];
        /**
         * IE throws an error if removeChild is called inside a modal.  We'll just skip removing the element for now
         * as the element will be removed when the modal window is closed. 
        **/ 
        try {
            head.removeChild(script);
        } catch (e) {
            return;
        }
    }
}

function getElementsByClassName(className) {
    var retnode = [];
    var myclass = new RegExp('\\b'+className+'\\b');
    var elem = this.getElementsByTagName('*');
    for (var i = 0; i < elem.length; i++) {
        var classes = elem[i].className;
        if (myclass.test(classes)) retnode.push(elem[i]);
    }
    return retnode;
}

function getElementsByClassNameForIE(className, thisObj) {
    var retnode = [];
    var myclass = new RegExp('\\b'+className+'\\b');
    var elem = thisObj.getElementsByTagName('*');
    for (var i = 0; i < elem.length; i++) {
        var classes = elem[i].className;
        if (myclass.test(classes)) retnode.push(elem[i]);
    }
    return retnode;
}
function trim() {
    return this.replace(/^\s*/, "").replace(/\s*$/, "");
}
document.getElementsByClassName = getElementsByClassName;

if (!window.Element){
    window.Element = function(){};
    window.htmlObj = new Element();
}

if (window.Element) {
    Element.prototype.getElementsByClassName = getElementsByClassName;
};

if (typeof String.trim == "undefined") {
    String.prototype.trim = trim;
}
if (typeof Array.inArray == "undefined") {
    Array.prototype.inArray = function(values) {
        var arrayIndex;
        var valueIndex;
        
        for (arrayIndex in this) {
            if (typeof values == "string") {
                if (this[arrayIndex] == values) return true;
            } else {
                for (valueIndex in values) {
                    if (this[arrayIndex] == values[valueIndex]) return true;
                }
            }
        }
        return false;
    }
}
function $$modal(url) {
    ec.run('open', 'ec._modal', url);
}
/**
 * @file config.js
 */
var _config = {
    format: 'html',
    apiKey: '',
    apiHost: '',
    siteId: 2,
    image: {
        categoryDiv: 'ec-imageCategories',
        libraryDiv: 'ec-imageLibrary',
        topPaginationDiv: 'ec-imageLibraryPaginationTop',
        bottomPaginationDiv: 'ec-imageLibraryPaginationBottom',
        messageDiv: 'ec-image-message'
    },
    design: {
        libraryDiv: 'ec-designCollection',
        categoryDiv: 'ec-categoryMenu',
        currentSelected: 'selectedDesigns',
        topPaginationDiv: 'ec-paginationTop',
        bottomPaginationDiv: 'ec-paginationBottom'
    },
    setApiHost: function(value){
        if ('' != value && value) {
            ec.config.apiHost = value;
        }
    },
    setApiKey: function(value){
        if ('' != value && value) {
            ec.config.apiKey = value;
        }
    },
    setSiteId: function(value){
        if ('' != value && value) {
            ec.config.siteId = value;
        }
    }
}
// Don't overwrite config if it already exists.
window.isAjaxActive = false;
window.ajaxLoaderTimerId = 0;
if (!ec.config) ec.config = _config;
_config = {};
/**
 * @file _base/_ajax.js
 */
var _ajax = {
    getJson: function() {
    },
    getHtml: function(url, div, callback) {
        ec._ajax.method = 'GET';
        ec._ajax._html(url, div, callback);
    },
    setHtml: function(url, div, callback, parameters) {
        ec._ajax.method = 'POST';
        ec._ajax._html(url, div, callback, parameters);
    },
    _html: function(url, div, callback, parameters){
        ec._ajax.response = 'HTML';
        
        if (!parameters){
            var parameters = '';
        }
        
        ec._ajax.getRequest({
            parameters: parameters,
            url: url,
            onComplete: function(html){
                if (div) {
                    div.innerHTML = html;
                }
                if (typeof callback == 'function') {
                    callback(html);
                }
            }
        });
    },
    url: null,
    httpRequest: null,
    response: 'JSON',
    jsonResponse: null,
    method: 'GET',
    options: null,
    getRequest: function( options ){
        
        if (typeof options != 'object') {
            options = {};
        }
        
        ec._ajax.url = options.url || null;
        ec._ajax.options = options;
        
        ec._ajax.url = ec._ajax.url.replace("/ec", "/ec/ajax");

        try {
            ec.__ga.trackEventByUrl(ec._ajax.url);
        } catch (e) {
            if (!window.errors) window.errors = new Array;
            window.errors.push(e);
        }

        if (window.XMLHttpRequest) {
            ec._ajax.httpRequest = new XMLHttpRequest();
        } else {
            if (ec.isIE()) {
                ec._ajax.httpRequest = new ActiveXObject("Microsoft.XMLHTTP"); 
            } else {
                alert('This site requires Ajax (XMLHTTP). ' +
                      'The browser you are using either does not support XMLHTTP ' +
                      'or it is turned off in the browser settings. ' +
                      'For help, please call support at 1-800-260-5887');
            }
        }
        
        if (typeof options.parameters == "object") {
            serializedParameters = ec.utility.serialize(options.parameters);
        } else {
            serializedParameters = options.parameters;
        }

        if ('POST' == ec._ajax.method) {
            ec._ajax.httpRequest.onreadystatechange = ec._ajax._onStatusChange;
            ec._ajax.httpRequest.open(ec._ajax.method, ec._ajax.url, true);
            ec._ajax.httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            ec._ajax.httpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            ec._ajax.httpRequest.setRequestHeader("Content-length", serializedParameters.length);
            ec._ajax.httpRequest.setRequestHeader("Connection", "close");
            ec._ajax.httpRequest.send(serializedParameters); 
        } else {
            ec._ajax.httpRequest.onreadystatechange = ec._ajax._onStatusChange;
            ec._ajax.httpRequest.open(ec._ajax.method, ec._ajax.url, true);
            ec._ajax.httpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
            if(ec.isIE()){
                ec._ajax.httpRequest.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
            }
            ec._ajax.httpRequest.send(null); 
        }
        // ajax busy working indicator
        var ajaxShowTimerFunct = function() {
            jQuery('#loaderDiv').show();
        };
        window.isAjaxActive = true;
        ajaxLoaderDiv = ec._dom.getAjaxLoaderDiv('loaderDiv', "Working...");
        if (window.isAjaxActive && !jQuery('#loaderDiv').is(":visible")) {
            window.ajaxLoaderTimerId = setTimeout(ajaxShowTimerFunct,100);
        }
        // GA tracking (note: it's not inside the on status change case 1, as it causes dupe GA tracking)
        _gaq.push(['_trackPageview', ec._ajax.url]);
    },
    _onStatusChange: function () {
        switch(ec._ajax.httpRequest.readyState) {
            case 1: // OPENED
            break;
            
            case 2: // HEADERS_RECEIVED
            break;
            
            case 3: // LOADING
                ec._ajax.onLoad();
            break;
            
            case 4: // DONE
                var ajaxHideTimerFunct = function() {
                    if (window.isAjaxActive == false && jQuery('#loaderDiv').is(':visible')) {
                        jQuery('#loaderDiv').hide();
                    }
                };
                window.isAjaxActive = false;
                clearTimeout(window.ajaxLoaderTimerId);
                setTimeout(ajaxHideTimerFunct,100);

                switch(ec._ajax.httpRequest.status) {
                    case 200:
                        if (ec._ajax.response == 'HTML') {
                            ec._ajax.jsonResponse = ec._ajax.httpRequest.responseText; 
                        } else {
                            ec._ajax.jsonResponse = eval("(" + ec._ajax.httpRequest.responseText + ")");
                        }
                        ec._ajax.onComplete();
                    break;
                }
            break;
        }
    }, 
    onLoad: function() {
        if (ec._ajax.options.onLoad) {
            if (typeof ec._ajax.options.onLoad == 'function') {
                ec._ajax.options.onLoad();
            }
        }
    },
    onComplete: function() {
        if (ec._ajax.options.onComplete) {
            if (typeof ec._ajax.options.onComplete == 'function') {
                ec._ajax.options.onComplete(ec._ajax.jsonResponse);
            }
        }
    }, 
    onError: function() {
        
    },
    _getBrowser: function() {
        if (!!(window.attachEvent && !window.opera)) {
            if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
                var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
                if (ieversion>=8) {
                    return "IE8";
                } else if (ieversion>=7) {
                    return "IE7";
                } else if (ieversion>=6) {
                    return "IE6";
                } else if (ieversion>=5) {
                    return "IE5";
                }
               }
        }
        if (!!window.opera) {
            return "Opera";
        }
        if (navigator.userAgent.indexOf('AppleWebKit/') > -1) {
            return "WebKit";
        }
        if (navigator.userAgent.indexOf('Gecko') > -1 && 
            navigator.userAgent.indexOf('KHTML') == -1) {
            return "Gecko";
        }
        if (!!navigator.userAgent.match(/Apple.*Mobile.*Safari/)) {
            return "MobileSafari";
        }
    }
}

var ajaxObject = _ajax;
ec._ajax = _ajax;

function $$get(url, div, callback) {
    if (typeof div == 'string') {
        div = $byId(div);
    }
    ec._ajax.getHtml(url, div, callback);
}

function $$post(url, div, callback, parameters) {
   if (typeof div == 'string') {
       div = $byId(div);
   }
   ec._ajax.setHtml(url, div, callback, parameters);
}


/**
 * @file _base/_dom.js
 */
var _dom = {
    id: '_dom',
    onLoad: function(div, message) {
        if (typeof div == 'string') {
            div = $byId(div);
        }

        div.innerHTML = "";
        var container = document.createElement('div');
        container.id = 'ec-dom-onload';
        var messageDiv = this.createAjaxLoaderMessage(message);
        var image = this.createAjaxLoaderImage();
        
        container.appendChild(image);
        container.appendChild(messageDiv);
        div.appendChild(container);
    },
    onReload: function(divId, message, left, top) {
        var element = $byId(divId);
        
        var messageDiv = this.createAjaxLoaderMessage(message);
        var image = this.createAjaxLoaderImage();
        image.style.backgroundColor = 'white';
        image.style.zIndex = '2000';
        image.style.cssFloat = '';
        image.style.width = '43px';

        messageDiv.style.zIndex = '2000';
        messageDiv.style.cssFloat = '';
        messageDiv.style.backgroundColor = 'white';
        messageDiv.style.clear = 'both';
        
        var placeholderElement = document.createElement('div');
        placeholderElement.style.width = '300px';
        placeholderElement.style.height = '200px';
        placeholderElement.style.left = left + 'px';
        placeholderElement.style.top = top + 'px';
        placeholderElement.style.position = 'absolute';
        placeholderElement.style.textAlign = 'center';
        placeholderElement.style.opacity = '0.8';
        placeholderElement.style.filter = "alpha(opacity=80)";
        
        placeholderElement.appendChild(image);
        placeholderElement.appendChild(messageDiv);
        element.appendChild(placeholderElement);
        
    },
    createAjaxLoaderImage: function(){
        var image = document.createElement('img');
        image.setAttribute('src', '/static/img/ajax-loader.gif');
        image.setAttribute('alt', 'loading...');
        image.setAttribute('border', '0');
        image.style.cssFloat = 'left';
        image.style.zIndex = '2000';
        image.style.position = 'relative';
        image.style.border = 'none';
        
        return image;
    },
    createAjaxLoaderMessage: function(message) {
        var messageDiv = document.createElement('div');
        messageDiv.innerHTML = message;
        messageDiv.style.cssFloat = 'left';
        messageDiv.style.position = 'relative';
        
        return messageDiv;
    },
    getAjaxLoaderDiv: function(divId, message) {
        ajaxLoaderDiv = jQuery('#'+divId).get(0);
        if (typeof ajaxLoaderDiv == "undefined") {
            // build when doesn't exist
            ajaxLoaderImg = this.createAjaxLoaderImage();
            ajaxLoaderDiv = this.createAjaxLoaderMessage(message);
            jQuery(ajaxLoaderDiv).attr('style', 'display: none;');
            jQuery(ajaxLoaderDiv).attr('id', divId);
            jQuery(ajaxLoaderDiv).append(ajaxLoaderImg);
            jQuery(document.body).append(ajaxLoaderDiv);
        }

        return ajaxLoaderDiv;
    }
}

ec._dom = _dom;
_dom = "";
/**
 * @file _base/_fx.js
 */
var dragObject = null;

var _fx = {
    mouse: {
        offset: null,
        onMove: function(event){
            event = event || window.event;
            var mousePosition = ec._fx.mouse.getCoordinates(event);
                
            if(dragObject){
                dragObject.style.position = 'absolute';
                dragObject.style.top = (mousePosition.y - ec._fx.mouse.offset.y) + "px";
                dragObject.style.left = (mousePosition.x - ec._fx.mouse.offset.x) + "px";
                return false;
            }    
        },
        onUp: function(event) {
            dragObject = null;
        },
        makeClickable: function(object){
            object.onmousedown = function(){
                dragObject = this;
            }
        },
        getCoordinates: function(event){
            if(event.pageX || event.pageY){
                return {x:event.pageX, y:event.pageY};
            }
            return { 
                x:event.clientX + document.body.scrollLeft - document.body.clientLeft, 
                y:event.clientY + document.body.scrollTop  - document.body.clientTop}; 
        },
        getOffset: function(target, event){
            event = event || window.event;

            var documentPosition = ec._fx.getPosition(target);
            var mousePosition  = ec._fx.mouse.getCoordinates(event);
            return {x:mousePosition.x - documentPosition.x, y:mousePosition.y - documentPosition.y};
        }
    },
    getPosition: function(element){
        var left = 0;
        var top  = 0;

        while (element.offsetParent){
            left += element.offsetLeft;
            top += element.offsetTop;
            element = element.offsetParent;
        }

        left += element.offsetLeft;
        top  += element.offsetTop;

        return {x:left, y:top};
    },
    makeDraggable: function(element){
        if(typeof element == 'string'){
            element = $byId(element);
        }
        if(!element) return;
        element.onmousedown = function(event){
            dragObject  = this;
            ec._fx.mouse.offset = ec._fx.mouse.getOffset(this, event);
            return false;
        }
    },
    unMakeDraggable: function(element){
        if(typeof element == 'string'){
            element = $byId(element);
        }
        if(!element) return;
        element.onmousedown = "";
    }
}

ec._fx = _fx;
_fx = "";

document.onmousemove = ec._fx.mouse.onMove; 
document.onmouseup = ec._fx.mouse.onUp;


/**
 * @file _base/_modal.js
 */
var _modal = {
    id: 'modalDiv',
    bodyDivId: 'bodyDiv',
    width: '400px',
    height: '400px',
    closeButton: 'enabled',
    dimmer: 'enabled',
    callback: null,
    forcePost: false,
    headerText: '',
    parameters: null,
    setDefaults: function(){
        ec._modal.width = '400px';
        ec._modal.height = '400px';
        ec._modal.closeButton = 'enabled';
        ec._modal.dimmer = 'enabled';
        ec._modal.forcePost = false;
        ec._modal.headerText = '';
        ec._modal.id = 'modalDiv';
        ec._modal.bodyDivId = 'bodyDiv';
        ec._modal.backgroundColor = '#FFFFFF';
        ec._modal.callback = null;
    },
    setHeaderText: function(value) {
        ec._modal.headerText = value;
    },
    setWidth: function(value) {
        ec._modal.width = value;
    },
    open: function(url) {
        //create the modal window div.
        var modalDiv = ec._modal.create();
        document.body.appendChild(modalDiv);
        adjustCenteredElement(modalDiv);
        ec._dom.onLoad('bodyDiv', 'Loading...');
        
        // trigger the onOpen event.
        ec._modal.onOpen();
        
        // open the dimmer.
        if(ec._modal.dimmer == 'enabled') {
            ec._dimmer.open();
            ec._modal.enableScrollEvent();
            ec._modal.enableResizeEvent();
        }
        // get content.
        if (ec._modal.forcePost){
            $$post(url, 'bodyDiv', ec._modal.callback, ec._modal.parameters);
        } else {
            $$get(url, 'bodyDiv', ec._modal.callback);
        }
    },
    close: function() { 
        ec._modal.disableScrollEvent();
        ec._modal.disableResizeEvent();
        ec._modal.onClose();

        // fix for IE browsers: background images causing to warn of https mixed content
        if (ec.utility.isIE()) {
            if (ec._modal.closeButton == 'enabled') {
                $byId('closeButton').style.backgroundImage = 'none';
            }
            if ($byId('modalSubmitButton')) {
                $byId('modalSubmitButton').style.backgroundImage = 'none';
            }
        }
        
        document.body.removeChild($byId(ec._modal.id));

        // close dimmer.
        ec._dimmer.close();
        
        // reset defaults
        ec._modal.setDefaults();
    },
    create: function() {
        var modalDiv = document.createElement('div');
        modalDiv.setAttribute('id', ec._modal.id);
        modalDiv.style.width = ec._modal.width;
        modalDiv.style.zIndex  = "2000";
        modalDiv.style.minHeight = ec._modal.height;
        modalDiv.style.position = "absolute";
        modalDiv.style.backgroundColor = "#f5f5f5";
        modalDiv.style.border = "2px solid #0066cc";
        
        var headerDiv = ec._modal.header.create();
        modalDiv.appendChild(headerDiv);
        
        var bodyDiv = ec._modal.body.create();
        modalDiv.appendChild(bodyDiv);
        
        return modalDiv;
    },
    header: {
        create: function() {
            var headerDiv = document.createElement('div');
            headerDiv.setAttribute('id', 'headerDiv');
            headerDiv.style.width = "100%";
            headerDiv.style.height = "20px";
            headerDiv.style.zIndex = "2001"; 
            headerDiv.style.position = "relative";
            headerDiv.style.backgroundColor = "#0066cc";
            headerDiv.style.cursor = "move";
            headerDiv.onclick = ec._modal.makeDraggable;
            headerDiv.onmouseover = ec._modal.makeDraggable;

            var headerTextDiv = document.createElement('div');
            headerTextDiv.innerHTML = ec._modal.headerText;
            headerTextDiv.style.color = "white";
            headerTextDiv.style.width = "300px";
            headerTextDiv.style.position = "relative";
            headerTextDiv.style.styleFloat = "left";
            headerTextDiv.style.cssFloat = "left";
            headerTextDiv.style.fontSize = "14px";
            headerTextDiv.style.fontWeight = "bold";
            headerTextDiv.style.marginLeft = "4px";
            headerDiv.appendChild(headerTextDiv);
            
            if (ec._modal.closeButton == 'enabled') {
                var closeButton = document.createElement('button');
                closeButton.setAttribute('id', 'closeButton');
                closeButton.onclick = ec._modal.close;
            
                headerDiv.appendChild(closeButton);
            }
            
            return headerDiv;
        }
    },
    body: {
        create: function() {
            var bodyDiv = document.createElement('div');
            bodyDiv.setAttribute('id', ec._modal.bodyDivId);
            bodyDiv.style.padding = "10px";
            bodyDiv.style.backgroundColor = ec._modal.backgroundColor;
            bodyDiv.onclick = ec._modal.unMakeDraggable;
            bodyDiv.onmouseover = ec._modal.unMakeDraggable;
            return bodyDiv;
        }
    },
    makeDraggable: function(){
        ec._fx.makeDraggable(ec._modal.id);
    },
    unMakeDraggable: function() {
        ec._fx.unMakeDraggable(ec._modal.id);
    },
    onOpen: function() {
        
    },
    onClose: function() {
        var dimmer = $byId('dimmer');
        if (dimmer) {
            document.body.removeChild(dimmer);
        }
        // Important: Delete any iframes here that will possibly require internal references to child elements.
        // This breaks in Firefox due to it not allowing a new iframe to take over in the DOM with the same name
        // unless the first is specifically deleted.
        if ('Gecko' == ec.getBrowser()) {
            if (window.uploadFormFrame) delete(window.uploadFormFrame);
        }
    },
    isDone: function() {
        if($byId('callback')) {
            eval($byId('callback').value);
        } 
        if($byId('isDone')) {
            if($byId('isDone').value) ec._modal.close();
        }
    },
    enableScrollEvent: function() {
        if (ec.utility.isIE()) {
            window.onscroll = function (e) {
                window.onscroll = ec._dimmer.update;
            }
            window.attachEvent("scroll", ec._dimmer.update);
        } else {
            window.addEventListener("scroll", ec._dimmer.update , false);
        }
    },
    enableResizeEvent: function() {
        if (ec.utility.isIE()) {
            window.onresize = function (e) {
                window.onresize = ec._dimmer.update;
            }
            window.attachEvent("resize", ec._dimmer.update);
        } else {
            window.addEventListener("resize", ec._dimmer.update , false);
        }
    },
    disableScrollEvent: function() {
        if (ec.utility.isIE()) {
            window.onscroll = function (e) {
                window.onscroll = "";
            }
            window.detachEvent("scroll", ec._dimmer.update);
        } else {
            window.removeEventListener("scroll", ec._dimmer.update , false);
        }
    },
    disableResizeEvent: function(){
        if (ec.utility.isIE()) {
            window.onresize = function (e) {
                window.onresize = "";
            }
            window.detachEvent("resize", ec._dimmer.update);
        } else {
            window.removeEventListener("resize", ec._dimmer.update , false);
        }
    }
}

var _dimmer = {
    open: function() {
        ec._dimmer.create();
        ec._dimmer.update();
    },
    close: function() {
        if ($byId('dimmer')) document.body.removeChild($byId('dimmer'));
    },
    create: function() {
        var winDims = {
            width: document.documentElement.clientWidth,
            height: document.documentElement.clientHeight
        };
    
        var browser = ec.utility.getBrowser();
        if (ec.utility.isIE() && winDims.width == '0') {
            winDims.width = document.body.clientWidth;
        }
        
        var dimmer = document.createElement('div');
        dimmer.setAttribute('id', 'dimmer');
        dimmer.style.display = "block";
        dimmer.style.zIndex = '1000';
        dimmer.style.width = winDims.width + 'px';
        dimmer.style.height = winDims.height + 'px';
        dimmer.style.position = 'absolute';
        dimmer.style.top = '0';
        dimmer.style.opacity = '0.7';
        dimmer.style.filter = "alpha(opacity=70)";
        dimmer.style.backgroundColor = 'black';
        document.body.appendChild(dimmer);
    },
    update: function() {
        var dimmer = $byId('dimmer');
        var top = cumulativeScrollOffset(document.body).top;
        dimmer.style.height = document.documentElement.clientHeight + top + 'px';
        dimmer.style.width = document.documentElement.clientWidth + 'px';
    }
}

ec._modal = _modal;
_modal = "";

ec._dimmer = _dimmer;
_dimmer = "";

/**
 * @file _base/_utility.js
 */
var _utility = {
    /**
     * form 
     * 
     * Utility functions for forms.
     * 
     * @member  utility
     * @public
     */    
    form: {
        /**
         * serialize
         * 
         * Serializes the values of a form.
         * 
         * @member  form
         * @public
         * @param {Element}  form               The form that is to be serialized. 
         * @return {String}  parameterString    Serialized values from form.  
         */
        serialize: function(form) {
            var parameterString = '';
            var debugMs = '';
            for (key in form) {            
                if (form[key]) {
                    // This gets the key / value pair for radio inputs.
                    if (typeof form[key] == 'object'){
                        if (form[key].length > 1 && typeof form[key] !== 'undefined') {
                            for (index in form[key]){
                                    if (ec.isIE() && typeof form[key][index] !== 'undefined') {
                                    
                                    } else {
                                        if (form[key][index] && (form[key][index].type == 'radio' || form[key][index].type == 'checkbox')) {
                                            if (form[key][index].checked){
                                                parameterString += '&' + form[key][index].name + '=' + encodeURIComponent(form[key][index].value);
                                            }
                                        }
                                    }
                            }
                        } 
                    }
                    if (form[key].type == 'text' || 
                        form[key].type == 'select-one' ||
                        form[key].type == 'hidden' || 
                        form[key].type == 'textarea' ||
                        form[key].type == 'password') {
                            var keyValue = form[key].name;
                            var value = form[key].value;
                            parameterString += '&' + keyValue + '=' + encodeURIComponent(value);
                    }
                    if (form[key].type == 'radio' && 'WebKit' == ec.utility.getBrowser()) {
                        if (form[key].checked) {
                            parameterString += '&' + form[key].name + '=' + encodeURIComponent(form[key].value);
                        }
                    }
                    if (form[key].type == 'select-multiple') {
                        
                        if (ec.isIE() || 'WebKit' == ec.getBrowser()) {
                            for (i=0;i<form[key].options.length;i++) {
                                if (form[key].options[i].selected == true){
                                    var keyValue = form[key].name;
                                    var value = form[key].options[i].value;
                                    parameterString += '&' + keyValue + '=' + encodeURIComponent(value);
                                }
                            }  
                        } else {
                            for (multiIndex in form[key].options) {
                                
                                if (form[key].options[multiIndex].selected == true){
                                    var keyValue = form[key].name;
                                    var value = form[key].options[multiIndex].value;
                                    parameterString += '&' + keyValue + '=' + encodeURIComponent(value);
                                }    
                            }
                        }
                    }
                }
            }
            
            if (ec.isIE() && (form !== null)){
                for (i=0;i<form.length;i++) {
                    if (form[i].type == 'radio'){
                        if (form[i].checked) {
                            parameterString += '&' + form[i].name + '=' + encodeURIComponent(form[i].value);
                        }
                    }
                }  
            }

            return parameterString;
        },
        submit: function(form, action, div, callback){
            if (typeof form == 'string') {
                form = $byId(form);
            }
            if (typeof div == 'string') {
                div = $byId(div);
            }
            
            var parameters = ec._utility.form.serialize(form);
            ec._ajax.setHtml(action, div, function(){if(typeof callback == 'function') callback();}, parameters);
        }
    },
    tab: {
        select: function(tabId, tabClass){
            var tabs;
            if (typeof tabClass == "object") {
                tabs = tabClass;
                tabClass = tabs[0].className.replace("selected", "");
            } else {
                tabs = document.getElementsByClassName(tabClass);
            }
            for(var index in tabs){
                tabs[index].className = tabClass;
            }
            if (typeof tabId == "string") {
                tabId = $byId(tabId); 
            }
            tabId.className = tabClass + ' selected';
        }
    },
    /**
     * search
     * 
     * Searches an array for a specified string in a specified key.
     *  
     * @member  utility
     * @public
     * @param {Array}   array          Array to be searched.
     * @param {String}  searchKey      Key to search for value in.
     * @param {String}  searchString   String to find in array.
     */
    search: function( array, searchKey, searchString ) {
        if ( array instanceof Array) {
            for (var i=0; i < array.length; i++) {
                if (typeof array[i][searchKey] == 'string') {
                    if (array[i][searchKey] == searchString) {
                        return array[i];
                    } 
                }
            }
        } else {
            if (typeof array[searchKey] == 'string') {
                if (array[searchKey] == searchString) {
                    return array;
                }
            }
        }
        return false;
    },
    /**
     * setInputValue 
     * 
     * Sets the value on an element.
     * 
     * @member  utility
     * @public
     * @param {String}  id      Id of the element you want to set the value on.  
     * @param {String}  vaule   Value to set on the element.
     */
    setInputValue: function (id, value) {
        var element = document.getElementById(id);
        element.value = value;
    },
    /**
     * serialize
     * 
     * Serializes the values of an object
     * 
     * @member  utility
     * @public
     * @param {Element}  object               The object that is to be serialized. 
     * @return {String}  parameterString    Serialized values from form.  
     */
    serialize: function(object) {
        var parameterString = '';
        
        for (key in object) {
            if (object[key]) {
                var keyValue = key;
                var value = object[key];
                parameterString += '&' + keyValue + '=' + value; 
            }
        }
        return parameterString;
    },
    /**
     * getBrowser
     * 
     * Returns the name of the browser being used.
     * 
     * @member  utility
     * @public
     * @return {String} Name of browser.
     */
    getBrowser: function() {
        if (!!(window.attachEvent && !window.opera)) {
            if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) { //test for MSIE x.x;
                var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
                if (ieversion>=8) {
                    return "IE8";
                } else if (ieversion>=7) {
                    return "IE7";
                } else if (ieversion>=6) {
                    return "IE6";
                } else if (ieversion>=5) {
                    return "IE5";
                }
            }
        }
        if (!!window.opera) {
            return "Opera";
        }
        if (navigator.userAgent.indexOf('AppleWebKit/') > -1) {
            return "WebKit";
        }
        if (navigator.userAgent.indexOf('Gecko') > -1 && 
            navigator.userAgent.indexOf('KHTML') == -1) {
            return "Gecko";
        }
        if (!!navigator.userAgent.match(/Apple.*Mobile.*Safari/)) {
            return "MobileSafari";
        }
    },
    /**
     * isIE
     * 
     * Checks if browser is IE 
     *  
     * @member  utility
     * @public
     * @return {Boolean}    Returns true if browser is IE.
     */
    isIE: function() {
        var browser = this.getBrowser();
        if (browser.match('IE')) {
            return true;
        } else {
            return false;
        }
    },
    isElement: function(elementId){
        var element = document.getElementById(elementId);
        if (element == null){
            return false;
        } else {
            return true;
        }
    },
    element: {
        show: function (id) {
            if (typeof id == 'string') {
                element = $byId(id);
            } else {
                element = id;
            }
            element.style.display = 'block';
        },
        hide: function (id) {
            if (typeof id == 'string') {
                element = $byId(id);
            } else {
                element = id;
            }
            element.style.display = 'none';
        },
        toggleShow: function(elementId, callingElement, toggleText) {
            if (null == toggleText) {
                var toggleText = 'hide';
            }
            ec.utility.element.show(elementId);
            if (typeof callingElement == 'string') {
                callingElement = $byId(callingElement);
            }
            var nextToggleText = callingElement.innerHTML;
            callingElement.innerHTML = toggleText;
            callingElement.onclick = function(){
                ec.utility.element.toggleHide(elementId, callingElement, nextToggleText);
            };
        },
        toggleHide: function(elementId, callingElement, toggleText) {
            if (null == toggleText) {
                var toggleText = 'change';
            }
            var nextToggleText = callingElement.innerHTML;
            ec.utility.element.hide(elementId);
            if (typeof callingElement == 'string') {
                callingElement = $byId(callingElement);
            }
            var nextToggleText = callingElement.innerHTML;
            callingElement.innerHTML = toggleText;
            callingElement.onclick = function(){
                ec.utility.element.toggleShow(elementId, callingElement, nextToggleText);
            };
        }
    },
    _expandDiv: function( divId, element ) {
        document.getElementById( divId ).style.display = 'block';
        element.innerHTML = '-';
        element.onclick = function() { ec.utility._collapseDiv( divId, element ); };
    },
    _collapseDiv: function( divId, element ) {
        document.getElementById( divId ).style.display = 'none';
        element.innerHTML = '+';
        element.onclick = function() { ec.utility._expandDiv( divId, element ); };
    },
    _getCookie: function( name ){
        var cookieName = encodeURIComponent( name ) + "=",
        cookieStart = document.cookie.indexOf( cookieName ),
        cookieValue = null;

        if ( cookieStart > -1 ) {
            var cookieEnd = document.cookie.indexOf( ";", cookieStart );
            if ( cookieEnd == -1) {
                cookieEnd = document.cookie.length;
            }
            cookieValue = decodeURIComponent( document.cookie.substring( cookieStart + cookieName.length, cookieEnd) );
        }

        return cookieValue;
    },
    _setCookie: function( name, value, expires, path, domain, secure){
        var cookieText = encodeURIComponent( name ) + "=" +
                         encodeURIComponent( value );
        if (expires instanceof Date) {
            cookieText += "; expires=" + expires.toGMTString();
        }
        if (path) {
            cookieText += "; path=" + path;
        }
        if (domain) {
            cookieText += "; domain=" + domain;
        }
        if (secure) {
            cookieText += "; secure";
        }

        document.cookie = cookieText;
    },
    _deleteCookie: function( name, path, domain, secure) {
        this.set(name, "", new Date(0), path, domain, secure);
    },
    getTestimonial: function() {
        var testimonial;
        var numberOfTestimonials;
        var randomNumber;
        var divId;
        var currentDiv; 

        numberOfTestimonials = document.getElementsByClassName('testimonials').length;
        randomNumber = Math.floor(Math.random()*numberOfTestimonials)+1;
        divId = 'testimonial' + randomNumber;
        testimonial = $byId(divId).innerHTML;
        $byId('show2').innerHTML = testimonial;
    }, 
    validate: function(callback) {
        var elements = document.getElementsByClassName('required');
        var errorMessage = "";
        for (var i in elements) {
            if (elements[i].value == "" && elements[i].value !== "undefined") {
                errorMessage += elements[i].title + " is required \n";
            }
        }
        var elements = document.getElementsByClassName('email');
        for (var i in elements) {
            var email = elements[i];
            if (!email.value || email.value == "" || 'object' != typeof email) {
                continue;
            }
            if (!ec.utility.validateEmailAddress(email.value)) {
                errorMessage += "Email address is invalid. \n";
            }
        }
        if (errorMessage) {
            alert(errorMessage);
        } else {
            if(typeof callback == 'function'){
                callback();
            }
        }
    },
    validateEmailAddress: function(email) {
        var validEmail = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/;
        return validEmail.test(email);
    }
}

var modalWindow = {
    div: '',
    keepCentered: true,
    show:  function(div, options){
        if (typeof div == 'object') {
            element = div;
        } else {
            element = document.getElementById(div);
        }
               
        modalWindow.div = element;
        
        if (typeof options !== 'object') {
            options = {};
        }

        element.style.display = 'block';
        if (modalWindow.keepCentered){
            
            adjustCenteredElement(element);
            
            if (ec.utility.isIE()) {
                window.onscroll = function (e) {
                    //adjustCenteredElement(element);
                    //modalWindow.disableScroll;
                    modalWindow.updateDimmer();
                }
                //window.attachEvent("scroll", modalWindow.centerElement);
                window.attachEvent("scroll", modalWindow.updateDimmer);
                //window.attachEvent("scroll", modalWindow.disableScroll);
            } else {
                //window.addEventListener("scroll", modalWindow.centerElement , false);
                //window.addEventListener("resize", modalWindow.centerElement, false);
                window.addEventListener("scroll", modalWindow.updateDimmer , false);
                //window.addEventListener("scroll", modalWindow.disableScroll, false);
            }
        }
        modalWindow.createDimmer();
        modalWindow.updateDimmer();
        if (options.callback) {
            if (typeof options.callback == 'function') {
                if (options.parameter){
                    options.callback(options.parameter);
                } else {
                    options.callback();
                }
            }
        }
    },
    hide: function(divId){
   
        utility.element.hide( divId );
        
        var dimmer = document.getElementById('dimmer');
        if (dimmer) {
            dimmer.style.display = 'none';
        }  
    },
    close: function(divId){
        var div = this.div;
        document.body.removeChild(div);
        var dimmer = document.getElementById('dimmer');
        if (dimmer) {
            document.body.removeChild(dimmer);
        }
        
        if (ec.utility.isIE()) {
            window.onscroll = "";
            window.detachEvent("scroll", modalWindow.centerElement);
            window.detachEvent("scroll", modalWindow.updateDimmer);
            window.detachEvent("scroll", modalWindow.disableScroll);
        } else {
            window.removeEventListener("scroll", modalWindow.centerElement, false);
            window.removeEventListener("scroll", modalWindow.updateDimmer, false);
            window.removeEventListener("scroll", modalWindow.disableScroll, false);
        }
    },
    open: function(options) {
        var width = options.width;
        var url = options.url;
        var height = options.height || 'auto';
        var modalDiv = modalWindow.createModal(width, height);
        document.body.appendChild(modalDiv);

        $$get(url, modalDiv, null);

        var modalOptions = {};
        modalWindow.show(modalDiv, modalOptions);
    },
    centerElement: function(){
        adjustCenteredElement(modalWindow.div);
    },
    createModal: function(width, height) {
        var modalDiv = document.createElement('div');
        modalDiv.setAttribute('id', 'modalDiv');
        modalDiv.style.width = width;
        modalDiv.style.zIndex  = "2000";
        modalDiv.style.minHeight = height;
        modalDiv.style.position = "absolute";
        modalDiv.style.backgroundColor = "white";
        modalDiv.style.padding = "10px";
        modalDiv.style.border = "4px solid #444444";

        return modalDiv;
    },
    disableScroll: function() {
        scroll(0,0);
    },
    createDimmer: function() {
        
        var winDims = {
            width: document.documentElement.clientWidth,
            height: document.documentElement.clientHeight
        };
    
        var browser = ec.utility.getBrowser();
        if (ec.utility.isIE() && winDims.width == '0') {
            winDims.width = document.body.clientWidth;
        }
        
        var dimmer = document.createElement('div');
        dimmer.setAttribute('id', 'dimmer');
        dimmer.style.display = "block";
        dimmer.style.zIndex = '1000';
        dimmer.style.width = winDims.width + 'px';
        dimmer.style.height = winDims.height + 'px';
        dimmer.style.position = 'absolute';
        dimmer.style.top = '0';
        dimmer.style.opacity = '0.5';
        dimmer.style.filter = "alpha(opacity=50)";
        dimmer.style.backgroundColor = 'black';
        document.body.appendChild(dimmer);
    },
    updateDimmer: function() {
        var dimmer = document.getElementById('dimmer');
        var top = cumulativeScrollOffset(document.body).top;
        dimmer.style.height = document.documentElement.clientHeight + top + 'px';
    }
}


function adjustCenteredElement(element)
{
    var dims = {
        width: element.clientWidth, 
        height: element.clientHeight
    };

    var winDims = {
        width: document.documentElement.clientWidth,
        height: document.documentElement.clientHeight
    };
    
    var browser = ec.utility.getBrowser();
    if (ec.utility.isIE() && winDims.width == '0') {
        winDims.width = document.body.clientWidth;
    }

    if (dims.height < winDims.height) {
        element.style.left = (winDims.width - dims.width) / 2 + 'px';
    }

    element.style.top = cumulativeScrollOffset(document.body).top + 80 + 'px';
}

function cumulativeScrollOffset( element ) {
    var valueT = 0, valueL = 0;
    do {
        valueT += element.scrollTop || 0;
        valueL += element.scrollLeft || 0;
        element = element.parentNode;
    } while (element);
    
    var result = [valueL, valueT];
    result.left = valueL;
    result.top = valueT;
    
    return result;
}



var crosstalk = function() {

    this.init = function() {

    };

    this.appendScript = function(url, id) {
        var script = document.createElement('script');
        var head = document.getElementsByTagName('head')[0];

        script.type = 'text/javascript';
        script.id = id;
        script.src = url; // + '&cleanup=' + script.id;

        head.appendChild(script);

        var t = setTimeout("ECcleanup('" + script.id + "')", 15000);
    };

    this.init();
}

function ECcleanup(id) {
    var script = document.getElementById(id);
    var head = document.getElementsByTagName('head')[0];
    head.removeChild(script);
}

function $byId(elementId) {
    var element = document.getElementById(elementId);

    if(ec.isIE() && element == null) {
        //return false;
    }
    
    return element;
}

function $byClassName(className, element) {
    if (typeof(element) != 'object') {
        var element = $byId(element);
    }
    if (ec.getBrowser() == 'IE6' || ec.getBrowser() == 'IE7') {
        var elements = getElementsByClassNameForIE(className, element);
    } else {
        var elements = element.getElementsByClassName(className);
    }
    return elements;
}

function $$login(uri) {
    if (uri) {
      form_uri = $byId('uri');
      form_uri.value = uri;
    }
    ec._modal.parameters = ec.utility.form.serialize($byId('loginLinkForm'));
    ec._modal.forcePost = 'true';
    ec._modal.height = '170px';
    if (!uri) {
        ec._modal.headerText = "Sign In To Your Account";
    } else {
        ec._modal.headerText = "Sign In";
    }
    ec._modal.callback = function(){$byId('username').focus();};
    $$modal('/ec/user/login/modal/true');
}

function $submit(form, action, div, callback) {
    if (typeof form == 'string') {
        form = $byId(form);
    }
    if (typeof div == 'string') {
        div = $byId(div);
    }
    ec._utility.form.submit(form, action, div, callback);
}

$$submit = $submit;

ec.utility = _utility;
ec._utility = _utility;
_utility = "";
/**
 * @file components/design.js
 */
var _design =
{
    current:
    {
        frontId: '',
        frontType: '',
        frontIntention: 'select',
        frontProductId: '',
        backId: '',
        backType: '',
        backIntention: 'select',
        backProductId: '',
        size: '',
        displaySide: 'front',
        libraryType: 'customizable',
        userId: '',
        numberToDisplay: '24',
        pageNumber: '1',
        productFilter: '',
        defaultCategory: 831,
        finished: false,
        eztId: '',
        bootData: []
    },

    // setter functions -- these exist due to undesirable behavior when directly referencing the object properties
    setCurrentPageNumber: function(pageNumber) {
        ec.design.current.pageNumber = pageNumber;
    },
    setCurrentLibraryType: function(libraryType) {
        ec.design.current.libraryType = libraryType;
    },
    setCurrentFinished: function(finished) {
        ec.design.current.finished = finished;
    },
    setCurrentFrontId: function(frontId) {
        ec.design.current.frontId = frontId;
    },
    setCurrentFrontType: function(frontType) {
        ec.design.current.frontType = frontType;
    },
    setCurrentBackId: function(backId){
        ec.design.current.backId = backId;
    },
    setCurrentBackType: function(backType) {
        ec.design.current.backType = backType;
    },
    setCurrentNumberToDisplay: function(numberToDisplay) {
        ec.design.current.numberToDisplay = numberToDisplay;
    },
    setCurrentUserId: function(userId) {
        ec.design.current.userId = userId;
    },
    setCurrentEztId: function(eztId) {
        ec.design.current.eztId = eztId;
    },
    setCurrentDisplaySide: function(displaySide) {
        ec.design.current.displaySide = displaySide;
        var sideToggle = document.getElementsByName('displaySide');
        if (sideToggle[0] && sideToggle[1]) {
            if (displaySide == 'front') {
                sideToggle[0].checked = true;
            } else {
                sideToggle[1].checked = true;
            }
        }
        var sideSelect = document.getElementById('sideSelect');
        if (displaySide == 'front') {
            sideSelect.selectedIndex = 0;
        } else {
            sideSelect.selectedIndex = 1;
        }
        
    },
    setCurrentFrontIntention: function(intention) {
        ec.design.current.frontIntention = intention;
    },
    setCurrentBackIntention: function(intention) {
        ec.design.current.backIntention = intention;
    },
    setCurrentBackRequired: function(backRequired) {
        ec.design.current.backRequired = backRequired;
    },
    setCurrentDefaultCategory: function(defaultCategory) {
        ec.design.current.defaultCategory = defaultCategory;
    },
    setProductFilter: function(productFilter) {
        ec.design.current.productFilter = productFilter;
    },
    setCurrentBackProductId: function(productId) {
        ec.design.current.backProductId = productId;
    },
    setCurrentFrontProductId: function(productId) {
        ec.design.current.frontProductId = productId;
    },
    setCurrentSideSelected: function(side) {
        ec.design.current.sideSelected = side;
    },

    /**
     * getBreadcrumbNavigation
     * 
     * @member _design
     * @public
     */
    getBreadcrumbNavigation: function(totalFound)
    {
        // Breadcrumb navigation builder.
        try {
            var breadcrumbNav = document.getElementById('ec-design-breadcrumbNav');
            if (!breadcrumbNav) {
                var breadcrumbNav = document.createElement('div');
            }
            breadcrumbNav.id = 'ec-design-breadcrumbNav';
            var topLevel = 'designTemplates';
            if (ec.design.current.libraryType == 'my' || ec.design.current.libraryType == 'saved' || ec.design.current.libraryType == 'unfinished') {
                topLevel = 'myDesigns';
            }
            var crumbs = [['#', 'myDesigns' == topLevel ? 'My Designs' : 'Design Templates', 'ec-design-breadcrumb-topLevel']];
            var product = jQuery('#productSelect option:selected');
            if (product.val()) {
                var productHref = '#' + product.val();
                var productText = product.text();
            } else {
                var productHref = '#';
                var productText = 'All Products';
            }
            crumbs.push([productHref, productText, 'ec-design-breadcrumb-product']);
            var category = jQuery('#categorySelect option:selected');
            if ('' != category.val()) {
                var categoryHref = '#';
                var categoryText = category.text();
                if ('designTemplates' == topLevel) {
                    crumbs.push([categoryHref, categoryText, 'ec-design-breadcrumb-category']);
                }
                var subCategory = jQuery('#subCategorySelect option:selected');
                if ('' != subCategory.val()) {
                    var subCategoryHref = '#';
                    var subCategoryText = subCategory.text();
                    crumbs.push([subCategoryHref, subCategoryText, 'ec-design-breadcrumb-subcategory']);
                }
            }
            var side = jQuery('#sideSelect option:selected');
            crumbs.push(['#', side.text(), 'ec-design-breadcrumb-side']);
            breadcrumbNav.innerHTML = 'You are viewing: ';
            for (x in crumbs) {
                if (crumbs[x][0]) {
                    breadcrumbNav.innerHTML += '<a id="' + crumbs[x][2] + '" href="' + crumbs[x][0] + '">' + crumbs[x][1] + '</a> > ';
                }
            }
            breadcrumbNav.innerHTML += ' Found ' + totalFound + ' matching';
            return breadcrumbNav;
        } catch (e) {}
    },

    /**
     * getCategories
     *
     * Returns all categories.
     *
     * @member  _design
     * @public
     *
     */
    getCategories: function()
    {
        var parameters = {};
        if (ec.design.current.bootData.siteId > 0) {
            parameters.siteId = ec.design.current.bootData.siteId;
        }
        var callback = "ec.design._addCategories";

        var id = 'categoryApiScript';

        ec._callApi('design/categories', parameters, callback);
    },
    
    reflectSelectedCategory: function(id)
    {
        jQuery('#categorySelect').val(id);
    },
    
    reflectSelectedProduct: function(id)
    {
        jQuery('#productSelect').val(id);
        ec.design.current.productFilter = id;
    },
    
    /**
     * _addCategories
     *
     * Callback function that stores json to the ec.jsonDataStore array.
     *
     * @member  _design
     * @private
     *
     * @param {Object} json  json to store in the json data store.
     */
    _addCategories: function(json)
    {
        ec.jsonDataStore['categoryMenu'] = json;

        if (ec.config.format == 'html') {
            ec.design._formatCategories(json);
            ec.design.reflectSelectedCategory(ec.__designSelector.category.parentCategoryId);
        }
    },

    /**
     *_formatCategories
     *
     * Formats the json data into HTML.
     *
     * @member  _design
     * @param {Object} json  json to format.
     * @public
     */
    _formatCategories: function( json )
    {
        ec.design.categoryMap = {};
        if (ec.design.current.bootData['hideDesignCategories']) {
            return false;
        }
        var categoryPlaceHolder = document.getElementById(ec.config.design.categoryDiv);

        var menu = document.createElement('div');
        menu.setAttribute('id', 'ec-category-menu');

        categoryPlaceHolder.appendChild(menu);

        var menuHeader = document.createElement('div');

        menuHeader.className = 'header';

        menu.appendChild(menuHeader);

        var menuHeaderText = document.createElement('div');
        menuHeaderText.className =  'text';
        menuHeaderText.innerHTML = 'Design Categories';

        menuHeader.appendChild(menuHeaderText);

        var menuBody = document.createElement('div');
        menuBody.className = 'body';

        menu.appendChild(menuBody);

        // Tack on shortcut links, my designs, etc.
        var categoryItem = document.createElement('div');
        categoryItem.className = 'ec-category-menuItem';
        menuBody.appendChild(categoryItem);

        for (var index in json.response.category) {
            var categoryItem = document.createElement('div');
            categoryItem.className = 'ec-category-menuItem';
            if (typeof json.response.category[index] == 'object') {
                if (json.response.category[index].children) {
                    var divToShow = "subCat_" + index;
                    var expandDiv = document.createElement('div');
                    expandDiv.className = 'ec-design-expand';

                    categoryItem.appendChild(expandDiv);

                    var expandInnerDiv = document.createElement('div');
                    expandInnerDiv.className = 'ec-design-expandInner';

                    expandDiv.appendChild(expandInnerDiv);

                    var expandLink = document.createElement('a');
                    expandLink.divToShow = divToShow;
                    expandLink.onclick = ec.design._handleCategoryExpand;

                    expandLink.innerHTML = '+';

                    expandInnerDiv.appendChild(expandLink);
                    var parentCategoryId = json.response.category[index].id;
                    var categoryItemLink = document.createElement('a');
                    categoryItemLink.setAttribute('id',json.response.category[index].id);
                    categoryItemLink.categoryId = json.response.category[index].id;
                    
                    categoryItemLink.parentCategoryId = json.response.category[index].id;
                    categoryItemLink.categoryName = json.response.category[index].name;
                    categoryItemLink.onclick = ec.design._handleCategoryClick;

                    categoryItemLink.className = 'ec-design-categoryLink';

                    categoryItemLink.innerHTML = json.response.category[index].name;

                    categoryItem.appendChild(categoryItemLink);
                    
                    // populate top level category drop-down
                    var categorySelect = document.getElementById('categorySelect');
                    var categoryOption = document.createElement('option');
                    try {
                        categorySelect.add(categoryOption,null); // standards compliant
                    } catch(ex) {
                        categorySelect.add(categoryOption); // IE only
                    }
                    categoryOption.value = json.response.category[index].id;
                    categoryOption.innerHTML = json.response.category[index].name;
                } else {
                    // populate top level category hierarchy
                    var spacerDiv = document.createElement('div');
                    spacerDiv.className = 'ec-design-spacer';
                    spacerDiv.innerHTML = " &nbsp ";

                    categoryItem.appendChild(spacerDiv);

                    var categoryItemLink = document.createElement('a');
                    categoryItemLink.setAttribute('id',json.response.category[index].id);
                    categoryItemLink.categoryId = json.response.category[index].id;
                    categoryItemLink.categoryName = json.response.category[index].name;
                    categoryItemLink.parentCategoryId = json.response.category[index].id;
                    categoryItemLink.onclick = ec.design._handleCategoryClick;
                    categoryItemLink.innerHTML = json.response.category[index].name;
                    
                    categoryItem.appendChild(categoryItemLink);
                    
                    // populate top level category drop-down
                    var categorySelect = document.getElementById('categorySelect');
                    var categoryOption = document.createElement('option');
                    try {
                        categorySelect.add(categoryOption,null); // standards compliant
                    } catch(ex) {
                        categorySelect.add(categoryOption); // IE only
                    }
                    categoryOption.value = json.response.category[index].id;
                    categoryOption.innerHTML = json.response.category[index].name;
                }
            }

            menuBody.appendChild(categoryItem);

            if (json.response.category[index].children) {
                var categorySubItems = document.createElement('div');
                categorySubItems.setAttribute('id', 'subCat_' + index);
                categorySubItems.style.display = 'none';

                if (typeof json.response.category[index].children.category.name == 'string') {
                    json.response.category[index].children.category[0] = [];
                    json.response.category[index].children.category[0] = json.response.category[index].children.category;
                }
                for ( var subIndex in json.response.category[index].children.category) {

                    var categorySubItem = document.createElement('div');
                    categorySubItem.className = 'ec-category-menuItemChild';

                    if (typeof json.response.category[index].children.category[subIndex] == 'object') {
                        var childCategoryId = json.response.category[index].children.category[subIndex].id;
                        ec.design.categoryMap[childCategoryId] = parentCategoryId;
                        if (json.response.category[index].children.category[subIndex].children) {
                            var categorySubItemLink = document.createElement('a');
                            categorySubItemLink.className =  'ec-design-categoryLink';
                            categorySubItemLink.setAttribute('id',json.response.category[index].id);
                            categorySubItemLink.categoryId = json.response.category[index].children.category[subIndex].id;
                            categorySubItemLink.categoryName = json.response.category[index].name;
                            categorySubItemLink.parentCategoryId = json.response.category[index].id;
                            categorySubItemLink.onclick = ec.design._handleCategoryClick;
                            categorySubItemLink.innerHTML = json.response.category[index].children.category[subIndex].name;
                            categorySubItem.appendChild(categorySubItemLink);
                            categorySubItems.appendChild(categorySubItem);
                            var categorySubSubItems = document.createElement('div');
                            categorySubSubItems.setAttribute('id', 'subSubCat_' + subIndex);
                            categorySubSubItems.style.display = 'none';
                            var divToShow = "subSubCat_" + subIndex;
                            var expandDiv = document.createElement('div');
                            expandDiv.className = 'ec-design-expand';

                            categorySubItem.appendChild(expandDiv);

                            var expandInnerDiv = document.createElement('div');
                            expandInnerDiv.className = 'ec-design-expandInner';

                            expandDiv.appendChild(expandInnerDiv);

                            var expandLink = document.createElement('a');
                            expandLink.divToShow = divToShow;
                            expandLink.onclick = ec.design._handleCategoryExpand;

                            expandLink.innerHTML = '+';

                            expandInnerDiv.appendChild(expandLink);

                            for (var subSubIndex in json.response.category[index].children.category[subIndex].children.category) {
                                if (typeof json.response.category[index].children.category[subIndex].children.category[subSubIndex] == 'object') {
                                    var grandChildCategoryId = json.response.category[index].children.category[subIndex].children.category[subSubIndex].id;
                                    ec.design.categoryMap[grandChildCategoryId] = parentCategoryId;
                                    var categorySubSubItem = document.createElement('div');
                                    categorySubSubItem.innerHTML = ' -';
                                    categorySubSubItem.className = 'ec-category-menuItemChild';
                                    var categorySubSubItemLink = document.createElement('a');
                                    categorySubSubItemLink.className =  'ec-design-categoryLink';
                                    categorySubSubItemLink.setAttribute('id',json.response.category[index].children.category[subIndex].id);
                                    categorySubSubItemLink.categoryId = json.response.category[index].children.category[subIndex].children.category[subSubIndex].id;
                                    categorySubSubItemLink.categoryName = json.response.category[index].children.category[subIndex].name;
                                    categorySubSubItemLink.parentCategoryId = json.response.category[index].children.category[subIndex].children.category[subSubIndex].id;
                                    categorySubSubItemLink.onclick = ec.design._handleCategoryClick;
                                    categorySubSubItemLink.innerHTML = json.response.category[index].children.category[subIndex].children.category[subSubIndex].name;
                                    categorySubSubItem.appendChild(categorySubSubItemLink);
                                    categorySubSubItems.appendChild(categorySubSubItem);
                                }
                            }
                            categorySubItem.appendChild(categorySubSubItems);
                        } else {
                                categorySubItem.innerHTML = "  -";
                                var categorySubItemLink = document.createElement('a');
                                categorySubItemLink.className =  'ec-design-categoryLink';
                                categorySubItemLink.setAttribute('id',json.response.category[index].id);
                                categorySubItemLink.categoryId = json.response.category[index].children.category[subIndex].id ;
                                categorySubItemLink.categoryName = json.response.category[index].name;
                                categorySubItemLink.parentCategoryId = json.response.category[index].id;
                                categorySubItemLink.onclick = ec.design._handleCategoryClick;
                                categorySubItemLink.innerHTML = json.response.category[index].children.category[subIndex].name;
                                categorySubItem.appendChild(categorySubItemLink);
                                categorySubItems.appendChild(categorySubItem);

                        }

                    }

                }
                categoryItem.appendChild(categorySubItems);
            }
        }
    },

    getProductsForUserDesigns: function()
    {
        if (!ec.design.current.userId) {
            return false;
        }

        var parameters = {};
        parameters.userId = ec.design.current.userId;
        parameters.libraryType = ec.design.current.libraryType;
        parameters.page = ec.design.current.displaySide;
        var callback = "ec.design._addProductsForUserDesigns";
        ec._callApi('design/productsForUserDesigns', parameters, callback);
    },

    _addProductsForUserDesigns: function( json )
    {
         if (ec.config.format == 'html') {
            ec.design._formatProductsForUserDesigns(json);
        }
    },

    _formatProductsForUserDesigns: function( json )
    {
        if (json.response.product) {
            var productSelect = document.getElementById('productSelect');
            var i;
            for (i = productSelect.options.length-1; i>=0; i--) {
                productSelect.remove(i);
            }
            var allProduct = document.createElement('option');
            try {
                productSelect.add(allProduct,null); // standards compliant
            } catch (ex) {
                productSelect.add(allProduct); // IE only
            }
            allProduct.value = '';
            allProduct.innerHTML = 'All';
            ec.design.setProductFilter('');
            if (typeof json.response.product != 'string') {
                if (json.response.product.name) {
                    var product = document.createElement('option');
                    try
                    {
                      productSelect.add(product,null); // standards compliant
                    }
                    catch(ex)
                    {
                      productSelect.add(product); // IE only
                    }
                    product.value = json.response.product.id;
                    product.innerHTML = json.response.product.name;
                } else {
                    for (var index in json.response.product) {
                        if (typeof json.response.product[index] == 'object') {
                            var product = document.createElement('option');
                            try
                              {
                                productSelect.add(product,null); // standards compliant
                              }
                            catch(ex)
                              {
                                productSelect.add(product); // IE only
                              }
                            product.value = json.response.product[index].id;
                            product.innerHTML = json.response.product[index].name;
                        }
                    }
                }
            }
        }
    },

    /**
     * getSubCategories
     *
     * Returns all subcategories for the current parent category.
     *
     * @member  _design
     * @public
     */
    getSubCategories: function()
    {

        var parameters = {};
        var callback = "ec.design._addSubcategories";

        parameters.resultsCategoryId = ec.__designSelector.category.currentCategoryId;
        parameters.displayCategoryId = ec.__designSelector.category.parentCategoryId;
        parameters.displaySide = ec.__designSelector.category.currentDisplaySide;

        ec._callApi('design/subcategories', parameters, callback);
    },

    _addSubcategories: function( json )
    {

        if (ec.config.format == 'html') {
            ec.design._formatSubcategories(json);
        }
    },

    _formatSubcategories: function(json)
    {

        if (json.response.category) {

            var subCategorySelect = document.getElementById('subCategorySelect');
            var i;
            for (i = subCategorySelect.options.length-1; i>=0; i--) {
                subCategorySelect.remove(i);
            }

            var allCategory = document.createElement('option');
            try {
                subCategorySelect.add(allCategory,null); // standards compliant
            } catch (ex) {
                subCategorySelect.add(allCategory); // IE only
            }
            allCategory.value = ec.__designSelector.category.parentCategoryId;
            allCategory.innerHTML = 'All';
            if(json.response.category.id) {
                var subCategory = document.createElement('option');
                try
                  {
                     subCategorySelect.add(subCategory,null); // standards compliant
                  }
                catch(ex)
                  {
                     subCategorySelect.add(subCategory); // IE only
                  }
                subCategory.value = json.response.category.id;
                subCategory.innerHTML = json.response.category.name;

                if (ec.__designSelector.category.currentCategoryId == subCategory.value) {
                    subCategorySelect.options[1].selected = "true";
                }

            } else {
                for (var index in json.response.category) {

                    if (typeof json.response.category[index] == 'object') {
                        var subCategory = document.createElement('option');
                        try
                          {
                            subCategorySelect.add(subCategory,null); // standards compliant
                          }
                        catch(ex)
                          {
                            subCategorySelect.add(subCategory); // IE only
                          }
                        subCategory.value = json.response.category[index].id;
                        subCategory.innerHTML = json.response.category[index].name;
                        if (ec.__designSelector.category.currentCategoryId == subCategory.value) {
                            subCategory.selected = true;
                        }
                    }
                }
            }
        } else {
            var subCategorySelect = document.getElementById('subCategorySelect');
            var i;
            for (i = subCategorySelect.options.length-1; i>0; i--) {
                subCategorySelect.remove(i);
            }
        }
    },

    /**
     * getLibrary
     *
     * Returns a collection of customizable designs for the given category.
     *
     * @member  _design
     * @public
     *
     * @param {Integer} categoryId      ID of category to return a design collection for.
     * @param {String} displaySide  Side to return for the collection.  Can either be 'front' or 'back'.
     *
     */
    getLibrary: function(categoryId, displaySide)
    {
        if(ec.design.current.libraryType == 'customizable' && categoryId == '' ) {
            categoryId = ec.design.current.defaultCategory;
        }

        if (!ec.design.current.userId) {
            return false;
        }

        var parameters = {};

        parameters.categoryId = categoryId;
        parameters.libraryType = ec.design.current.libraryType;

        parameters.displaySide = displaySide || ec.design.current.displaySide;
        parameters.numberToDisplay = ec.design.current.numberToDisplay;
        parameters.pageNumber = ec.design.current.pageNumber;
        parameters.userId = ec.design.current.userId;

        if (ec.design.current.frontId > '0') {
            parameters.selectedFrontId = ec.design.current.frontId;
            parameters.selectedFrontType = ec.design.current.frontType;
        }

         if (ec.design.current.productFilter != '') {
           parameters.productFilter = ec.design.current.productFilter;
        }

        ec.__designSelector.category.currentCategoryId = categoryId;


        var callback = "ec.design._addLibrary";

        ec._dom.onLoad(ec.config.design.libraryDiv, "Please wait as designs load...");
        setTimeout(function(){ec._callApi('design/library', parameters, callback);}, 1000);
    },

    /**
     * _addLibrary
     *
     * Callback function that stores json to the ec.jsonDataStore array.
     *
     * @member  _design
     * @private
     *
     * @param {Object} json  json to store in the json data store.
     */
    _addLibrary: function( json )
    {
        ec.jsonDataStore['designCollection'] = json;

        if (ec.config.format == 'html') {
            ec.design._formatLibrary(json);

        }
    },

    /**
     *_formatLibrary
     *
     * Formats the json data into HTML.
     *
     * @member  _design
     * @param {Object} json  json to format.
     * @public
     */
    _formatLibrary: function(json)
    {
        var catHeaderBlurbDiv = document.getElementById('ec-categoryBlurb');

        if (!catHeaderBlurbDiv) return;

        if (!json.response.design) {
            alert('Sorry, there was a problem with your last action.\nPlease try reselecting your front and back designs.');
            window.location = '/ec/design';
        }

        catHeaderBlurbDiv.innerHTML = json.response.design['categoryBlurbs']['headerBlurb'];

        var catFooterBlurbDiv = document.getElementById('ec-categoryFooterBlurb');
        if (typeof catFooterBlurbDiv !== 'undefined') {
            catFooterBlurbDiv.innerHTML = json.response.design['categoryBlurbs']['footerBlurb'];
        }
        
        // Retrieve all designs.
        var suggestedDesigns = ec.design._getFormattedLibraryDesigns('suggestedDesign');
        var featuredDesigns = ec.design._getFormattedLibraryDesigns('featuredDesign');
        var alternativeDesigns = ec.design._getFormattedLibraryDesigns('alternateDesign');

        // Messaging for various steps of the design selection process.
        var messageContainer = document.createElement('div');
        messageContainer.id = 'ec-design-messageContainer';
        messageContainer.style.padding = '0px';
        messageContainer.style.margin = '0px';
        
        // Instructions for next steps, current step, etc.
        var instructionContainer = document.createElement('div');
        instructionContainer.id = 'ec-design-instructionContainer';
        // Choose side message container.
        var chooseSideMessageContainer = document.createElement('div');
        chooseSideMessageContainer.id = 'ec-design-chooseSideMessage';
        // Internal message for choose a side.
        var chooseSideMessage = document.createElement('h2');
        chooseSideMessage.innerHTML = 'back' == ec.design.current.displaySide ? 'Choose a Back/Inside:' : 'Choose a Front:';
        // Select a template message container.
        var selectTemplateContainer = document.createElement('div');
        selectTemplateContainer.id = 'ec-design-selectTemplate';
        // Left side of select template blurb.
        var selectTemplateLeft = document.createElement('div');
        selectTemplateLeft.id = 'ec-design-selectTemplateLeft';
        // Blurb for left side.
        var selectTemplateLeftMessage = document.createElement('small');
        selectTemplateLeftMessage.innerHTML = 'back' == ec.design.current.displaySide ? 'Select one of the template options below for the back/inside of your printing order.' : 'Select one of the templates below for the front of your print order.';
        // Right side of select template blurb.
        var selectTemplateRight = document.createElement('div');
        selectTemplateRight.id = 'ec-design-selectTemplateRight';
        selectTemplateRight.style.marginTop = '-18px';
        // Blurb for right side.
        var selectTemplateRightMessage = document.createElement('small');
        selectTemplateRightMessage.innerHTML = 'back' == ec.design.current.displaySide ? 'Next Step: Customize Your Design' : 'Next Step: Choosing a Back';
        // Clear
        var instructionContainerClear = document.createElement('br');
        instructionContainerClear.style.clear = 'both';
        // Assemble instruction container contents.
        chooseSideMessageContainer.appendChild(chooseSideMessage);
        selectTemplateLeft.appendChild(selectTemplateLeftMessage);
        selectTemplateRight.appendChild(selectTemplateRightMessage);
        selectTemplateContainer.appendChild(selectTemplateLeft);
        selectTemplateContainer.appendChild(selectTemplateRight);
        instructionContainer.appendChild(chooseSideMessageContainer);
        instructionContainer.appendChild(selectTemplateContainer);
        instructionContainer.appendChild(instructionContainerClear);
        
        // Blank selection container, populated with options depending on selected product.
        var blankSelectionContainer = document.createElement('div');
        blankSelectionContainer.id = 'ec-design-blankSelectionContainer';
        var placeHolder = document.getElementById(ec.config.design.libraryDiv);
        if( typeof placeHolder !== 'undefined') {
            placeHolder.innerHTML = "";
            placeHolder.appendChild(messageContainer);
            placeHolder.appendChild(instructionContainer);
            if (0 == suggestedDesigns.children.length) {
                placeHolder.appendChild(blankSelectionContainer);
            }
            if (!document.getElementById(ec.config.design.topPaginationDiv)) {
                var paginationDivTop = document.createElement('div');
                paginationDivTop.id = ec.config.design.topPaginationDiv;
                placeHolder.appendChild(paginationDivTop);
            }
        }
        if (typeof featuredDesigns !== 'undefined'){
            placeHolder.appendChild(featuredDesigns);
        }
        if (typeof suggestedDesigns !== 'undefined'){
            placeHolder.appendChild(suggestedDesigns);
        }
        if (typeof alternativeDesigns !== 'undefined') {
            placeHolder.appendChild(alternativeDesigns);
        }
        if (suggestedDesigns.children.length > 0){
            placeHolder.appendChild(blankSelectionContainer);
        }
        if (!document.getElementById(ec.config.design.bottomPaginationDiv)) {
            var paginationDivBottom = document.createElement('div');
            paginationDivBottom.id = ec.config.design.bottomPaginationDiv;
            placeHolder.appendChild(paginationDivBottom);
        }
        var position = typeof suggestedDesigns !== 'undefined' ? 'bottom' : 'top';
        ec.design.getPagination();
        // Populate content.
        jQuery.get(
            '/ec/ajax/design/selected-message',
            {"side": ec.design.current.sideSelected},
            function(data,textStatus,jqXHR) {
                jQuery(messageContainer).html(data);
                jQuery.get(
                    '/ec/ajax/design/blank-selector',
                    {"displaySide": ec.design.current.displaySide, "position": position},
                    function(data,textStatus,jqXHR) {
                        jQuery(blankSelectionContainer).html(data);
                        var el = jQuery('#ec-design-messageContainer');
                        if (el.html()) {
                            el.fadeIn(1000, function(){setTimeout(function(){el.fadeOut(1000);}, 3000)});
                        }
                    }
                );                
            }
        );
        /*
        $$get('/ec/design/selected-message/side/' + ec.design.current.sideSelected, messageContainer, function() {
            alert('get');
            $$get(
                '/ec/design/blank-selector/displaySide/' + ec.design.current.displaySide + '/position/' + position,
                blankSelectionContainer,
                function() {
                    var el = jQuery('#ec-design-messageContainer');
                    if (el.html()) {
                        el.fadeIn(1000, function(){
                            setTimeout(function(){el.fadeOut(1000);}, 3000);
                        });
                    }
                }
            );
        });
        */
        // Unset any on-view items.
        ec.design.setCurrentSideSelected(null);
        ec.__designSelector.showDesigns();
    },

    /**
     * getSaved
     *
     * Returns a collection of saved designs for the given user ID.
     *
     * @member  _design
     * @public
     *
     * @param {Integer} userId   ID of the user to return designs for.
     *
     */
    getSaved: function(userId)
    {
        var parameters = {};
        parameters.userId = userId;

        var callback = "ec.design._addSaved";

        ec._dom.onLoad(ec.config.design.libraryDiv, "Please wait as designs load...");

        ec._callApi('design/saved', parameters, callback);
    },

    /**
     * _addSaved
     *
     * Callback function that stores json to the ec.jsonDataStore array.
     *
     * @member  _design
     * @private
     *
     * @param {Object} json  json to store in the json data store.
     */
    _addSaved: function ( json )
    {
        ec.jsonDataStore['savedDesigns'] = json;

        if (ec.config.format == 'html') {
            ec.design._formatLibrary(json);
        }
    },

    /**
     * getPagination
     *
     * Returns pagination for the selected category and display side.
     *
     * @member _design
     * @public
     *
     * @param {Integer} categoryId
     * @param {String}  displaySide 'front' or 'back'
     */
    getPagination: function()
    {
        var parameters = {};
        parameters.categoryId = ec.__designSelector.category.currentCategoryId;
        parameters.libraryType = ec.design.current.libraryType;
        parameters.numberToDisplay = ec.design.current.numberToDisplay;
        parameters.pageNumber = ec.design.current.pageNumber;
        parameters.displaySide = ec.design.current.displaySide;
        parameters.userId = ec.design.current.userId;
        if (ec.design.current.displaySide == 'back') {
            parameters.SelectedFrontId = ec.design.current.frontId;
            parameters.selectedFrontType = ec.design.current.frontType;
        }
        if (ec.design.current.productFilter != '') {
           parameters.productFilter = ec.design.current.productFilter;
        }

        var callback = "ec.design._addPagination";

        ec._callApi('design/pagination', parameters, callback);
    },

    _addPagination: function(json)
    {
        ec.jsonDataStore['paging'] = json;
        ec.design._formatPagination();
    },

    _formatPagination: function()
    {
        var numberOfPages = ec.jsonDataStore.paging.response.pages;
        var totalPages = ec.jsonDataStore.paging.response.total;

        var topPaginationDiv = document.getElementById(ec.config.design.topPaginationDiv);
        var bottomPaginationDiv = document.getElementById(ec.config.design.bottomPaginationDiv);
        if (topPaginationDiv && bottomPaginationDiv) {
            if ('saved' == ec.design.current.libraryType || 'my' == ec.design.current.libraryType) {
                topPaginationDiv.className = 'ec-pagination-saved';
                bottomPaginationDiv.className = 'ec-pagination-saved';
            } else {
                topPaginationDiv.className = 'ec-pagination-customizable';
                bottomPaginationDiv.className = 'ec-pagination-customizable';
            }
            var breadcrumbNav = ec.design.getBreadcrumbNavigation(totalPages);
            topPaginationDiv.appendChild(breadcrumbNav);

           if (!document.getElementById('ec-top-current-page')) {
                var navigationSplit = '0';
                if (numberOfPages < 1) {
                    var zeroFoundMessageSpan = document.createElement('div');
                    zeroFoundMessageSpan.className = 'ec-zeroFoundMessage';
                    if (ec.design.current.libraryType == 'saved' ) {
                        zeroFoundMessageSpan.innerHTML = "Can't find what you're looking for in your 'Finished Designs'? " +
                                "Try selecting 'All Designs' in the 'Subcategory' dropdown at the left.";
                    } else if (ec.design.current.libraryType == 'unfinished') {
                        zeroFoundMessageSpan.innerHTML = "Can't find what you're looking for in your 'Unfinished Designs'? " +
                                "Try selecting 'All Designs' in the 'Subcategory' dropdown at the left.";
                    } else if (ec.design.current.libraryType == 'customizable') {
                        zeroFoundMessageSpan.innerHTML = "Can't find what you're looking for? " +
                                "Try choosing a different category using the category navigation on the left.";
                    }
                    topPaginationDiv.appendChild(zeroFoundMessageSpan);

                } else {
                    var pagesLabelTop = document.createElement('span');
                    pagesLabelTop.id = 'ec-design-paginationLabel-top';
                    pagesLabelTop.innerHTML = 'Page: ';
                    topPaginationDiv.appendChild(pagesLabelTop);
                    var pagesLabelBottom = document.createElement('span');
                    pagesLabelBottom.id = 'ec-design-paginationLabel-top';
                    pagesLabelBottom.innerHTML = 'Page: ';
                    bottomPaginationDiv.appendChild(pagesLabelBottom);
                    for (var page = 1;page <= numberOfPages;page++){
                        if(page == ec.design.current.pageNumber){
                            var topCurrentPage = document.createElement('span');
                            topCurrentPage.setAttribute('id','ec-top-current-page');
                            topCurrentPage.className =  'ec-numberedCurrent';
                            topCurrentPage.innerHTML = page;

                            topPaginationDiv.appendChild(topCurrentPage);
                            var bottomCurrentPage = document.createElement('span');
                            bottomCurrentPage.className =  'ec-numberedCurrent';
                            bottomCurrentPage.innerHTML = page;

                            bottomPaginationDiv.appendChild(bottomCurrentPage);
                        } else {
                            var topNumbered = document.createElement('a');
                            topNumbered.className = 'ec-numbered';
                            topNumbered.onclick = ec.design._handlePaginationClick;
                            topNumbered.innerHTML = page;

                            topPaginationDiv.appendChild(topNumbered);

                            var bottomNumbered = document.createElement('a');
                            bottomNumbered.className = 'ec-numbered';
                            bottomNumbered.onclick = ec.design._handlePaginationClick;
                            bottomNumbered.innerHTML = page;

                            bottomPaginationDiv.appendChild(bottomNumbered);
                        }
                        navigationSplit++
                        if (navigationSplit == '28') {
                            var topNavBreak = document.createElement('br');
                            topPaginationDiv.appendChild(topNavBreak);
                            var bottomNavBreak = document.createElement('br');
                            bottomPaginationDiv.appendChild(bottomNavBreak);
                            navigationSplit = '0';
                        }
                    }
                }
           }
        }
        setTimeout(function(){
            jQuery("#ec-design-breadcrumb-topLevel").mouseenter(
                function(event){
                    flashBG('#myDesignsDiv');
                    flashBG('#designTemplatesDiv');
                }
            ).mouseleave(
                function(event){
                    clearBG('#myDesignsDiv');
                    clearBG('#designTemplatesDiv')
                }
            );
            jQuery("#ec-design-breadcrumb-product").mouseenter(
                function(event){
                    flashBG('#productSelectDiv');
                }
            ).mouseleave(
                function(event){
                    clearBG('#productSelectDiv');
                }
            );
            jQuery("#ec-design-breadcrumb-category").mouseenter(
                function(event){
                    flashBG('#categorySelectDiv');
                }
            ).mouseleave(
                function(event){
                    clearBG('#categorySelectDiv');
                }
            );
            jQuery("#ec-design-breadcrumb-subcategory").mouseenter(
                function(event){
                    flashBG('#subCategorySelectDiv');
                }
            ).mouseleave(
                function(event){
                    clearBG('#subCategorySelectDiv');
                }
            );
            jQuery("#ec-design-breadcrumb-side").mouseenter(
                function(event){
                    flashBG('#sideSelectDiv');
                }
            ).mouseleave(
                function(event){
                    clearBG('#sideSelectDiv');
                }
            );
        }, 300);
    },
    _getImageSize: function(element, designImage)
    {
        var width;
        var height;

        switch (element.productId) {
            // Regular Postcard
            case '1':
                switch (element.orientation) {
                    // Portrait
                    case '1':
                        width = '114';
                        height = '87';
                        break;
                    // Landscape
                    case '2':
                        width = '87';
                        height = '114';
                        break;
                    // No Orientation Value
                    default:
                        width = null;
                        height = null;
                }
                break;
            // Jumbo Postcard
            case '2':
                switch (element.orientation) {
                    // Portrait
                    case '1':
                        width = '140';
                        height = '91';
                        break;
                    // Landscape
                    case '2':
                        width = '91';
                        height = '140';
                        break;
                    // No Orientation Value
                    default:
                        width = null;
                        height = null;
                }
                break;
            // Panoramic Postcard
            case '3':
                switch (element.orientation) {
                    // Portrait
                    case '1':
                        width = '175';
                        height = '90';
                        break;
                    // Landscape
                    case '2':
                        width = '90';
                        height = '175';
                        break;
                    // No Orientation Value
                    default:
                        width = null;
                        height = null;
                }
                break;
            // Business Card (no bleed)
            case '4':
                switch (element.orientation) {
                    // Portrait
                    case '1':
                        width = '150';
                        height = '86';
                        break;
                    // Landscape
                    case '2':
                        width = '86';
                        height = '150';
                        break;
                    // No Orientation Value
                    default:
                        width = null;
                        height = null;
                }
                break;
            // Business Card (bleed)
            case '5':
                switch (element.orientation) {
                    // Portrait
                    case '1':
                        width = '150';
                        height = '86';
                        break;
                    // Landscape
                    case '2':
                        width = '86';
                        height = '150';
                        break;
                    // No Orientation Value
                    default:
                        width = null;
                        height = null;
                }
                break;
            // Letter Flyer
            case '6':
                switch (element.orientation) {
                    // Portrait
                    case '1':
                        width = '112';
                        height = '87';
                        break;
                    // Landscape
                    case '2':
                        width = '87';
                        height = '112';
                        break;
                    // No Orientation Value
                    default:
                        width = null;
                        height = null;
                }
                break;
            // Door Hanger
            case '10':
                switch (element.orientation) {
                    // Portrait
                    case '1':
                        width = '73';
                        height = '200';
                        break;
                    // Landscape
                    case '2':
                        width = '73';
                        height = '200';
                        break;
                    // No Orientation Value
                    default:
                        width = null;
                        height = null;
                }
                break;
        }

        if (width != null){
            designImage.setAttribute('width', width);
        }
        if (height != null){
            designImage.setAttribute('height', height);
        }
        return designImage;
    },
    _formatDesign: function(element, designType)
    {
        if (ec.design.current.displaySide == 'back' && element.productId == '11') {
            var displaySideText = 'inside';
        } else {
            var displaySideText = ec.design.current.displaySide;
        }

        var designHolder = document.createElement('div');
        if ('my' == ec.design.current.libraryType) {
            designHolder.style.height = '300px';
        }
        designHolder.className =  'ec-design';

        var design = document.createElement('div');
        design.className = 'ec-design-design';
        if (designType == 'suggestedDesign') {
            design.innerHTML = '<b>Suggested Design</b><br />';
        }

        if (designType == 'featuredDesign') {
            design.innerHTML = '<b>Featured Design</b><br />';
        }

        var designImage = document.createElement('img');
        if (ec.design.current.displaySide == 'front' && element.productId == '11' && element.smallThumbUrl.search('t_thumbnail') > 0) {
            designImage.className = 'ec-design-image-greetingcard';
        } else {
            designImage.className = 'ec-design-image';
        }
        designImage.setAttribute('src', element.smallThumbUrl);
        designImage.setAttribute('alt', element.name);
        designImage.onclick = ec.design._handleShowDetails;
        designImage.designId = element.id;
        designImage.designType = designType;

        ec.design._getImageSize(element, designImage);

        var designName = document.createElement('div');
        designName.className =  'ec-design-name';
        designName.style.textAlign = 'center';
        designName.innerHTML = element.name;

        var designOptions = document.createElement('div');
        designOptions.className =  'ec-options';

        var sep = document.createElement('span');
        sep.innerHTML = ' | ';

        var designOptionsPricing = document.createElement('div');
        designOptionsPricing.className = 'ec-design-pricing';
        designOptionsPricing.innerHTML = element.pricing;

        var designOptionsDetails = document.createElement('img');
        designOptionsDetails.className = 'ec-design-detailsLink magnifyGlass';
        designOptionsDetails.setAttribute('title', 'view design details');
        designOptionsDetails.setAttribute('src', '/static/img/magnifyGlass.png');
        designOptionsDetails.onclick = ec.design._handleShowDetails;
        designOptionsDetails.designId = element.id;
        designOptionsDetails.designType = designType;
        designOptionsDetails.backRequired = element.backReguired;
        designOptionsDetails.productId = element.productId;
        designOptionsDetails.requiredBack = element.requiredBack;

        designName.appendChild(designOptionsDetails);

        var designOptionsSelect = document.createElement('a');
        designOptionsSelect.className =  'ec-design-select';
        designOptionsSelect.setAttribute('title', 'use this design');
        designOptionsSelect.onclick = ec.design._handleDesignSelection;
        designOptionsSelect.designId = element.id;
        designOptionsSelect.designType = element.designType;
        designOptionsSelect.backRequired = element.backRequired;
        designOptionsSelect.productId = element.productId;
        designOptionsSelect.requiredBack = element.requiredBack;
        designOptionsSelect.intent = 'select';

        if (element.designType == 'customizable') {
            selectVerb = 'Select this ';
        } else if(element.designType == 'unfinished') {
            selectVerb = 'Edit this ';
        } else if(element.designType == 'customized' || element.designType == 'uploaded') {
            selectVerb = 'Order this ';
        }

        designOptionsSelect.innerHTML = selectVerb + displaySideText;
        designOptions.appendChild(designOptionsSelect);
        if (element.designType == 'customized') {
            var designOptionsEdit = document.createElement('a');
            designOptionsEdit.className =  'ec-design-select';
            designOptionsEdit.setAttribute('title', 'edit this design');
            designOptionsEdit.intent = 'edit';
            designOptionsEdit.designId = element.userProjectId;
            designOptionsEdit.designType = element.designType;
            designOptionsSelect.designType = 'uploaded'; //in case of customized design change type on 'select' button to upload so treated as a finished design
            designOptionsEdit.backRequired = element.backRequired;
            designOptionsEdit.productId = element.productId;
            designOptionsEdit.onclick = ec.design._handleDesignSelection;
            designOptionsEdit.innerHTML = 'Edit this ' + displaySideText;
            designOptions.appendChild(designOptionsEdit);

        }

        if(element.designType != 'customizable' ) {

            if(element.designType == 'uploaded' || element.designType == 'customized') {
                var designOptionsView = document.createElement('a');
                designOptionsView.className =  'ec-design-select';
                designOptionsView.setAttribute('title', 'View this design');
                designOptionsView.pdfUrl = element.pdfUrl;
                designOptionsView.onclick = ec.design._handleShowPdf;
                designOptionsView.innerHTML = 'View this ' + displaySideText;
                designOptions.appendChild(designOptionsView);
            }
            var designOptionsDelete = document.createElement('a');
            designOptionsDelete.className =  'ec-design-select';
            designOptionsDelete.designType = element.designType;
            designOptionsDelete.designId = element.id;
            designOptionsDelete.setAttribute('title', 'Delete this design');
            designOptionsDelete.onclick = ec.design._handleDeleteDesign;
            designOptionsDelete.innerHTML = 'Delete this design';
            designOptions.appendChild(designOptionsDelete);

            if(element.designType == 'customized') {
                var designOptionsCopy = document.createElement('a');
                designOptionsCopy.className =  'ec-design-select';
                designOptionsCopy.designType = element.designType;
                designOptionsCopy.designId = element.id;
                designOptionsCopy.setAttribute('title', 'Copy this design');
                designOptionsCopy.onclick = ec.design._handleCopyDesign;
                designOptionsCopy.innerHTML = 'Copy this design';
                designOptions.appendChild(designOptionsCopy);
            }
        }

        var designOptionsProduct = document.createElement('div');
        designOptionsProduct.className =  'ec-design-product';
        designOptionsProduct.innerHTML = element.product;

        var designLabel = document.createElement('i');
        designLabel.style.display = 'block';
        designLabel.style.fontSize = '9pt';
        switch (element.designType) {
            case 'unfinished':
                designLabel.innerHTML += 'Unfinished';
                break;
            case 'uploaded':
                designLabel.innerHTML += 'Finished';
                break;
            case 'finished':
                designLabel.innerHTML += 'Finished';
                break;
            case 'customized':
                designLabel.innerHTML += 'Finished';
                break;
        }
        var designModified = document.createElement('small');
        if ('unfinished' == element.designType || 'uploaded' == element.designType || 'customized' == element.designType) {
            designLabel.innerHTML = 'Status: ' + designLabel.innerHTML;
            designModified.innerHTML = 'Last update: ' + element.lastModified;
        }
        design.appendChild(designImage);
        design.appendChild(designName);
        design.appendChild(designOptionsProduct);
        design.appendChild(designLabel);
        design.appendChild(designModified);
        var designInfo = document.createElement('div');
        designInfo.className = 'ec-design-info';
        designInfo.appendChild(design);
        var designControls = document.createElement('div');
        designControls.className = 'ec-design-controls';
        designControls.appendChild(designOptions);

        designHolder.appendChild(designInfo);
        designHolder.appendChild(designControls);
        return designHolder;
    },

    _getFormattedLibraryDesigns: function(designType)
    {
        var designs = document.createElement('div');

        if (typeof ec.jsonDataStore['designCollection'].response.design[designType] != 'string') {
            if (ec.jsonDataStore['designCollection'].response.design[designType].design.name) {
                var design = ec.design._formatDesign(ec.jsonDataStore['designCollection'].response.design[designType].design, designType);
                designs.appendChild(design);
            } else {
                for(var index in ec.jsonDataStore['designCollection'].response.design[designType].design) {
                    if (typeof ec.jsonDataStore['designCollection'].response.design[designType].design[index] == 'object') {
                        var design = ec.design._formatDesign(ec.jsonDataStore['designCollection'].response.design[designType].design[index], designType);
                        designs.appendChild(design);
                    }
                }
            }
        }

        if(designs.childNodes.length > 0) {
            switch (designType) {
                case 'suggestedDesign':
                designs.className = 'ec-suggested-designs';
                break;

                case 'featuredDesign':
                designs.className = 'ec-featured-designs';
                break;

                default:
                break;
            }
        }

        return designs;
    },
    _handleCategoryClick: function(e)
    {
        var target = e?e.target:window.event?window.event.srcElement:null;
        if (target.library) {
            ec.__designSelector.setCurrentOption('myDesigns');
            return true;
        }
        if (ec.__designSelector.page.currentTab == 'designs') {
            ec.__designSelector.setParentCategoryId(target.parentCategoryId);
            ec.__designSelector.setCurrentCategoryId(target.categoryId);
            ec.__designSelector.setNameForDisplay(target.categoryName);
            ec.__designSelector.switchLibrary('customizableDesigns');
            if (ec.design.categoryMap[target.categoryId]) {
                ec.design.reflectSelectedCategory(ec.design.categoryMap[target.categoryId]);
            } else {
                ec.design.reflectSelectedCategory(target.parentCategoryId);
            }
        } else {
            var tabBody = document.getElementById('tab-body');
            tabBody.currentCategoryName = target.categoryName;
            ec._utility.tab.select('designs', 'tab-fileType');
            ec.__designSelector.setParentCategoryId(target.parentCategoryId);
            ec.__designSelector.setCurrentCategoryId(target.categoryId);
            ec._ajax.getHtml('/ec/design/designs', $byId('tab-body'), ec.__designSelector._backToDesignsCallback);
        }
        ec.__ga.trackEvent('designCategoryView', target.categoryName);
        jQuery('#categorySelectDiv').fadeIn();
    },

    _handlePaginationClick: function(e)
    {
        var target = e?e.target:window.event?window.event.srcElement:null;
        ec.design.setCurrentPageNumber(target.innerHTML);
        ec.design.getLibrary(ec.__designSelector.category.currentCategoryId);
    },

    _handleBlankBackSelection: function()
    {
        jQuery('#ec-design-returnToCustomizing').fadeOut();
        ec.design.setCurrentBackId(null);
        ec.design.setCurrentBackIntention(null);
        ec.design.setCurrentBackProductId(null);
        ec.design.setCurrentBackRequired(null);
        ec.design.setCurrentBackType(null);
        ec.__designSelector.doneSelecting();
        $$get('/ec/design/remove-back');
    },

    _handleDesignSelection: function(e)
    {
        jQuery('#ec-design-returnToCustomizing').fadeOut();

        if (e && e.getAttribute && e.getAttribute('designid')) {
            var target = {};
            target.designId = e.getAttribute('designid');
            target.designType = e.getAttribute('designtype');
            target.intent = e.getAttribute('intent');
            target.backRequired = e.getAttribute('backrequired');
            target.productId = e.getAttribute('productid');
            target.requiredBack = e.getAttribute('requiredback');
        } else {
            var target = e?e.target:window.event?window.event.srcElement:null;
        }
        if (!target) var target = {};
        if (target.fromModal == 'true') {
            var divToClose = target.parentNode.id;
            modalWindow.close(divToClose);
        }

        ec.design.reflectSelectedProduct(target.productId);

        if (ec.design.current.finished && ec.design.current.displaySide == "front" && ec.design.current.frontId) {
            ec._modal.height = "252px";
            $$modal('/ec/design/prompt/'+
                'designId/' + target.designId +
                '/designType/' + target.designType +
                '/intent/' + target.intent +
                '/backRequired/' + target.backRequired +
                '/productId/' + target.productId +
                '/requiredBack/' + target.requiredBack
                );
        } else {
            ec.__designSelector.setDesign(target.designId,target.designType,target.intent,target.backRequired, target.productId, target.requiredBack);
        }
        var editorStep = $byId('progressButtonDesignEditorStep');
        if (editorStep) editorStep.className ='progressButton';
        var optionsStep = $byId('progressButtonDeliveryOptionsStep');
        if (optionsStep) optionsStep.className='progressButton';
   },

   _handleShowDetails: function(e)
   {
           var target = e?e.target:window.event?window.event.srcElement:null;
           ec.__designSelector.showDetails(target.designId, target.designType, target.backRequired);

   },

   _handleShowPdf: function(e)
   {
        var target = e?e.target:window.event?window.event.srcElement:null;
        window.open(target.pdfUrl);
   },

   _handleDeleteDesign: function(e)
   {
        var target = e?e.target:window.event?window.event.srcElement:null;
        ec.__designSelector.deleteDesign(target.designId, target.designType);

   },

   _handleCopyDesign: function(e)
   {
        var target = e?e.target:window.event?window.event.srcElement:null;
        ec._modal.height = '144px';
        $$modal('/ec/design/get-name/designId/'+ target.designId);
   },

   _handleCategoryExpand: function(e)
   {
        var target = e?e.target:window.event?window.event.srcElement:null;
        document.getElementById( target.divToShow ).style.display = 'block';
        target.innerHTML = '-';
        target.onclick = ec.design._handleCategoryCollapse;

   },

   _handleCategoryCollapse: function(e)
   {
           var target = e?e.target:window.event?window.event.srcElement:null;
           document.getElementById( target.divToShow ).style.display = 'none';
        target.innerHTML = '+';
        target.onclick = ec.design._handleCategoryExpand;
   }

}

ec.design = _design;
_design = {};
/**
 * @file components/image.js
 */
var _image = {
    /**
     * getCategories
     *
     * Makes API call that gets image categories as json wrapped in a callback function call.
     *
     * @member  _image
     * @public
     */
    current:
    {
        categoryId: '',
        type: '',
        page: '1',
        callingPage: 'designSelector'
    },

    setCurrentCategoryId: function (categoryId) {
        ec.image.current.categoryId = categoryId;
    },

    setCurrentType: function (type) {
        ec.image.current.type = type;
    },

    setCurrentPageNumber: function (page) {
        ec.image.current.page = page;
    },

    setCurrentCallingPage: function () {
        var currentLocation = window.location.pathname;
        var currentBaseLocation = currentLocation.substring(0, 10);

    	if(currentBaseLocation == "/ec/design") {
    		ec.image.current.callingPage = 'designSelector';
    	} else {
    		ec.image.current.callingPage = 'editor';
    	}
    },


    getCategories: function () {
    	ec.image.setCurrentCallingPage();
        var parameters = {};

        var callback = "ec.image._addCategories";

        if (document.getElementById(ec.config.image.libraryDiv)) {
            var imageDiv = document.getElementById(ec.config.image.libraryDiv);
            imageDiv.innerHTML = '';
        }

        ec._dom.onLoad(ec.config.image.categoryDiv, "Please wait...");
        ec._callApi('design/image/categories', parameters, callback);
    },
    /**
     * getLibrary
     *
     * Makes API call that gets the image library as json wrapped in a callback function call.
     *
     * @member  _image
     * @param {Integer} categoryId  Id of the category to pull images from.
     * @public
     */
    getLibrary: function(categoryId) {
        ec.image.setCurrentCallingPage();
    	ec.image.setCurrentCategoryId(categoryId);
    	ec.image.setCurrentType('library');
        var parameters = {};
        parameters.categoryId = categoryId;
        parameters.page = ec.image.current.page;
        parameters.limit = 9;
        var callback = "ec.image._addLibrary";

        if (document.getElementById(ec.config.image.libraryDiv)) {
            var imageDiv = document.getElementById(ec.config.image.libraryDiv);
            imageDiv.innerHTML = '';
        }

        ec._dom.onLoad(ec.config.image.libraryDiv, "Please wait...");
        ec._callApi('design/image/library', parameters, callback);
    },
    /**
     * getSaved
     *
     * Makes API call that gets the saved images for the userId as json wrapped in a callback function call.
     *
     * @member  _image
     * @public
     */
    getSaved: function(eztId) {
        ec.image.setCurrentCallingPage();
        var parameters = {};
        if (eztId) {
            parameters.userId = eztId;
        } else {
            if (ec.image.current.callingPage == 'editor') {
                parameters.userId = ec.__editor.current.eztId;
            } else {
                parameters.userId = ec.design.current.eztId;
            }
        }
        parameters.page = ec.image.current.page;
        parameters.limit = 9;
        ec.image.setCurrentType('saved');

        var callback = "ec.image._addSavedImages";

        if (document.getElementById(ec.config.image.categoryDiv)) {
            var menu = document.getElementById(ec.config.image.categoryDiv);
            menu.innerHTML = '';
        }
        ec._dom.onLoad(ec.config.image.libraryDiv, "Please wait...");
        ec._callApi('design/image/saved', parameters, callback);
   },

   getIndustryLogos: function() {
        ec.image.setCurrentCallingPage();
        ec.image.setCurrentType('industry');
        var parameters = {};
        parameters.page = ec.image.current.page;
        parameters.limit = 9;
        var callback = "ec.image._addLibrary";

        if (document.getElementById(ec.config.image.libraryDiv)) {
            var imageDiv = document.getElementById(ec.config.image.libraryDiv);
            imageDiv.innerHTML = '';
        }

        if (document.getElementById(ec.config.image.categoryDiv)) {
            var menu = document.getElementById(ec.config.image.categoryDiv);
            menu.innerHTML = '';
        }

        ec._dom.onLoad(ec.config.image.libraryDiv, "Please wait...");
        ec._callApi('design/image/industry', parameters, callback);
    },

    getCompanyLogos: function() {
        ec.image.setCurrentCallingPage();
        ec.image.setCurrentType('logo');
        var parameters = {};
        parameters.page = ec.image.current.page;
        parameters.limit = 9;
        var callback = "ec.image._addLibrary";

        if (document.getElementById(ec.config.image.libraryDiv)) {
            var imageDiv = document.getElementById(ec.config.image.libraryDiv);
            imageDiv.innerHTML = '';
        }

        if (document.getElementById(ec.config.image.categoryDiv)) {
            var menu = document.getElementById(ec.config.image.categoryDiv);
            menu.innerHTML = '';
        }

        ec._dom.onLoad(ec.config.image.libraryDiv, "Please wait...");
        ec._callApi('design/image/logo', parameters, callback);
    },

    getCoupons: function() {
        ec.image.setCurrentCallingPage();
        ec.image.setCurrentType('coupon');
        var parameters = {};
        parameters.page = ec.image.current.page;
        parameters.limit = 9;
        var callback = "ec.image._addLibrary";

        if (document.getElementById(ec.config.image.libraryDiv)) {
            var imageDiv = document.getElementById(ec.config.image.libraryDiv);
            imageDiv.innerHTML = '';
        }

        if (document.getElementById(ec.config.image.categoryDiv)) {
            var menu = document.getElementById(ec.config.image.categoryDiv);
            menu.innerHTML = '';
        }

        ec._dom.onLoad(ec.config.image.libraryDiv, "Please wait...");
        ec._callApi('design/image/coupon', parameters, callback);
    },

   getPaging: function() {
   	    ec.image.setCurrentCallingPage();
   	    var parameters = {};
   	    if (ec.image.current.callingPage == 'editor') {
   	    	parameters.userId = ec.__editor.current.eztId;
   	    } else {
            parameters.userId = ec.design.current.eztId;
   	    }
        parameters.categoryId = ec.image.current.categoryId;
        parameters.type = ec.image.current.type;
        parameters.limit = 9;
        var callback = "ec.image._addPaging";
        ec._callApi('design/image/paging', parameters, callback);
   },

   deleteSaved: function(imageId)
   {
        var confirmed = confirm('Are you sure you want to delete this image?');
        if(confirmed){
           $$get('/ec/image/delete/imageId/' + imageId,'', function(){ec.image.getSaved();});
        }
    },
   /**
    *_addCategories
    *
    * Callback function that stores json to the ec.jsonDataStore array.
    *
    * While the callback functions only vary slighly from each other, they cannot be combined into one generic
    * function, as the callback only allows one parameter; the json object.
    *
    * @member  _image
    * @param {Object} json  json to store in the json data store.
    * @public
    */
   _addCategories: function (json) {
       ec.jsonDataStore['imageCategoryMenu'] = json;

       if (ec.config.format == 'html') {
           ec.image._formatCategories(json);
       }
   },
   /**
    *_addLibrary
    *
    * Callback function that stores json to the ec.jsonDataStore array.
    *
    * @member  _image
    * @param {Object} json  json to store in the json data store.
    * @public
    */
   _addLibrary: function (json) {
       ec.jsonDataStore['imageLibrary'] = json;

       if (ec.config.format == 'html') {
           ec.image._formatLibrary(json, 'library');
       }
   },
   /**
    *_addSavedImages
    *
    * Callback function that stores json to the ec.jsonDataStore array.
    *
    * @member  _image
    * @param {Object} json  json to store in the json data store.
    * @public
    */
   _addSavedImages: function (json) {
       ec.jsonDataStore['savedImages'] = json;

       if (ec.config.format == 'html') {
           ec.image._formatLibrary(json, 'saved');
       }
   },
   _addPaging: function (json) {
       ec.jsonDataStore['paging'] = json;

       if (ec.config.format == 'html') {
           ec.image._formatPaging(json);
       }
   },
   /**
    *_formatCategories
    *
    * Formats the json data into HTML.
    *
    * @member  _image
    * @param {Object} json  json to format.
    * @public
    */
   _formatCategories: function(json) {
       var placeHolder = document.getElementById(ec.config.image.categoryDiv);
       placeHolder.innerHTML = "";
       placeHolder.innerHTML = "<strong>Select From:</strong> ";
       placeHolder.style.display = 'block';
       placeHolder.style.backgroundColor = '#EAEAEA';

       if(document.getElementById('uploadForm')){
            var uploadForm = document.getElementById('uploadForm');
            uploadForm.innerHTML = '';
       }

       for ( var index in json.response.category ) {
           if (typeof json.response.category[index] == 'object') {
               if (json.response.category[index].category){

                   var jsonToPass = json.response.category[index];

                   menuLink = document.createElement('a');
                   menuLink.className = 'ec-image-menuLink';
                   menuLink.innerHTML = json.response.category[index].name;
                   menuLink.indexValue = index;
                   menuLink.onclick = ec.__imageManager._handleCategoryClick;
               } else {
                   menuLink.innerHTML = json.response.category[index].name;
                   menuLink.categoryId = json.response.category[index].id;
                   menuLink.onclick = ec.__imageManager._handleBottomLevelCategoryClick;

               }
               placeHolder.appendChild(menuLink);
           }
       }



   },
   /**
    *_formatSubCategories
    *
    * Formats the json data into HTML.
    *
    * @member  _image
    * @param {Object} json  json to format.
    * @public
    */
   _formatSubCategories: function(index) {
       var divElement = document.getElementById(ec.config.image.categoryDiv);
       var subElement = document.getElementById('subSubMenu');

       if (document.getElementById('subSubMenu')) {
           var subElement = document.getElementById('subSubMenu');
           subElement.innerHTML = '';
       }

       var subMenuItem = document.createElement('div');
       subMenuItem.setAttribute('id', 'ec-image-subMenu');

       for ( var subIndex in ec.jsonDataStore['imageCategoryMenu'].response.category[index].category){


           var subMenuLink = document.createElement('a');
           subMenuLink.setAttribute('id', 'subMenuLink_' + subIndex);
           subMenuLink.className = 'imageManagerLink';
           subMenuLink.subIndexValue = subIndex;
           subMenuLink.indexValue = index;

           if (ec.jsonDataStore['imageCategoryMenu'].response.category[index].category[subIndex].category){
               subMenuLink.onclick = ec.__imageManager._handleCategoryClick;
           } else {
                subMenuLink.categoryId = ec.jsonDataStore['imageCategoryMenu'].response.category[index].category[subIndex].id;
                subMenuLink.onclick = ec.__imageManager._handleBottomLevelCategoryClick;
           }

           if (ec.jsonDataStore['imageCategoryMenu'].response.category[index].category[subIndex].name) {
               subMenuLink.innerHTML = ec.jsonDataStore['imageCategoryMenu'].response.category[index].category[subIndex].name;
               sep = document.createElement('span');
               sep.innerHTML = ' | ';
               subMenuItem.appendChild(subMenuLink);
               subMenuItem.appendChild(sep);
            }
       }

       if (document.getElementById('ec-image-subMenu')) {
           var subMenuDiv = document.getElementById('ec-image-subMenu');
       }
       if (typeof subMenuDiv == 'object') {
           divElement.replaceChild(subMenuItem, subMenuDiv);
       } else {
           divElement.appendChild(subMenuItem);
       }

   },
   /**
    *_formatSubSubCategories
    *
    * Formats the json data into HTML.
    *
    * @member  _image
    * @param {Object} json  json to format.
    * @public
    */
   _formatSubSubCategories: function(subIndex, index) {
       var divElement = document.getElementById(ec.config.image.categoryDiv);

       var subMenuItem = document.createElement('div');
       subMenuItem.setAttribute('id', 'subSubMenu');

       for ( var subSubIndex in ec.jsonDataStore['imageCategoryMenu'].response.category[index].category[subIndex].category ){
           var subMenuLink = document.createElement('a');
           subMenuLink.categoryId = ec.jsonDataStore['imageCategoryMenu'].response.category[index].category[subIndex].category[subSubIndex].id;
           subMenuLink.onclick = ec.__imageManager._handleBottomLevelCategoryClick;

           if (ec.jsonDataStore['imageCategoryMenu'].response.category[index].category[subIndex].category[subSubIndex].name) {
               subMenuLink.innerHTML = ec.jsonDataStore['imageCategoryMenu'].response.category[index].category[subIndex].category[subSubIndex].name;
               separator = document.createElement('span');
               separator.innerHTML = ' | ';
               subMenuItem.appendChild(subMenuLink);
               subMenuItem.appendChild(separator);
           }
       }

       if (document.getElementById('subSubMenu')) var subMenuDiv = document.getElementById('subSubMenu');
       if (typeof subMenuDiv == 'object') {
           divElement.replaceChild(subMenuItem, subMenuDiv);
       } else {
           divElement.appendChild(subMenuItem);
       }

   },
   /**
    *_formatLibrary
    *
    * Formats the json data into HTML.
    *
    * @member  _image
    * @param {Object} json  json to format.
    * @public
    */
   _formatLibrary: function(json, type) {
       ec.image.setCurrentCallingPage();
       var placeHolder = document.getElementById(ec.config.image.libraryDiv);
       placeHolder.innerHTML = '';
       var messageDiv = document.createElement('div');
       messageDiv.id = ec.config.image.messageDiv;
       placeHolder.appendChild(messageDiv);
       var paginationDivTop = document.createElement('div');
       paginationDivTop.id = ec.config.image.topPaginationDiv;
       paginationDivTop.className = 'ec-pagination-customizable';
       placeHolder.appendChild(paginationDivTop);

       if(document.getElementById('fieldName')){
            var fieldDiv = document.getElementById('fieldName');
            var fieldName = fieldDiv.getAttribute('value');
       }
       if(document.getElementById('userProjectId')){
            var userProjectDiv = document.getElementById('userProjectId');
            var userProjectId = userProjectDiv.getAttribute('value');
       }

       if(document.getElementById('uploadForm')){
            var uploadForm = document.getElementById('uploadForm');
            uploadForm.innerHTML = '';
       }

       if (json.response.array && json.response.array.thumbUrl) {

          var image = document.createElement('div');
               image.className = 'ec-image-image';
               image.innerHTML = "<img src=\"" +json.response.array.thumbUrl + "\"><br />";
               if(type == 'saved'){
                   image.innerHTML += "<a onclick=\"ec.image.deleteSaved("+ json.response.array.id + ")\"> Delete this image </a>";
                   image.innerHTML += "<br\>";
               }

                if (ec.image.current.type == 'coupon') {
                    imageName = document.createElement('span');
                    imageName.innerHTML = json.response.array.name;
                    image.appendChild(imageName);
                }

                if(ec.image.current.callingPage == 'designSelector') {
                    if (type != 'saved') {
                       if(ec.design.current.bootData['tempUser']) {
                           var imageLink = document.createElement('span');
                           imageLink.innerHTML = 'Login to Save to my images';
                           image.appendChild(imageLink);
                       } else {
                           var imageLink = document.createElement('a');
                           imageLink.setAttribute('href', '#');
                           imageLink.innerHTML = 'Save to my images';
                           imageLink.onclick = ec.image._handleSaveClick;

                           imageLink.imageId = json.response.array.id;
                           image.appendChild(imageLink);
                       }
                    }
               } else {
                   var imageLink = document.createElement('a');
                   imageLink.setAttribute('href', '#');
                   imageLink.innerHTML = 'use this image';
                   imageLink.fieldName = fieldName;
                   imageLink.encodedUri = encodeURIComponent(json.response.array.windowsPath);
                   imageLink.userProjectId = userProjectId;
                   imageLink.onclick = ec.__imageManager._handleAssignImageToDesignClick;
                   image.appendChild(imageLink);
               }

               placeHolder.appendChild(image);

       } else {
	       for (var index in json.response.array) {
               if (typeof json.response.array[index] == 'object') {
                   var image = document.createElement('div');
                   image.className = 'ec-image-image';
                   image.innerHTML = "<img src=\"" +json.response.array[index].thumbUrl + "\"><br />";
                   if(type == 'saved'){
                       image.innerHTML += "<a onclick=\"ec.image.deleteSaved("+ json.response.array[index].id + ")\"> Delete this image </a>";
                       image.innerHTML += "<br\>";
                   }
                    if (ec.image.current.type == 'coupon') {
                        imageName = document.createElement('span');
                        imageName.innerHTML = json.response.array[index].name + "<br />";
                        image.appendChild(imageName);
                    }
                    if(ec.image.current.callingPage == 'designSelector') {
                        if (type != 'saved') {
                            var tempUser;
                            if(ec.image.current.callingPage == 'designSelector') {
                                tempUser = ec.design.current.bootData['tempUser'];
                            } else if(ec.image.current.callingPage == 'editor') {
                                tempUser = ec.__editor.current.tempUser;
                            }
                           if(tempUser) {
                               var imageLink = document.createElement('span');
                               imageLink.innerHTML = 'Login to Save to my images';
                               image.appendChild(imageLink);
                           } else {
                               var imageLink = document.createElement('a');
                               imageLink.setAttribute('href', '#');
                               imageLink.innerHTML = 'Save to my images';
                               imageLink.onclick = ec.image._handleSaveClick;

                               imageLink.imageId = json.response.array[index].id;
                               image.appendChild(imageLink);
                           }
                        }
                   } else {
                       var imageLink = document.createElement('a');
                       imageLink.setAttribute('href', '#');
                       imageLink.innerHTML = 'use this image';
                       imageLink.fieldName = fieldName;
                       imageLink.encodedUri = encodeURIComponent(json.response.array[index].windowsPath);
                       imageLink.userProjectId = userProjectId;
                       imageLink.onclick = ec.__imageManager._handleAssignImageToDesignClick;
                       image.appendChild(imageLink);
                   }

                   placeHolder.appendChild(image);
               }
	       }
       }

       var paginationBottomTop = document.createElement('div');
       paginationBottomTop.id = ec.config.image.bottomPaginationDiv;
       paginationBottomTop.className = 'ec-pagination-customizable';
       placeHolder.appendChild(paginationBottomTop);
       ec.image.getPaging();
   },

   _formatPaging: function( json ) {
   	    var numberOfPages = ec.jsonDataStore.paging.response.pages;
        var totalPages = ec.jsonDataStore.paging.response.total;
        var topPaginationDiv = document.getElementById(ec.config.image.topPaginationDiv);
        var bottomPaginationDiv = document.getElementById(ec.config.image.bottomPaginationDiv);

        var topTotalFoundDiv = document.createElement('div');
        topTotalFoundDiv.className =  'ec-pagination-total';
        topTotalFoundDiv.innerHTML = "Found " + totalPages + " matching";
        topPaginationDiv.appendChild(topTotalFoundDiv);

        var bottomTotalFoundDiv = document.createElement('div');
        bottomTotalFoundDiv.className =  'ec-pagination-total';
        bottomTotalFoundDiv.innerHTML = "Found " + totalPages + " matching";
        bottomPaginationDiv.appendChild(bottomTotalFoundDiv);

        var navigationSplit = '0';
        for (var page = 1;page <= numberOfPages;page++){
            if(page == ec.image.current.page){
                var topCurrentPage = document.createElement('span');
                topCurrentPage.className =  'ec-numberedCurrent';
                topCurrentPage.innerHTML = page;

                topPaginationDiv.appendChild(topCurrentPage);
                var bottomCurrentPage = document.createElement('span');
                bottomCurrentPage.className =  'ec-numberedCurrent';
                bottomCurrentPage.innerHTML = page;

                bottomPaginationDiv.appendChild(bottomCurrentPage);
            } else {
                var topNumbered = document.createElement('a');
                topNumbered.className = 'ec-numbered';
                topNumbered.onclick = ec.image._handlePaginationClick;
                topNumbered.innerHTML = page;

                topPaginationDiv.appendChild(topNumbered);

                var bottomNumbered = document.createElement('a');
                bottomNumbered.className = 'ec-numbered';
                bottomNumbered.onclick = ec.image._handlePaginationClick;
                bottomNumbered.innerHTML = page;

                bottomPaginationDiv.appendChild(bottomNumbered);
            }
            navigationSplit++
            if (navigationSplit == '28') {
                var topNavBreak = document.createElement('br');
                topPaginationDiv.appendChild(topNavBreak);
                var bottomNavBreak = document.createElement('br');
                bottomPaginationDiv.appendChild(bottomNavBreak);
                navigationSplit = '0';
            }
        }
   },

   _handlePaginationClick: function(e)
    {
        var target = e?e.target:window.event?window.event.srcElement:null;
        ec.image.setCurrentPageNumber(target.innerHTML);
        switch (ec.image.current.type) {
        	case 'saved':
        	   ec.image.getSaved(ec.design.current.eztId);
        	break;
        	case 'library':
        	   ec.image.getLibrary(ec.image.current.categoryId)
        	break;
        	case 'logo':
        	   ec.image.getCompanyLogos();
        	break;
        	case 'industry':
        	   ec.image.getIndustryLogos()
        	break;
            case 'coupon':
               ec.image.getCoupons();
            break;
        }

    },

    _handleSaveClick: function(e)
    {
        var target = e?e.target:window.event?window.event.srcElement:null;
        var callback = function(){ec.image.getSaved(ec.design.current.eztId);};//"ec.image._addLibrayImageToSaved";
        var parameters = {};
        parameters.ezt2Id = ec.design.current.eztId;
        parameters.imageId = target.imageId;
        parameters.userId = ec.design.current.eztId;
        parameters.type = ec.image.current.type;
        ec._dom.onLoad(ec.config.image.messageDiv, "Saving, please wait...");
        $$post(
                    '/ec/image/save',
                    ec.config.image.messageDiv,
                    callback,
                    parameters
                );

    },

    _addLibrayImageToSaved: function()
    {
    	 var messageDiv = document.getElementById(ec.config.image.messageDiv);
    	 messageDiv.innerHTML = '';
    }

}

ec.image = _image;
_image = {};
/**
 * @file components/pricing.js
 */
var _pricing = {
    // deliverMethod: '',
    //stockMethod: '',
    showSection: function() {
        //global variables holding user selected values
        window.stockMethod = '';
        window.colorMethod = '';
        window.deliverMethod = '';
        window.quantityVal = '';
        if (!window.shippingOptionId) window.shippingOptionId = 1;

        baseProduct = jQuery('#ppp').val();

        var parameters = {};
        parameters.baseProduct = baseProduct;

        var callback = "ec.pricing._addMenu";
        var id = 'selectionsApiScript';

        jQuery("#startMyOrder").fadeIn();
        ec._callApi('product/collections', parameters, callback);
    },

    selectedVal: function(divId) {

        var result = 0;
        if (document.getElementById(divId)) {
            for (var z = 0; z <document.getElementById(divId).length; ++z ) {
                if (document.getElementById(divId).options[z].selected == true ) {
                    result = document.getElementById(divId).options[z].value;
                    break;
                }
            }
        }

        return result;
    },

    checkKeypress: function(e) {
        var keynum;
        if (window.event) { // IE
            keynum = e.keyCode;
        } else if (e.which) { // Netscape/Firefox/Opera
            keynum = e.which;
        }
        if (13 == keynum) {
            this.getEstimate();
        }
    },

    //checks what is already selected and save them as global variables. use it before
    //builing stock and color menu
    checkSelected: function() {

        window.deliverMethod = ec.pricing.selectedVal("aaa");
        window.stockMethod = ec.pricing.selectedVal("bbb");
        //ec.pricing.stockMethod = 0;
        window.colorMethod = ec.pricing.selectedVal("ccc");
        if (document.getElementById('inputNumber')) {
            window.quantityVal = document.getElementById('inputNumber').value;
        } else {
            window.quantityVal = 0;
        }
    },

    showResult: function() {
        if (deliverMethod == 0 || stockMethod == 0 || colorMethod == 0 || baseProduct == 0) {
            var placeHolder = document.getElementById('estimate');
            placeHolder.className = "pricing";
            var minMessage = document.getElementById('minQuantity');
            minMessage.innerHTML = '';
            placeHolder.innerHTML = '';
        } else if (deliverMethod != 0 && stockMethod != 0 && colorMethod != 0 && baseProduct != 0 && quantityVal > Number(0) ) {
            ec.pricing.getEstimate();
        }

    },

    productPrintMenu: function() {
        var parameters = {};
        parameters.siteId = ec.config.siteId ? ec.config.siteId : 2;
        parameters.printGroup = window.currentProductPrintGroup ? window.currentProductPrintGroup : 'all';
        ec._callApi('product/printOptions', parameters, 'ec.pricing._formatProductPrintMenu');
    },

    deliverMenu: function() {
        ec.pricing.checkSelected();

        var placeHolder = document.getElementById('mailingSelections');
        placeHolder.className = "pricing";
        y = 0;
        var deliverIndex = 0;
        newDeliverArray = new Array();
        newDeliverName = new Array();
        deliveryArray = window.deliveryArray;

        while (y < deliveryArray.length)
        {
            //var arrayResult = ec.jsonDataStore['productMenu'].response.array[y];
            if (stockMethod == 0 && colorMethod == 0) { //only product selected
                if (baseProduct == ec.jsonDataStore['productMenu'].response.array[y].product) {
                    newDeliverArray[deliverIndex] = deliveryArray[y];
                    newDeliverName[deliverIndex] = deliverName[y];
                    deliverIndex ++;
                }
            } else if (stockMethod != 0 && colorMethod == 0) { //only stock selected
                if (baseProduct == ec.jsonDataStore['productMenu'].response.array[y].product & stockMethod == ec.jsonDataStore['productMenu'].response.array[y].stock) {
                    newDeliverArray[deliverIndex] = deliveryArray[y];
                    newDeliverName[deliverIndex] = deliverName[y];
                    deliverIndex ++;
                }
            } else if (stockMethod == 0 && colorMethod != 0) { //only color selected
                if (baseProduct == ec.jsonDataStore['productMenu'].response.array[y].product & colorMethod == ec.jsonDataStore['productMenu'].response.array[y].color) {
                    newDeliverArray[deliverIndex] = deliveryArray[y];
                    newDeliverName[deliverIndex] = deliverName[y];
                    deliverIndex ++;
                }
            } else if (stockMethod != 0 && colorMethod != 0) { //both stock and color are available
                if (baseProduct == ec.jsonDataStore['productMenu'].response.array[y].product & colorMethod == ec.jsonDataStore['productMenu'].response.array[y].color & stockMethod == ec.jsonDataStore['productMenu'].response.array[y].stock) {
                    newDeliverArray[deliverIndex] = deliveryArray[y];
                    newDeliverName[deliverIndex] = deliverName[y];
                    deliverIndex ++;
                }
            }

            y ++;
        }

        tempMenu = '<div id="pricing-delivery"><label for="mailMenu">Delivery:</label><select tabindex="2" id="aaa" name="mailMenu" onChange="{ec.pricing.stockMenu(); ec.pricing.autoAdvanceAll();}"></div>';
        //if stock color and product combination doesn't contain anything, we have a problem, reset deliver menu
        if (newDeliverArray != '') {
            options = buildMenu(newDeliverArray, newDeliverName, deliverMethod);
        } else {
            deliverMethod = 0;
            stockMethod = 0;
            colorMethod =0;
            options = buildMenu(deliveryArray, deliverName, deliverMethod);
            var stockHolder = document.getElementById('stockOptions');
            stockHolder.innerHTML = '';
            var colorHolder = document.getElementById('colorOptions');
            colorHolder.innerHTML = '';
        }

        placeHolder.innerHTML = tempMenu + options + '</select>';
           
        ec.pricing.showResult();
        ec.pricing._updateCSS();
        jQuery('#pricing-delivery').fadeIn(500);
    },

    stockMenu: function() {
        var placeHolder = document.getElementById('stockOptions');
        placeHolder.className = "pricing";
        ec.pricing.checkSelected();
        ec.pricing.deliverMenu();

        var y =0;
        var stockArray = new Array();
        var stockName = new Array();
        var stockIndex = 0;

        while (y < ec.jsonDataStore['productMenu'].response.array.length)
        {
            if (deliverMethod == 0 && colorMethod == 0) { //only product is selected
                if (ec.jsonDataStore['productMenu'].response.array[y].product == baseProduct ) {
                    stockArray[stockIndex] = ec.jsonDataStore['productMenu'].response.array[y].stock;
                    stockName[stockIndex] = ec.jsonDataStore['productMenu'].response.array[y].stockName;
                    stockIndex ++;
                }
            } else if (deliverMethod != 0 && colorMethod == 0) { //only deliver is selected
                if (deliveryArray[y] == deliverMethod & ec.jsonDataStore['productMenu'].response.array[y].product == baseProduct ) {
                    stockArray[stockIndex] = ec.jsonDataStore['productMenu'].response.array[y].stock;
                    stockName[stockIndex] = ec.jsonDataStore['productMenu'].response.array[y].stockName;
                    stockIndex ++;
                }
            } else if (deliverMethod == 0 && colorMethod != 0) { //only color is selected
                if (colorMethod == ec.jsonDataStore['productMenu'].response.array[y].color & ec.jsonDataStore['productMenu'].response.array[y].product == baseProduct ) {
                    stockArray[stockIndex] = ec.jsonDataStore['productMenu'].response.array[y].stock;
                    stockName[stockIndex] = ec.jsonDataStore['productMenu'].response.array[y].stockName;
                    stockIndex ++;
                }
            } else if (deliverMethod != 0 && colorMethod != 0) { //both deliver and color are selected
                if (deliveryArray[y] == deliverMethod & ec.jsonDataStore['productMenu'].response.array[y].product == baseProduct & colorMethod == ec.jsonDataStore['productMenu'].response.array[y].color) {
                    stockArray[stockIndex] = ec.jsonDataStore['productMenu'].response.array[y].stock;
                    stockName[stockIndex] = ec.jsonDataStore['productMenu'].response.array[y].stockName;
                    stockIndex ++;
                }
            }
            y++;
        }

        tempMenu = '<div id="pricing-paper"><label for="stockMenu">Paper:</label><select tabindex="4" id="bbb" name="stockMenu" onChange="{ec.pricing.colorMenu(); ec.pricing.autoAdvanceAll();}"></div>';
        options = buildMenu(stockArray, stockName, stockMethod);

        placeHolder.innerHTML = tempMenu + options + '</select>';

        ec.pricing.showResult();

        jQuery('#pricing-paper').fadeIn(500);
          
        var zipCode = window.zipCode && isFinite(window.zipCode) ? window.zipCode : window.zipCode && window.zipCode.value ? window.zipCode.value : '';
        var zipPlaceHolder = jQuery('#zipCodeContainer');
        zipPlaceHolder.addClass('pricing');
        if (deliverMethod > 30) {
            jQuery('#zipCodeContainer').show();
            zipPlaceHolder.html('<div id="pricing-zipcode"><label for="zipCode">Zip Code: </label> <input tabindex="3" id="zipCode" size="10" type="text" name="zipCode" value="' + zipCode + '" onchange="ec.pricing._cleanZipcode(true);" /></div>');
            jQuery('#pricing-zipcode').fadeIn(500);
        } else {
            jQuery('#zipCodeContainer').hide();
            jQuery('#pricing-zipcode').fadeOut();
        }
          
    },

    colorMenu: function() {
        var placeHolder = document.getElementById('colorOptions');
        placeHolder.className = "pricing";
        ec.pricing.checkSelected();
        ec.pricing.stockMenu();

        y = 0;
        colorArray = new Array();
        colorName = new Array();
        var colorIndex = 0;

        while (y < ec.jsonDataStore['productMenu'].response.array.length)
        {
            if (stockMethod != '0' && deliverMethod != '0' ) { //stock and deliver selected
                if (deliveryArray[y] == deliverMethod & baseProduct == ec.jsonDataStore['productMenu'].response.array[y].product & stockMethod == ec.jsonDataStore['productMenu'].response.array[y].stock) {
                    colorArray[colorIndex] = ec.jsonDataStore['productMenu'].response.array[y].color;
                    colorName[colorIndex] = ec.jsonDataStore['productMenu'].response.array[y].colorName;
                    colorIndex ++;
                }
            } else if (stockMethod == '0' && deliverMethod != '0') { //only deliver selected
                if (deliveryArray[y] == deliverMethod & baseProduct == ec.jsonDataStore['productMenu'].response.array[y].product) {
                    colorArray[colorIndex] = ec.jsonDataStore['productMenu'].response.array[y].color;
                    colorName[colorIndex] = ec.jsonDataStore['productMenu'].response.array[y].colorName;
                    colorIndex ++;
                }
            } else if (stockMethod != '0' && deliverMethod == '0' ) { //only stock selected
                if (stockMethod == ec.jsonDataStore['productMenu'].response.array[y].stock & baseProduct == ec.jsonDataStore['productMenu'].response.array[y].product) {
                    colorArray[colorIndex] = ec.jsonDataStore['productMenu'].response.array[y].color;
                    colorName[colorIndex] = ec.jsonDataStore['productMenu'].response.array[y].colorName;
                    colorIndex ++;
                }
            } else if (stockMethod == '0' && deliverMethod == '0' ) { //neither stock nor deliver selected
                if (baseProduct == ec.jsonDataStore['productMenu'].response.array[y].product) {
                    colorArray[colorIndex] = ec.jsonDataStore['productMenu'].response.array[y].color;
                    colorName[colorIndex] = ec.jsonDataStore['productMenu'].response.array[y].colorName;
                    colorIndex ++;
                }
            }
            y ++;
        }

        tempMenu = '<div id="pricing-sides"><label for="colorMenu">Sides:</label><select tabindex="5" id="ccc" name="colorMenu" onChange="{ec.pricing.showQuantity();}"></div>';
        options = buildMenu(colorArray, colorName, colorMethod);
        placeHolder.innerHTML = tempMenu + options + '</select>';

        ec.pricing.showResult();
        jQuery('#pricing-sides').fadeIn(500);
    },

    showQuantity: function() {
        var quantityBox = document.getElementById("qty");
        quantityBox.className = "pricing";
        ec.pricing.checkSelected();
        ec.pricing.stockMenu();

        if (quantityVal > 0) {
            qtyVal = quantityVal;
        } else {
            qtyVal = '';
        }
        quantityBox.innerHTML = '<div id="pricing-quantity"><label for="inputNumber">Quantity:</label> <input tabindex="6" id="inputNumber" type="text" size="10" name="inputNumber" value="' + qtyVal  + '" onchange="ec.pricing._cleanQuantity(true)" /><div id="pricingUpdateButton" onclick="ec.run(\'getEstimate\', \'ec.pricing\');"></div></div>';
         
        if (deliverMethod == 0 || stockMethod == 0 || colorMethod == 0 || baseProduct == 0) {
            var placeHolder = document.getElementById('estimate');
            var minMessage = document.getElementById('minQuantity');
            minMessage.innerHTML = '';
            placeHolder.innerHTML = '';
        } else if (deliverMethod != 0 && stockMethod != 0 && colorMethod != 0 && baseProduct != 0) {
            ec.pricing.getEstimate();
        }
        jQuery('#quantityContainer').fadeIn(500);
    },

    binderyMenu: function() {
        if (!inputQuantity) return false;
        jsonBindery = ec.jsonDataStore['pricingEstimate'].response.bindery;
        if (!jsonBindery.array) return false;

        var placeHolder = document.getElementById('binderyService');
        placeHolder.className = "pricing";
        var binderyLength = jsonBindery.array.length;

        var binderyType = new Array();
        i = 0;
        while (i < binderyLength) {
            binderyType[i] = jsonBindery.array[i].binderyType;
            i++;
        }
        uniqueTypes = unique(binderyType);

        var dependentBinderyId = new Array();
        var dependentBinderyType = new Array();
        var dependentBinderyName = new Array();
        var dependentMessage = new Array();
        var binderyMethod = [0,0,0,0];
        var bindMenu = '<div id="pricing-bindery">';
        var eachMenu = new Array();
        var index = '';

        k = 0;
        while (k < uniqueTypes.length) {

            binderyMethod[k] = ec.pricing.binValues[k];

            var j = 0;
            var binderyName = new Array();
            var binderyId = new Array();
            var m = 0;

            for (var i = 0; i < binderyLength; ++i) {

                if (uniqueTypes[k] == jsonBindery.array[i].binderyType) {

                    binderyName[j] = jsonBindery.array[i].binderyName;
                    binderyId[j] = jsonBindery.array[i].binderyId;

                    //have dependent hit
                    if (binderyMethod[k] != 0 && binderyMethod[k] == binderyId[j] && jsonBindery.array[i].dependentBinderyId != 0) {
                        dependentBinderyId[m]   = jsonBindery.array[i].dependentBinderyId;
                        dependentBinderyName[m] = jsonBindery.array[i].dependentBinderyName;
                        dependentBinderyType[m] = jsonBindery.array[i].dependentBinderyType;
                        dependentMessage[m]     = '<div id="pricingBinderyDependencyMessage">If ' + binderyName[j] + ' is selected, ' + dependentBinderyName[m] + ' is required.</div>';

                        //calculate out the k index
                        for (x=0; x<uniqueTypes.length; ++x) {
                            if (dependentBinderyType[m] == uniqueTypes[x]) {
                                index = x;
                                break;
                            }
                        }

                        //rebuild option which contains the dependent id
                        var p=0;
                        var requiredBinderyName = new Array();
                        var requiredBinderyId = new Array();

                        for (var q=0; q < binderyLength; ++q) {
                            if (jsonBindery.array[q].binderyType == dependentBinderyType[m]) {
                                requiredBinderyName[p] = jsonBindery.array[q].binderyName;
                                requiredBinderyId[p] = jsonBindery.array[q].binderyId;
                                p++;
                            }
                        }
                        eachMenu[index] = buildMenu(requiredBinderyId, requiredBinderyName, dependentBinderyId[m]);
                        m++;
                    } //end dependency check

                    j++;
                }
            }

            //if bindery option menus not existiing, build it
            if (typeof(eachMenu[k]) == 'undefined') {
                eachMenu[k] = buildMenu(binderyId, binderyName, ec.pricing.binValues[k]);
            }

            k++;

        }

        var i = 0;
        while (i < uniqueTypes.length) {
            temp1 = '<label for="binderyService">' + uniqueTypes[i] + ':</label>' + ' <select tabindex="'+ (i + 7) + '" id="bindery_' + i + '" onChange="{ec.pricing.getEstimate();}">';
            temp2 = temp1 + eachMenu[i] + '</select>';
            bindMenu += temp2;
            i++;
        }
        placeHolder.innerHTML = bindMenu + dependentMessage + '</div>';
        jQuery('#pricing-bindery').show();
    },

    findProductId: function(productPrintId, mailOption, stockOption, colorOptionId, printOptionId) {
        jsonProduct = ec.jsonDataStore['productMenu'].response;

        var i = 0;
        while (i < jsonProduct.array.length) {
            if (productPrintId == jsonProduct.array[i].product && mailOption == jsonProduct.array[i].mailing && stockOption == jsonProduct.array[i].stock && colorOptionId == jsonProduct.array[i].color && printOptionId == jsonProduct.array[i].print) {
                productId = ec.jsonDataStore['productMenu'].response.array[i].id;
            }
            i++;
        }
        return productId;
    },

    getEstimate: function() {
        productPrintId = jQuery('#ppp').val();
        deliver = jQuery('#aaa').val().split("");
        mailOption = deliver[0];
        stockOption = jQuery('#bbb').val();
        colorOptionId = jQuery('#ccc').val();
        printOptionId = deliver[1];

        // last check before the api call
        if (document.getElementById('inputNumber') != 'NULL') {
            inputQuantity = document.getElementById('inputNumber').value;
        } else {
            inputQuantity = 0;
        }

        // since deliver is concantanated by mail and print option
        if (mailOption == 0) {
            printOptionId = 0;
        }

        // bindery values
        var binValues = [0,0,0,0];

        binValues[0] = jQuery('#bindery_0').val(); // folding
        binValues[1] = jQuery('#bindery_1').val(); // scoring
        binValues[2] = jQuery('#bindery_2').val(); // glue sealing
        binValues[3] = jQuery('#bindery_3').val(); // perforation

        ec.pricing.binValues = binValues;

        if (productPrintId != 0 && mailOption != 0 && stockOption != 0 && colorOptionId != 0 && printOptionId != 0) {

            //find product id
            productId = ec.pricing.findProductId(productPrintId, mailOption, stockOption, colorOptionId, printOptionId);

            var parameters = {};
            var binderyArray = {};

            parameters.binderyArray = binValues;
            parameters.siteId = ec.config.siteId;
            parameters.productId = productId;
            parameters.quantity = inputQuantity;

            var callback = "ec.pricing._addEstimate";
            var id = 'selectionsApiScript';
            ec._callApi('product/price', parameters, callback);
            jQuery('#binderyService').html('');
        } else {
            var placeHolder = document.getElementById('estimate');
            var minMessage = document.getElementById('minQuantity');
            minMessage.innerHTML = '';
            placeHolder.innerHTML = '';
            jQuery('#binderyService').html('');
        }
    },
    _addMenu: function(json) {

        ec.jsonDataStore['productMenu'] = json;
        if (ec.config.format == 'html') {
            ec.pricing._formatProductMenu(json);
        }
    },
    _addEstimate: function(json) {
        ec.jsonDataStore['pricingEstimate'] = json;
        if (ec.config.format == 'html') {
            ec.pricing._formatEstimate(json);
        }
    },
    _formatEstimate: function(json) {
        var placeHolder = document.getElementById('estimate');
        placeHolder.className = "pricing";
        var minMessage = document.getElementById('minQuantity');
        minMessage.className = "pricing";

        if (json.response.bindery) {
            ec.pricing.binderyMenu();
        } else {
            json.response.totalBinderyPrice = 0;
        }
        
        if (deliverMethod == 0 || stockMethod == 0 || colorMethod == 0 || baseProduct == 0) {
            jQuery('#inputNumber,#minQuantity').removeClass('pricingQuantityProblem');
            minMessage.innerHTML = '';
            placeHolder.innerHTML = '';
        } else if (inputQuantity == '') {
            jQuery('#inputNumber,#minQuantity').removeClass('pricingQuantityProblem');
            minMessage.innerHTML = json.response.minQty + ' is the minimum quantity for the options selected.';
            placeHolder.innerHTML = '';
        } else if (inputQuantity != '' && inputQuantity < Number(json.response.minQty)) { //check if it's below the min quantity
            jQuery('#inputNumber,#minQuantity').addClass('pricingQuantityProblem');
            minMessage.innerHTML = json.response.minQty + ' is the minimum quantity for the options selected. Please enter a higher quantity.';
            placeHolder.innerHTML = '';
        } else {
            jQuery('#inputNumber,#minQuantity').removeClass('pricingQuantityProblem');
            ec.pricing.getShipping();
            if (json.response.price > 0 ) {
                placeHolder.innerHTML = '';
                minMessage.innerHTML = json.response.minQty + ' is the minimum quantity for the options selected.';
                if (json.response.totalBinderyPrice > 0) {
                    placeHolder.innerHTML += '<div id="pricing-bindery-price">Bindery price is: $' + json.response.totalBinderyPrice + '</div>';
                }

                placeHolder.innerHTML += '<div id="ourLowPrice">'
                + '<div id="pricing-quote-label">Our Low Price:</div> <div id="pricing-quote-price">$' + json.response.price + ' ($' + json.response.unitPrice + ' ea.)</div>'
                + '</div>';
                
                if (json.response.postageUnitPrice != '0.000') {
                    quantity = document.getElementById('inputNumber').value;
                    printUnitPrice = json.response.unitPrice - json.response.postageUnitPrice;
                    placeHolder.innerHTML += '<div id="unitPricingBreakout">'
                    + '<div id="pricing-printing-price">Printing: $' + (printUnitPrice.toFixed(3) * quantity).toFixed(2) + ' ($' + printUnitPrice.toFixed(3) + ' ea.)</div>'
                    + '<div id="pricing-postage-price">Postage: $' + (json.response.postageUnitPrice * quantity).toFixed(2) + ' ($' + json.response.postageUnitPrice + ' ea.)</div>'
                    + '</div>';
                }

                if (document.getElementById('zipCode')) {
                    window.zipCode = jQuery('#zipCode').val();
                } else {
                    window.zipCode = '';
                }
                
                if (json.response.nextPriceBreak != '') {
                    var nextPriceBreak = document.getElementById('nextPriceBreak');
                    nextPriceBreak.innerHTML  = "Next price break at "
                    nextPriceBreak.innerHTML += '<a tabindex="12" onclick="ec.pricing.updateQuantity(' + json.response.nextPriceBreak + ');">' + json.response.nextPriceBreak + '</a>';
                } else {
                    var nextPriceBreak = document.getElementById('nextPriceBreak');
                    nextPriceBreak.innerHTML = "Please call us at 800-260-5887 for large volume pricing.";
                }
            } else {
                placeHolder.innerHTML += 'Selected product combination not found.';
            }
        }
        document.getElementById('shipping').innerHTML = '';
    },
    getShipping: function() {
        if (document.getElementById('zipCode')) {
            window.zipCode = jQuery('#zipCode').val();
        } else {
            window.zipCode = '';
        }
        productPrintId = jQuery('#ppp').val();
        deliver = jQuery('#aaa').val().split("");
        mailOption = deliver[0];
        stockOption = jQuery('#bbb').val();
        colorOptionId = jQuery('#ccc').val();
        printOptionId = deliver[1];

        // last check before the api call
        if (document.getElementById('inputNumber') != 'NULL') {
            inputQuantity = document.getElementById('inputNumber').value;
        } else {
            inputQuantity = 0;
        }

        // since deliver is concantanated by mail and print option
        if (mailOption == 0) {
            printOptionId = 0;
        }

        if (productPrintId != 0 && mailOption != 0 && stockOption != 0 && colorOptionId != 0 && printOptionId != 0) {
            //find product id
            productId = ec.pricing.findProductId(productPrintId, mailOption, stockOption, colorOptionId, printOptionId);
            var parameters = {};

            parameters.siteId = ec.config.siteId;
            parameters.productId = productId;
            parameters.quantity = inputQuantity;
            parameters.postalCode = zipCode;
            
            var callback = "ec.pricing._addShipping";
            var id = 'selectionsApiScript';
            ec._callApi('product/shippingDefault', parameters, callback);
            ec._callApi('product/shipping', parameters, callback);
        } else {
            var shippingMessage = document.getElementById('shipping');
            shippingMessage.innerHTML = '';
        }
    },
    autoAdvanceAll: function() {
        var deliverMethodSelect = document.getElementById('aaa');
        if (deliverMethodSelect) {
            if (deliverMethodSelect.options.length == 2) {
                deliverMethodSelect.options[1].selected = true;
                ec.pricing.stockMenu();
            }
        }
        
        var stockTypeSelect = document.getElementById('bbb');
        if (stockTypeSelect) {
            if (stockTypeSelect.options.length == 2) {
                stockTypeSelect.options[1].selected = true;
                ec.pricing.colorMenu();
            }
        }
        
        var printedSidesSelect = document.getElementById('ccc');
        if (printedSidesSelect) {
            if (printedSidesSelect.options.length == 2) {
                printedSidesSelect.options[1].selected = true;
                ec.pricing.showQuantity();
            }
        }
        
        var productTypeSelect = document.getElementById('ppp');
        if (productTypeSelect) {
            if (productTypeSelect.options.length == 2 && !productTypeSelect.options[1].selected) {
                productTypeSelect.options[1].selected = true;
                ec.pricing.showSection();
            }
        }
        
        ec.pricing._updateCSS();
    },
    updateQuantity: function(quantity) {
        jQuery('#inputNumber').val(quantity);
        ec.run('getEstimate', 'ec.pricing');
    },
    startMyOrder: function() {
        productPrintId = jQuery('#ppp').val();
        deliver = jQuery('#aaa').val().split("");
        mailOption = deliver[0];
        stockOption = jQuery('#bbb').val();
        colorOptionId = jQuery('#ccc').val();
        printOptionId = deliver[1];
        inputQuantity = jQuery('#inputNumber').val();
        
        var callback = function() {
            if (window.startMyOrderTarget) {
                window.location = window.startMyOrderTarget + '/productFilter/' + productPrintId;
            } else {
                window.location = '/create-a-postcard';
            }
            
        };

        if (productPrintId != 0 && mailOption != 0 && stockOption != 0 && colorOptionId != 0 && printOptionId != 0) {
            //find product id
            productId = ec.pricing.findProductId(productPrintId, mailOption, stockOption, colorOptionId, printOptionId);
            var parameters = {};
            parameters.productId = productId;
            parameters.productPrintId = productPrintId;
            parameters.mailingOptionId = mailOption;
            parameters.stockOptionId = stockOption;
            parameters.colorOptionId = colorOptionId;
            parameters.printOptionId = printOptionId;
            parameters.quantity = inputQuantity;
            if (window.shippingOptionId) parameters.shippingOptionId = window.shippingOptionId;
            // save selection to session
            $$post('/ec/index/pricing', null, callback, parameters);
        } else {
            callback();
        }
    },
    _addShipping: function(json) {
        ec.jsonDataStore['shipping'] = json;
        if (ec.config.format == 'html') {
            ec.pricing._formatShipping(json);
        }
    },
    _cleanQuantity: function(getEstimate) {
        try {
            var quantity = jQuery('#inputNumber');
            var cleanZipcode = quantity.val();
            cleanQuantity = cleanZipcode.replace(/\D/g, '');
            quantity.val(cleanQuantity);
            
            if (getEstimate) ec.pricing.getEstimate();
        } catch (e) {
            if (!window.errors) window.errors = new Array;
            window.errors.push(e);
        }
    },
    _cleanZipcode: function(getEstimate) {
        try {
            var zipcode = jQuery('#zipCode');
            var cleanZipcode = zipcode.val();
            cleanZipcode = cleanZipcode.replace(/\D/g, '');
            cleanZipcode = cleanZipcode.substr(0,5);
            zipcode.val(cleanZipcode);
            window.zipCode = cleanZipcode;
            if (getEstimate) ec.pricing.getEstimate();
        } catch (e) {
            if (!window.errors) window.errors = new Array;
            window.errors.push(e);
        }
    },
    _formatShipping: function(json) {
        if (json.response && json.response.array) {
            var shippingMessage = document.getElementById('shipping');
            shippingMessage.className = "pricing";
            shippingMessage.innerHTML = '';
            var shippingSelectionMenu = document.createElement('div');
            shippingSelectionMenu.innerHTML = '';
            shippingSelectionMenu.id = 'shippingSelectionMenu';
            for (var i = 0; i < json.response.array.length; ++i) {
                if (json.response.array[i].price > 0) {
                    var inputHtml = '<div class="pricing-shipping-option"><input type="radio" name="shippingOption" value="' + json.response.array[i].id + '" onclick="ec.pricing.setShipping(' + json.response.array[i].id + ');"';
                    if (window.shippingOptionId == json.response.array[i].id || !window.shippingOptionId && 0 == i) {
                        if (!window.shippingOptionId) window.shippingOptionId = json.response.array[i].id;
                        shippingMessage.innerHTML = json.response.array[i].description + ': $' + json.response.array[i].price;
                        // No zip code -- tack on message to indicate shipping is an estimate.
                        if (!window.zipCode) shippingMessage.innerHTML += '<div id="pricing-change-shipping-estimate-text"> (Shipping estimate. Enter zip code for more accuracy.)</div>';
                        inputHtml += 'checked="checked"';
                    }
                    inputHtml += ' /> ' + json.response.array[i].description + ': $' + json.response.array[i].price + '</div>';
                    shippingSelectionMenu.innerHTML += inputHtml;
                }
            }
            if (shippingSelectionMenu.innerHTML == '') {
                shippingMessage.innerHTML = 'Shipping Prices Not Found.';
            } else {
                shippingMessage.innerHTML += '<a tabindex="11" id="pricing-change-shipping" onclick="ec.pricing.showShippingSelection()"> Change</a>';
            }
            shippingMessage.appendChild(shippingSelectionMenu);
        }
    },
    setShipping: function(id) {
        ec.pricing.hideShippingSelection();
        window.shippingOptionId = id;
        setTimeout(function(){
            ec.pricing._formatShipping(ec.jsonDataStore['shipping'])
            }, 400);
    },
    showShippingSelection: function() {
        jQuery('#shippingSelectionMenu').slideToggle();
    },
    hideShippingSelection: function() {
        jQuery('#shippingSelectionMenu').slideToggle();
    },
    _formatProductMenu: function(json) {
        var placeHolder = document.getElementById('mailingSelections');
        placeHolder.className = "pricing";
        deliveryArray = new Array();
        deliverName = new Array();
        //construct deliver method arrays, hold them in global variables
        for (var z = 0; z < ec.jsonDataStore['productMenu'].response.array.length; ++z) {
            window.deliveryArray[z] = ec.jsonDataStore['productMenu'].response.array[z].mailing + ec.jsonDataStore['productMenu'].response.array[z].print;
            window.deliverName[z] = ec.jsonDataStore['productMenu'].response.array[z].printName + '+' + ec.jsonDataStore['productMenu'].response.array[z].mailingName;
        }
        ec.pricing.deliverMenu();
        // auto advance
        ec.pricing.autoAdvanceAll();
    },
    _formatProductPrintMenu: function(json) {
        var placeHolder = document.getElementById('itemTypes');
        var html = '<div id="pricing-product"><label for="orderType">Product:</label>';
        html += '<select tabindex="1" id="ppp" name="orderType" onchange="ec.run(\'showSection\', \'ec.pricing\');">';
        html += '<option>Please Make a Selection</option>';
        for (var z = 0; z < json.response.array.length; z++) {
            if (json.response.array[z]) {
                html += '<option value="' + json.response.array[z].id + '">' + json.response.array[z].name + '</option>';
            }
        }
        html += '</select></div>';
        placeHolder.innerHTML = html;
        // auto advance
        ec.pricing.autoAdvanceAll();
        jQuery('#pricing-product').fadeIn(500);
    },
    _updateCSS: function() {
        try {
            var pricingContainer = jQuery('#formPricing');
            var deliver = jQuery('#aaa');
            // Check for various things to determine what to do with the styling of the price calculator.
            if (deliver.length > 0) {
                // Reset to standard styling.
                pricingContainer.removeClass('pricing-form-initial');
                pricingContainer.addClass('pricing-form-product-selected');
            }
        } catch (e) {
            if (!window.errors) window.errors = new Array;
            window.errors.push(e);
        }
    }
}
function unique(arrayName)
{
    var newArray = new Array();
        label:for (var i=0; i<arrayName.length;i++ )
        {
            for (var j=0; j<newArray.length;j++ )
            {
                if (newArray[j]==arrayName[i]) {
                    continue label;
                }
            }
            newArray[newArray.length] = arrayName[i];
        }
    return newArray;
}

function buildMenu(arrayValue,arrayOption, selectedVal)
{

    var optionValue = unique(arrayValue);
    var optionName = unique(arrayOption);
    var addSelected = '';
    i = 0;

    var option = '<option value="0">Please make a selection</option>';

    while ( i < optionName.length) {

        if (optionValue[i] == selectedVal) {
            addSelected = 'selected';
        } else {
            addSelected = '';
        }

        option += '<option value = ' + optionValue[i] + ' ' + addSelected + '>' + optionName[i] + '</option>';
        i++;
    }
    return option;
}
ec.pricing = _pricing;
_pricing = '';
/**
 * @file components/local/accountAdmin.js
 */
var _accountAdmin = {
    addDiscount: function()
    {
        $$post(
            '/ec/account-admin/add-discount',
            null,
            function()
            {
                ec._modal.close();
                $byId('message').style.display = 'block';
                $byId('message').innerHTML = 'Code created.';
                setTimeout(function(){$byId('message').style.display='none';}, 3000);
            },
            ec.utility.form.serialize($byId('addDiscount'))
        );
    },
    removeDiscount: function(discountId, accountId, userId)
    {
        var parameters = {};
        parameters.discountId = discountId;
        parameters.accountId = accountId;
        parameters.userId = userId;
        $$post(
            '/ec/account-admin/remove-discount',
            'bodyDiv',
            null,
            parameters
        );
    },
    editInfo: function()
    {
        if (confirm('Are you sure all changes are correct?')) {
            ec._dom.onLoad('saveMessage', 'Updating ...');
            $$post(
                '/ec/account-admin/edit-info',
                'bodyDiv',
                null,
                ec.utility.form.serialize($byId('editInfo'))
            );
        }
    },
    searchUsers: function()
    {
        ec._dom.onLoad('results', 'Searching ...');
        $$post(
            '/ec/account-admin/search-users',
            'adminContent',
            null,
            ec.utility.form.serialize($byId('searchAccount'))
        );
    },
    userMenuAction: function(e, userId, accountId)
    {
        ec._modal.width = '525px';
        if (e.value.length > 0) {
            var url = '/ec/account-admin/' + e.value;
            if (userId && accountId) {
                url += '?userId=' + userId + '&accountId=' + accountId;
            } else {
                if (userId) {
                    url += '?userId=' + userId;
                }
                if (accountId) {
                    url += '?accountId=' + accountId;
                }
            }
            $$modal(url);
            e.value = '';
        }
    },
    report: {
        run: function(formId)
        {
            ec._dom.onLoad('report', 'Running report ...');
            var form = $byId(formId);
            if (form) {
                $$post(
                    '/ec/account-admin/reports',
                    'adminContent',
                    null,
                    ec.utility.form.serialize($byId(formId)) + '&runReport=1'
                );
            } else {
                window.location='/ec/account-admin';
            }
        }
    }
};

ec.__accountAdmin = _accountAdmin;
_accountAdmin = {};
/**
 * @file components/local/account.js
 */
var _account = {
    saveContactInformation: function(){
        var form = $byId('contactForm');
        if (form) {
            var parameters = ec._utility.form.serialize(form);
            $$post('/ec/user/contact-information', 'bodyDiv', function(){if($byId('isDone').value){ec.__account.refreshContactInformation();ec._modal.close();}}, parameters);
        }
    },
    refreshContactInformation: function(){
        if ($byId('accountInformation')) {
            $$get('/ec/user', 'accountInformation');
        }
    },
    saveUserEmail: function(form){
        var parameters = ec._utility.form.serialize(form);
        $$post('/ec/user/email', 'modalDiv', function(){ec.__account.closeModal();}, parameters);
    },
    resetPassword: function(form){
        var parameters = ec._utility.form.serialize(form);
        $$post('/ec/user/reset-password', 'modalDiv', function(){ec.__account.closeModal();}, parameters);
    },
    submit:function(form, url){
        var parameters = ec._utility.form.serialize(form);
        $$post(url, 'modalDiv', function(){ec.__account.closeModal();}, parameters);
    },
    closeModal: function(){
        if($byId('isDone').value) {
            modalWindow.close();
        }
    },
    cancelOrder: function(id, div) {
        var confirmed = confirm('Are you sure you want to cancel this order?');
        if(confirmed){
           var parameters = {'id': id};
           callback = function(){
               $$get('/ec/order-history/scheduled/div/' + div, div);
           };
           $$post('/ec/order/remove-scheduled-item', null, callback, parameters);
        }
    }
}

ec.__account = _account;
_account = '';
/**
 * @file components/local/addressList.js
 */
var _addressList = {

    open: function(){
        var uploadAddressListDiv = document.createElement('div');
        uploadAddressListDiv.setAttribute('id', 'uploadAddressListDiv');
        uploadAddressListDiv.style.width = '400px';
        uploadAddressListDiv.style.zIndex  = '2000';
        uploadAddressListDiv.style.height = '200px';
        uploadAddressListDiv.style.position = "absolute"
        uploadAddressListDiv.style.backgroundColor = "white"
        document.body.appendChild(uploadAddressListDiv);
        adjustCenteredElement(uploadAddressListDiv);

        ec._ajax.getHtml('/ec/upload/upload/type/address', uploadAddressListDiv, null);

        var options = {};
        modalWindow.show(uploadAddressListDiv, options);
    },
    close: function(){
        modalWindow.close('uploadAddressListDiv');
    },
    changeCount: function(id, newCount) {
        $$post('/ec/address-list/change-count/', 
                'addressLists',
                null,
                {'id': id, 'count': newCount}
        );
    },
    rename: function(id,addressListName){
    ec._ajax.getHtml('/ec/address-list/rename/id/' + 
        id + '/name/' + addressListName +
        '/forward/manage',
        $byId('addressLists'));
    },
    setSendListLater: function(sendListLaterEmail, count){
        $$post('/ec/address-list/set-send-list-later/',
            'addressLists',
            null,
            {'sendListLaterEmail': sendListLaterEmail, 'count': count}
        );
        ec._modal.close();
    },
    unsetSendListLater: function(){
        $$post('/ec/address-list/unset-send-list-later/',
            'addressLists'
        );
    }
}

function deleteAddressList(id) {
    var response = confirm("Delete this list?");
    if (response){
        ec._ajax.getHtml('/ec/address-list/delete/id/' + id, $byId('addressLists'));
    } else{

    }
}
 
ec.__addressList = _addressList;
_addressList = {};
/**
 * @file components/local/checkout.js
 */
var _checkout = {
    current:
    {
        bootData: [],
        paymentSource: 'creditCard',
        paymentType: 'saved',
        shippingOptionId: '1'
    },
    boot: function (parameters)
    {
        if (!parameters) {
            parameters = ec.__checkout.current.bootData;
        } else {
            ec.__checkout.current.bootData = parameters;
        }
        var newPaymentElements = [
            'number',
            'date_expires_month',
            'date_expires_year',
            'name',
            'line1',
            'line2',
            'city',
            'state',
            'zip'];
        
        if ($byId('number')) {
            for (var x = 0; x < newPaymentElements.length; x++) {
                $byId(newPaymentElements[x]).onchange = function() {
                    ec.__checkout.current.paymentType = 'new';
                };
            }
        }
        
        
        var accountPaymentHeader = $byId('accountPaymentHeader');
        if (accountPaymentHeader) {
            accountPaymentHeader.onclick = function() {
                ec.__checkout._handlePaymentSourceSelection('account');
            }
        }
        if (parameters.paymentSource) {
            ec.__checkout._handlePaymentSourceSelection(parameters.paymentSource);
        }
        if (parameters.paymentType) {
            ec.__checkout.paymentType = parameters.paymentType;
        }
        var shippingOptionForm = $byId('shippingOptionForm');
        if (shippingOptionForm != null) {
            for(i=0; i < shippingOptionForm.elements.length; i++) {
                if(shippingOptionForm.elements[i].checked) {
    	    		ec.__checkout.current.shippingOptionId = shippingOptionForm.elements[i].value;
    		    }
    		}
        }
    },
    open: function()
    {
        var savedAccountAddressDiv = document.createElement('div');
        savedAccountAddressDiv.setAttribute('id', 'savedAccountAddressDiv');
        savedAccountAddressDiv.style.width = '400px';
        savedAccountAddressDiv.style.zIndex  = '2000';
        savedAccountAddressDiv.style.height = '400px';
        savedAccountAddressDiv.style.position = "absolute";
        savedAccountAddressDiv.style.backgroundColor = "white";
        document.body.appendChild(savedAccountAddressDiv);
        adjustCenteredElement(savedAccountAddressDiv);

        $$post('/ec/checkout/account-address/', savedAccountAddressDiv, null);

        var options = {};
        modalWindow.show(savedAccountAddressDiv, options);
    },
    close: function()
    {
        ec._modal.close();
    },
    show: function(elementId, callingElement)
    {
        ec.utility.element.show(elementId);
        callingElement.innerHTML = "hide";
        callingElement.onclick = function() {
            ec.__checkout.hide(elementId, callingElement);
        };
    },
    hide: function(elementId, callingElement)
    {
        ec.utility.element.hide(elementId);
        callingElement.innerHTML = "change";
        callingElement.onclick = function(){
            ec.__checkout.show(elementId, callingElement);
        };
    },
    addContactInformation: function(form)
    {
        $$post('/ec/contact/set', null, null, ec.utility.form.serialize(form));
    },
    addShippingAddressToInvoice: function(addressId, callback)
    {
        var parameters = {
            addressId: addressId
        };

        $$post(
            '/ec/checkout/shipping',
            'shippingInformation',
            function() {
                $$get(
                    '/ec/checkout/shipping-option',
                    'shippingContainer',
                    function(){ec._modal.close();ec.__checkout.refreshInvoiceTotal();}
                );
            },
            parameters
        );
    },
    setShippingOption: function()
    {
        var optionId = 1;
        var shippingOptionForm = $byId('shippingOptionForm');
        for(i=0; i < shippingOptionForm.elements.length; i++) {
            if(shippingOptionForm.elements[i].checked) {
    			optionId = shippingOptionForm.elements[i].value;
    		}
		}

        if ($byId('shippingOptionSelected') !== null && 1 == $byId('shippingOptionSelected').value && ec.__checkout.current.shippingOptionId == optionId) {
            return false;
        }

        $byId("invoiceTotal").innerHTML = '<strong>Total: </strong>Loading...';

        ec.__checkout.current.shippingOptionId = optionId;
        
        var parameters = {
            postalCode: $byId('shipping_zip').value,
            shippingOptionId: optionId
        }
        
        $$post(
            '/ec/checkout/shipping-option',
            'shippingContainer',
            function() {$$get('/ec/order/promotion', 'promotionContainer', function(){ec.__checkout.refreshInvoiceTotal()})},
            parameters
        );
    },
    checkBankcard: function(callback)
    {
        if (typeof(callback) == 'function' && $byId('isDone')) {
            $byId('checkoutMessage').innerHTML += "Authorizing card...";
            $byId('isDone').id = 'isDoneOld';
            callback();
        } else {
            // Error with bankcard.
            $byId('checkoutMessage').innerHTML = "Error Found";
            $byId('number').focus();
            ec._modal.close();
        } 
    },
    checkout: function()
    {
        var errorMessage = '';
        var valstreet_address = new RegExp("[pP]{1}[.]*[oO]{1}[.]*[ ]*[bB]{1}[oO]{1}[xX]{1}");
        if ($byId('shippingInformation').style.display != 'none' && $byId("shipping_line1").value.match(valstreet_address) != null) {
            errorMessage += "A P.O. Box is not allowed for the Shipping Address. \n\n";
        }

        if ($byId('shippingOptionSelected') !== null && 0 == $byId('shippingOptionSelected').value) {
            try {
                document.forms['shippingOptionForm'].elements[1].focus();
            } catch (error) {}
            alert("Please select a shipping method.");
            try {
                ec.__ga.trackEvent('checkoutValidationFailed');
            } catch (e) {
                if (!window.errors) window.errors = new Array;
                window.errors.push(e);
            }
            return false;
        }

        if (errorMessage) {
            try {
                $byId("shipping_line1").focus();
            } catch (error) {}
            alert(errorMessage);
            if (ec.getBrowser() == "IE7" || ec.getBrowser() == "IE6") {
              $byId('updateAddress').onclick();
            } else {
              $byId('updateAddress').click();
            }
            try {
                ec.__ga.trackEvent('checkoutValidationFailed');
            } catch (e) {
                if (!window.errors) window.errors = new Array;
                window.errors.push(e);
            }
            return false;
        }

        if (!$byId('agreeToTerms').checked) {
            alert('Please read and agree to the terms and conditions.');
            try {
                ec.__ga.trackEvent('checkoutValidationFailed');
            } catch (e) {
                if (!window.errors) window.errors = new Array;
                window.errors.push(e);
            }
            $byId('agreeToTerms').focus();
            return false;
        }
        
        var creditCardForm = $byId('creditCardForm');
        
        var checkoutCallback = function(){
            if($byId('isDone')) {
                window.location = '/ec/checkout/complete';
            } else {
                ec._dom.onLoad('paymentContainer', ' Processing payment...');
                $$get('/ec/payment', 'paymentContainer', function(){
                    try {
                        ec.__checkout._loadPaymentOptions($byId('creditCardForm'));
                    } catch (e) {}
                });
                ec._modal.close();
            }
        }
        
        var refreshCheckoutCallback = function(){
            if($byId('isDone')) {
                window.location = '/ec/checkout/complete';
            } else {
                $$get('/ec/payment', 'paymentContainer', function(){
                    try {
                        ec.__checkout._loadPaymentOptions($byId('creditCardForm'));
                    } catch (e) {}
                });
                ec._modal.close();
            }
        }
        
        var contactInformationCallback = function(callback) {
            var shippingCallback = function() {
                $$submit('shippingForm', '/ec/checkout/shipping', 'shippingInformation', callback);
            }
            $$submit('contactInformationForm',
                     '/ec/checkout/contact-information',
                     'contactInformation',
                     shippingCallback);
        }
        
        var validateShippingAndContact = function() {
            $byId('checkoutMessage').innerHTML += "Verifying order contact and shipping information...";
            if (ec.getBrowser() == "IE7" || ec.getBrowser() == "IE6"){
                var shippingErrors = getElementsByClassNameForIE('errors', $byId('shippingForm'));
                var contactInformationErrors = getElementsByClassNameForIE('errors', $byId('contactInformationForm'));
            } else {
                var shippingErrors = $byId('shippingForm').getElementsByClassName('errors');
                var contactInformationErrors = $byId('contactInformationForm').getElementsByClassName('errors');
            }
            if (ec.__checkout.current.bootData.requiresShippingAddress === 1 && shippingErrors.length > 0) {
                $byId('checkoutMessage').innerHTML += "oops<br />";
                $byId('shippingAddressDisplay').innerHTML = '<b style="color: red;">Please provide a valid shipping address.</b>';
                try {
                    ec.__ga.trackEvent('checkoutValidationFailed');
                } catch (e) {
                    if (!window.errors) window.errors = new Array;
                    window.errors.push(e);
                }
                ec._modal.close();
                window.location.hash = 'shippingTop';
                return false;
            }
            if (contactInformationErrors.length > 0) {
                $byId('checkoutMessage').innerHTML += "oops<br />";
                try {
                    ec.__ga.trackEvent('checkoutValidationFailed');
                } catch (e) {
                    if (!window.errors) window.errors = new Array;
                    window.errors.push(e);
                }
                ec._modal.close();
                $byId('contact_name').focus();
                return false;
            }
            return true;
        }

        var newBankcardCallback = function() {
            var creditCardCallback = function(){
                ec.__checkout.checkBankcard(
                    function(){
                        $$submit('creditCardForm', '/ec/checkout/checkout', 'checkoutMessage', checkoutCallback);
                    }
                );
            };
            ec.__checkout._savePaymentOptions(creditCardForm);
            var parameters = ec.utility.form.serialize(creditCardForm);
            if ($byId('saveCard').checked) {
                parameters += '&saveCard=1';
            }
            parameters += '&paymentType=new';
            $byId('checkoutMessage').innerHTML += "Placing Order with Credit Card<br />";
            var callback = function() {
                if (validateShippingAndContact() == false) {
                    try {
                        ec.__ga.trackEvent('checkoutValidationFailed');
                    } catch (e) {
                        if (!window.errors) window.errors = new Array;
                        window.errors.push(e);
                    }
                    return false;
                }
                $byId('checkoutMessage').innerHTML += "OK<br />";
                $$post(
                    '/ec/payment/bankcard',
                    'paymentCreditCards',
                    creditCardCallback,
                    parameters
                );
            }
            contactInformationCallback(callback);
        };

        var accountCallback = function() {
            var accountFormCallback = function(){
                $$submit('accountForm', '/ec/checkout/checkout', 'checkoutMessage', refreshCheckoutCallback);
            };
            var parameters = {
                paymentSource: 'account',
                id: $byId('accountId').value,
                type: $byId('accountType').value
            };
            $byId('checkoutMessage').innerHTML += "Submitting Order Using Prepaid Account<br />";
            var callback = function() {
                if (validateShippingAndContact() == false) {
                    try {
                        ec.__ga.trackEvent('checkoutValidationFailed');
                    } catch (e) {
                        if (!window.errors) window.errors = new Array;
                        window.errors.push(e);
                    }
                    return false;
                }
                $byId('checkoutMessage').innerHTML += "OK<br />";
                $$post('/ec/payment/account', 'paymentContainer', accountFormCallback, parameters);
            }
            contactInformationCallback(callback);
        };
        
        var savedBankcardCallback = function() {
            $byId('checkoutMessage').innerHTML += "Verifying order contact and shipping information...";
            var callback = function() {
                if (validateShippingAndContact() == false) {
                    try {
                        ec.__ga.trackEvent('checkoutValidationFailed');
                    } catch (e) {
                        if (!window.errors) window.errors = new Array;
                        window.errors.push(e);
                    }
                    return false;
                }
                $byId('checkoutMessage').innerHTML += "OK<br />";
                $byId('checkoutMessage').innerHTML += "Placing Order with Saved Credit Card<br />";
                $byId('checkoutMessage').innerHTML += "Card Authorization...";
                $$submit('creditCardForm',
                         '/ec/checkout/checkout',
                         'checkoutMessage',
                         refreshCheckoutCallback);
            }
            contactInformationCallback(callback);
        };
        
        if ('account' == ec.__checkout.current.paymentSource) {
            modalCallback = accountCallback;
        } else {
            switch (ec.__checkout.current.paymentType) {
                case 'new':
                    modalCallback = newBankcardCallback;
                    break;
                case 'saved':
                    modalCallback = savedBankcardCallback;
                    break;
            }
        }
        
        ec._modal.closeButton = "disabled";
        ec._modal.height = "200px";
        ec._modal.callback = modalCallback;
        $$modal('/ec/checkout/payment');
                
        return true;
    },
    refreshInvoiceTotal: function(responseDiv)
    {
        $$get('/ec/order/invoice-total', 'invoiceTotalDiv', function(){$$get('/ec/order/small-cart', 'smallCart')});
    },
    refresh: function()
    {
        $$post('/ec/checkout/payment', 'paymentWrapper', function(){$$post('/ec/order/cart', 'cart', null);ec.__checkout.boot(ec.__checkout.current.bootData);});
    },
    submitForm: function(formId)
    {
        var form = $byId(formId);
        if (form) {
            form.submit();
        }
    },
    _handlePaymentSourceSelection: function(value)
    {
        switch(value) {
            case 'creditCard':
                var accountRadios = document.getElementsByClassName('accountRadio');
                for(var index in accountRadios){
                    accountRadios[index].checked = false;
                }
                break;
            case 'account':
                var ccRadios = document.getElementsByClassName('ccRadio');
                for(var index in ccRadios){
                    ccRadios[index].checked = false;
                }
                break;
            default:
                return false;
                break;
        }
        ec.__checkout.current.paymentSource = value;
        return true;
    },
    _loadPaymentOptions: function(form)
    {
        if ('object' != typeof ec.__checkout.cardholderInformation) {
            return false;
        }
        form.elements['name'].value = ec.__checkout.cardholderInformation.name;
        form.elements['line1'].value = ec.__checkout.cardholderInformation.line1;
        form.elements['line2'].value = ec.__checkout.cardholderInformation.line2;
        form.elements['city'].value = ec.__checkout.cardholderInformation.city;
        form.elements['state'].value = ec.__checkout.cardholderInformation.state;
        form.elements['zip'].value = ec.__checkout.cardholderInformation.zip;
    },
    _savePaymentOptions: function(form)
    {
        ec.__checkout.cardholderInformation = {};
        ec.__checkout.cardholderInformation.name = form.elements['name'].value
        ec.__checkout.cardholderInformation.line1 = form.elements['line1'].value
        ec.__checkout.cardholderInformation.line2 = form.elements['line2'].value
        ec.__checkout.cardholderInformation.city = form.elements['city'].value
        ec.__checkout.cardholderInformation.state = form.elements['state'].value
        ec.__checkout.cardholderInformation.zip = form.elements['zip'].value
    }
};

ec.__checkout = _checkout;
_checkout = {};
/**
 * @file components/local/designSelector.js
 */
var _designSelector =
{

    category:
    {
        nameForDisplay: '',
        parentCategoryId: 0,
        currentCategoryId: 0,
        currentDisplaySide: 'front'
    },

    page:
    {
        currentTab:'designs'
    },

    boot: function(json) {
        ec.design.current.bootData = json;
        if (json.apiKey) {
            ec.config.setApiKey(json.apiKey);
        }
        if (json.apiHost) {
            ec.config.setApiHost(json.apiHost);
        }
        if(json.categoryId) {
            if (json.categoryName) {
                ec.__designSelector.setNameForDisplay(json.categoryName);
            }
            ec.__designSelector.setParentCategoryId(json.categoryId);
            ec.__designSelector.setCurrentCategoryId(json.categoryId);
        } else {
            ec.__designSelector.setParentCategoryId(ec.design.current.defaultCategory);
            ec.__designSelector.setCurrentCategoryId(ec.design.current.defaultCategory);
        }
        
        if (json.subCategory && json.categoryId) {
            ec.__designSelector.setParentCategoryId(json.categoryId);
            ec.__designSelector.setCurrentCategoryId(json.subCategory);
        }
        
        if (json.productFilter) {
            ec.design.setProductFilter(json.productFilter);
            ec.design.reflectSelectedProduct(json.productFilter);
        }
        
        if (json.finished) {
            ec.design.setCurrentFinished(json.finished);
        }
        
        ec.design.getCategories();
        if (json.front) {
            ec.design.setCurrentFrontId(json.front.id);
            ec.design.setCurrentFrontType(json.front.type);
            ec.design.setCurrentFrontIntention(json.front.intention);
            ec.design.setCurrentFrontProductId(json.front.productId);
        }
        if (json.back) {
            ec.design.setCurrentBackId(json.back.id);
            ec.design.setCurrentBackType(json.back.type);
            ec.design.setCurrentBackIntention(json.back.intention);
            ec.design.setCurrentBackProductId(json.back.productId);
        }
        if (json.userId) {
            ec.design.setCurrentUserId(json.userId);
        }
        if (json.eztId) {
            ec.design.setCurrentEztId(json.eztId);
        }
        
        
        switch (json.change) {
            case 'front':
                if (typeof json.front == "object") {
                    if (null !== json.front.categoryId) {
                        ec.__designSelector.category.currentCategoryId = json.front.categoryId;
                    }
                }
                if (json.back) {
                    ec.design.setCurrentDisplaySide('back');
                    ec.__designSelector.setDesign(json.back.id, json.back.type, json.back.intention, '', json.back.productId,'none', false);
                } else {
                    ec.design.setCurrentDisplaySide('front');
                }
                break;

            case 'back':
                if (typeof json.back == "object") {
                    if (null !== json.back.categoryId) {
                        ec.__designSelector.category.currentCategoryId = json.back.categoryId;
                    }
                }
                if (json.front) {
                    ec.design.setCurrentDisplaySide('front');
                    ec.__designSelector.setDesign(json.front.id, json.front.type, json.front.intention, '', json.front.productId, 'none', false);
                } else {
                    ec.design.setCurrentDisplaySide('back');
                }
                break;

            default:
                break;
        }
        ec.design.getLibrary(ec.__designSelector.category.currentCategoryId);
        ec.__designSelector.displaySubCategories();
    },
    setCurrentOption: function(selection) {
        switch(selection) {
            case 'default':
                jQuery('#categorySelectDiv').fadeIn();
                break;
            case 'customizable':
                ec.__designSelector.setNameForDisplay("What's New");
                ec.__designSelector.switchLibrary('customizableDesigns');
                jQuery('#categorySelectDiv').fadeIn();
                break;
            case 'myDesigns':
                ec.__designSelector.setNameForDisplay('My Designs');
                ec.__designSelector.switchLibrary('myDesigns');
                jQuery('#categorySelectDiv').fadeOut();
                break;
        }
    },
    setCurrentTab: function(tab)
    {
        ec.__designSelector.page.currentTab = tab;
        ec._utility.tab.select(tab, 'tab tab-fileType');
        if (tab == 'images') {
            $$get('/ec/image/embed', 'tab-designsBody');
        } else if (tab == 'addresses') {
            $$get('/ec/address-list/manage', 'tab-designsBody');
        } else if (tab == 'orders') {
            $$get('/ec/order-history', 'tab-designsBody');
        }
    },

    setNameForDisplay: function(name)
    {
        ec.__designSelector.category.nameForDisplay = name;
        return false;
    },

    setParentCategoryId: function(categoryId)
    {
        ec.__designSelector.category.parentCategoryId = categoryId;
    },
    setCurrentCategoryId: function(categoryId)
    {
        ec.__designSelector.category.currentCategoryId = categoryId;
    },
    switchLibrary: function(newLibrary)
    {
        if (newLibrary == 'customizableDesigns') {
            ec.design.setCurrentLibraryType('customizable');
            ec.design.setCurrentPageNumber('1');
            ec.design.getLibrary(ec.__designSelector.category.currentCategoryId);
            ec.__designSelector.displaySubCategories();

        } else if (newLibrary == 'myDesigns') {
            ec.design.setCurrentLibraryType('my');
            ec.design.setCurrentPageNumber('1');
            ec.design.getLibrary('');
            ec.__designSelector.displaySubCategories();
        }
    },
    categorySelect: function(selectId)
    {
        var select = document.getElementById( selectId );
        if (ec.__designSelector.page.currentTab == 'designs') {
            ec.__designSelector.setParentCategoryId(select.options[select.selectedIndex].value);
            ec.__designSelector.setCurrentCategoryId(select.options[select.selectedIndex].value);
            ec.__designSelector.switchLibrary('customizableDesigns');
        }
        select.options[select.selectedIndex].selected = true;
    },
    subCategorySelect: function(selectId)
    {
        //determine what type of design it is
        var select = document.getElementById( selectId );
        if (select.id == 'subCategorySelect') {
            if (select.options[select.selectedIndex].value == 'finished'
                || select.options[select.selectedIndex].value == 'unfinished'
                || select.options[select.selectedIndex].value == 'my') {
                if (select.options[select.selectedIndex].value == 'finished') {
                    ec.design.setCurrentLibraryType('saved');
                    ec.design.setCurrentPageNumber('1');
                    ec.design.getLibrary('');
                } else if (select.options[select.selectedIndex].value == 'unfinished') {
                    ec.design.setCurrentLibraryType('unfinished');
                    ec.design.setCurrentPageNumber('1');
                    ec.design.getLibrary('');
                } else {
                    ec.design.setCurrentLibraryType('my');
                    ec.design.setCurrentPageNumber('1');
                    ec.design.getLibrary('');
                }
            } else {
                ec.__designSelector.setCurrentCategoryId(select.options[select.selectedIndex].value);
                ec.design.setCurrentLibraryType('customizable');
                ec.design.setCurrentPageNumber('1');
                ec.design.getLibrary(ec.__designSelector.category.currentCategoryId);
            }

        } else if (select.id == 'productSelect') {
            var confirmMsg = "We noticed you have selected a front and want to change the product type.\n"
                           + "Please note that if you choose a different product type, you’ll need to choose\n"
                           + "choose a front again, as the front and back must be the same product type and size.\n"
                           + "\n"
                           + "Click ‘OK’ to continue with the change, and \n"
                           + "‘Cancel’ to keep the selected front and choose a matching back.";
            if (ec.design.current.frontId && ec.design.current.displaySide == 'back') {
                if (confirm(confirmMsg)) {
                    ec.design.setProductFilter(select.options[select.selectedIndex].value);
                    ec.__designSelector.selectNewFront();
                    return false;
                } else {
                    for (var index in select.options) {
                        if (select.options[index]) {
                            if (select.options[index].value == ec.design.current.productFilter) {
                                select.options[index].selected = true;
                            }
                        }
                    }
                    return false;
                }
            }
            select.options[select.selectedIndex].selected = true;
            select.options[select.selectedIndex].selected = true;
            ec.design.setProductFilter(select.options[select.selectedIndex].value);
            ec.design.getLibrary(ec.__designSelector.category.currentCategoryId);
        }



    },
    displaySubCategories: function()
    {

        if (ec.design.current.libraryType == "my") {
            var subCategorySelect = document.getElementById('subCategorySelect');
            var i;
            for (i = subCategorySelect.options.length-1; i>=0; i--) {
                subCategorySelect.remove(i);
            }
            var all = document.createElement('option');
            all.value = 'my';
            all.text = 'All Designs';
            try
            {
                subCategorySelect.add(all,null);
            }
            catch(ex)
            {
                subCategorySelect.add(all);
            }
            var finished = document.createElement('option');
            finished.value = 'finished';
            finished.text = 'Finished Designs';
            try
            {
                subCategorySelect.add(finished,null); // standards compliant
            }
            catch(ex)
            {
                subCategorySelect.add(finished); // IE only
            }
            var unfinished = document.createElement('option');
            unfinished.value = 'unfinished';
            unfinished.text = 'Unfinished Designs';
            try
            {
                subCategorySelect.add(unfinished,null); // standards compliant
            }
            catch(ex)
            {
                 subCategorySelect.add(unfinished); // IE only
            }
            ec.design.getProductsForUserDesigns();
        } else {
            ec.design.getSubCategories();
        }
    },

    selectNewFront: function()
    {
        if ('designs' != ec.__designSelector.page.currentTab) {
            window.location = '/ec/design/index/change/front';
        } else {
            ec.design.setCurrentDisplaySide('front');
            ec.design.getLibrary(ec.__designSelector.category.currentCategoryId);
            ec.__designSelector.getCurrent();
        }
    },

    selectNewBack: function()
    {
        if ('designs' != ec.__designSelector.page.currentTab) {
            window.location = '/ec/design/index/change/back';
        } else {
            ec.design.setCurrentDisplaySide('back');
            ec.design.getLibrary(ec.__designSelector.category.currentCategoryId);
            ec.__designSelector.getCurrent();
        }
    },

    getCurrent: function()
    {
        $$get('/ec/design/selected', ec.config.design.currentSelected, function(){updateBackImageSize();});
    },

    doneSelecting: function()
    {
        var selectedDesignForm = ec.__designSelector.createSelectedDesignForm();

        var selectedDesignsDiv = document.getElementById('ec-selectedDesigns');
        selectedDesignsDiv.appendChild(selectedDesignForm);
        if (document.getElementById('ec-designCollection')) {
            ec._dom.onLoad('ec-designCollection', "Please wait...");
        }
        selectedDesignForm.submit();
        try {
            ec.__ga.trackEvent('orderStarted');
        } catch (e) {
            if (!window.errors) window.errors = new Array;
            window.errors.push(e);
        }
    },

    /**
     * setDesign
     *
     * Sets the design properties for the selected design, and then returns the library collection based on the
     * current display side of the design.
     *
     * @member  _design
     * @public
     *
     * @param   {Integer}   designId    ID of the current selected design.
     * @param   {String}    designType     'customizable', (saved) 'uploaded', (saved) 'customized', 'unfinished'
     * @param   {String}    intention      default value of 'select', otherwise optional.  could also be 'edit'
     *                                   This is similar to concept of a step in a workflow
     * @param   {String}    backRequired   'required' does not display "Use this Front Only" link, otherwise 'no'
     * @param   {Integer}   productId
     * @param   {String}    requiredBack
     * @param   {Boolean}   submit
     */
    setDesign: function (designId, designType, intention, backRequired, productId, requiredBack, submit)
    {
        ec.__designSelector.dimDesigns();
        if (!intention) {
            var intention = 'select';
        }
        if (typeof submit == 'undefined') {
            if (ec.design.current.displaySide == 'front'  && ec.design.current.backId > 0 ) {
                submit = true;
            } else if (ec.design.current.displaySide == 'back' && ec.design.current.frontId > 0) {
            	submit = true;
            } else {
            	submit = false;
            }
        }
        
        if (typeof requiredBack == 'undefined') {
        	requiredBack = 'none';
        }
        var parameters = {};
        parameters.designId = designId;
        parameters.side = ec.design.current.displaySide;
        parameters.categoryId = ec.__designSelector.category.currentCategoryId;
        parameters.backRequired = backRequired;
        parameters.intention = intention;
        switch (ec.design.current.displaySide) {
            case 'front':
                parameters.frontDesignType = designType;
                ec.design.setCurrentFrontId(designId);
                ec.design.setCurrentFrontType(designType);
                ec.design.setCurrentDisplaySide('back');
                ec.design.setCurrentPageNumber('1');
                ec.design.setCurrentFrontIntention(intention);
                ec.design.setCurrentBackRequired(backRequired);
                ec.design.setCurrentFrontProductId(productId);
                ec.design.setCurrentSideSelected('front');
                if (productId != ec.design.current.backProductId) {
                	ec.design.setCurrentBackId('');
                	ec.design.setCurrentBackIntention('');
                	ec.design.setCurrentBackType('');
                }
                if (requiredBack !== 'none' && designType !== 'uploaded' && designType !== 'customized') {
                	parameters.backDesignType = designType;
	                ec.design.setCurrentBackId(requiredBack);
	                ec.design.setCurrentBackIntention(intention);
	                ec.design.setCurrentBackType(designType);
	                
	                var doneSelectingCallback = function(){ec.__designSelector.doneSelecting();};
                        var selectedCallback = function(){$$post('/ec/design/selected', 'selectedDesigns', doneSelectingCallback)};
	                
	                $$post('/ec/design/select', null, selectedCallback, parameters);
                } else {   
                    var refreshCartCallback = function(){$$post('/ec/order/small-cart', 'smallCart', function(){ec.design.getLibrary(ec.__designSelector.category.currentCategoryId);});};
                    var selectedCallback = function(){$$post('/ec/design/selected', 'selectedDesigns', refreshCartCallback)};
                    $$post('/ec/design/select', null, selectedCallback, parameters);
                }
                try {
                    ec.__ga.trackEvent('designSelectedFront', "id:" + designId);
                } catch (e) {
                    if (!window.errors) window.errors = new Array;
                    window.errors.push(e);
                }
                break;
            case 'back':
                parameters.backDesignType = designType;
                ec.design.setCurrentBackId(designId);
                ec.design.setCurrentBackIntention(intention);
                ec.design.setCurrentBackType(designType);
                ec.design.setCurrentDisplaySide('front');
                ec.design.setCurrentBackProductId(productId);
                ec.design.setCurrentSideSelected('back');
                if (submit) {
                    $$post('/ec/design/select', null, function() {
                            $$post('/ec/design/selected', 'selectedDesigns', function() {
                                ec.__designSelector.doneSelecting()
                            });
                        }, parameters);
                } else {
                    $$post('/ec/design/select', null, function() {
                            $$post('/ec/design/selected', 'selectedDesigns', ec.__designSelector.showDesigns);
                        }, parameters);
                    ec.design.getLibrary(ec.__designSelector.category.currentCategoryId);
                }
                try {
                    ec.__ga.trackEvent('designSelectedBack', "id:" + designId);
                } catch (e) {
                    if (!window.errors) window.errors = new Array;
                    window.errors.push(e);
                }
                break;
        }
    },

    /**
     * createSelectedDesignForm
     *
     * Creates a form to store the selected designs in, formatted for posting to transition to the
     * next step in the workflow.
     *
     * @param
     * @return object selectedDesignForm
     */
    createSelectedDesignForm: function ()
    {
        var side = 'front';

        var selectedDesignForm = document.createElement('form');
        selectedDesignForm.setAttribute('method', 'post');
        selectedDesignForm.setAttribute('action', window.location.href);
        selectedDesignForm.setAttribute('id', 'selectedDesignForm');

        var frontSelection = document.createElement('input');
        frontSelection.setAttribute('type', 'hidden');
        frontSelection.setAttribute('name', 'frontId');
        frontSelection.setAttribute('value', ec.design.current.frontId);
        selectedDesignForm.appendChild(frontSelection);

        var frontDesignTypeInput = document.createElement('input');
        frontDesignTypeInput.setAttribute('type', 'hidden');
        frontDesignTypeInput.setAttribute('name', 'frontDesignType');
        frontDesignTypeInput.setAttribute('value', ec.design.current.frontType);
        selectedDesignForm.appendChild(frontDesignTypeInput);

        var frontDesignIntention = document.createElement('input');
        frontDesignIntention.setAttribute('type', 'hidden');
        frontDesignIntention.setAttribute('name', 'frontDesignIntention');
        frontDesignIntention.setAttribute('value', ec.design.current.frontIntention);
        selectedDesignForm.appendChild(frontDesignIntention);
        if (ec.design.current.backId) {
            side = 'back';

            var backSelection = document.createElement('input');
            backSelection.setAttribute('type', 'hidden');
            backSelection.setAttribute('name', 'backId');
            backSelection.setAttribute('value', ec.design.current.backId);
            selectedDesignForm.appendChild(backSelection);

            var backDesignTypeInput = document.createElement('input');
            backDesignTypeInput.setAttribute('type', 'hidden');
            backDesignTypeInput.setAttribute('name', 'backDesignType');
            backDesignTypeInput.setAttribute('value', ec.design.current.backType);
            selectedDesignForm.appendChild(backDesignTypeInput);

            var backDesignIntention = document.createElement('input');
            backDesignIntention.setAttribute('type', 'hidden');
            backDesignIntention.setAttribute('name', 'backDesignIntention');
            backDesignIntention.setAttribute('value', ec.design.current.backIntention);
            selectedDesignForm.appendChild(backDesignIntention);
        }

        var displaySideInput = document.createElement('input');
        displaySideInput.setAttribute('type', 'hidden');
        displaySideInput.setAttribute('name', 'displaySide');
        displaySideInput.setAttribute('value', side);
        selectedDesignForm.appendChild(displaySideInput);

        var designIdInput = document.createElement('input');
        designIdInput.setAttribute('type', 'hidden');
        designIdInput.setAttribute('name', 'designId');
        designIdInput.setAttribute('value', ec.design.current.frontId);
        selectedDesignForm.appendChild(designIdInput);

        return selectedDesignForm;
    },
    deleteDesign: function(designId, designType)
    {
        var confirmed = confirm('Are you sure you want to delete this design?');
        if(confirmed){
            $$get('/ec/design/delete/designId/' + designId + '/designType/' + designType,'', function(){ec.design.getLibrary();});
            //modalWindow.close('detailDiv');
        }

    },
    copyDesign: function(designId)
    {
        designName = document.getElementById("nameForm").elements["designName"].value;
        $$get('/ec/design/copy/designId/' + designId + '/designName/' + designName,'', function(){ec.design.getLibrary();});
        ec._modal.close();
    },
    makeDetailsDraggable: function() 
    {
        ec._fx.makeDraggable('ec-design-details-container');
    },
    unMakeDetailsDraggable: function()
    {
        ec._fx.unMakeDraggable('ec-design-details-container');
    },
    showDetails: function(designId, designType, backRequired)
    {
        var detailsContainer = document.createElement('div');
        detailsContainer.setAttribute('id','ec-design-details-container');
        
        var detailsDiv = document.createElement('div');
        detailsDiv.setAttribute('id','ec-design-details');
        detailsDiv.onclick = ec.__designSelector.unMakeDetailsDraggable;
        detailsDiv.onmouseover = ec.__designSelector.unMakeDetailsDraggable;
        var detailsHeader = document.createElement('div');
        detailsHeader.setAttribute('id','ec-design-details-header');
        detailsHeader.onclick = ec.__designSelector.makeDetailsDraggable;
        detailsHeader.onmouseover = ec.__designSelector.makeDetailsDraggable;
           
        var closeButton = document.createElement('button');
            closeButton.setAttribute('id','ec-closeButton');
            closeButton.onclick = ec.__designSelector._handleCloseModal;
            detailsHeader.appendChild(closeButton);
            detailsContainer.appendChild(detailsHeader); 
            detailsContainer.appendChild(detailsDiv);
            document.body.appendChild(detailsContainer);   
        if (ec.design.current.libraryType == 'customizable') {
            detailsDiv.designId = designId;
            detailsDiv.designType = designType;
            detailsDiv.backRequired = backRequired;
            var parameters = {};
            parameters.designId = designId;
            parameters.designType = 'customizable';
            parameters.displayType = designType;
            var callback = "ec.__designSelector.formatDetails";
            ec._callApi('design/designDetails', parameters, callback);
        } else {
            detailsDiv.designId = designId;
            detailsDiv.designType = designType;
            detailsDiv.backRequired = backRequired;
            var designDetails = ec.utility.search(ec.jsonDataStore.designCollection.response.design[designType].design, 'id', designId);
            var options = {};
            options.callback = function(){
                var details = document.getElementById('ec-design-details');
                var nameSpan = document.createElement('span');
            nameSpan.innerHTML = designDetails.name;
            nameSpan.style.cssFloat = 'left';
            detailsDiv.appendChild(nameSpan);
            detailsDiv.appendChild(document.createElement('br'));
            detailsDiv.appendChild(document.createElement('br'));
            var thumbnail = document.createElement('img');
            thumbnail.style.border = "1px solid #999999";
            thumbnail.src = designDetails.largeThumbUrl;
            detailsDiv.appendChild(thumbnail);

            detailsDiv.appendChild(document.createElement('br'));
            detailsDiv.appendChild(document.createElement('br'));
            var productSpan = document.createElement('span');
            productSpan.style.cssFloat = 'left';
            productSpan.innerHTML = designDetails.product;
            detailsDiv.appendChild(productSpan);

            detailsDiv.appendChild(document.createElement('br'));
            if (ec.design.current.libraryType == 'unfinished') {
                   var createdSpan = document.createElement('span');
                   createdSpan.style.cssFloat = 'left';
                   createdSpan.innerHTML = 'Created: ' + designDetails.dateCreated;
                   detailsDiv.appendChild(createdSpan);
                   detailsDiv.appendChild(document.createElement('br'));
                   var lastModifiedSpan = document.createElement('span');
                   lastModifiedSpan.style.cssFloat = 'left';
                   lastModifiedSpan.style.fontWeight = 'strong';
                   lastModifiedSpan.innerHTML = 'Last Modified: ' + designDetails.lastModified;
                   detailsDiv.appendChild(document.createElement('br'));
                }
                if (ec.design.current.libraryType == 'saved') {
                   var createdSpan = document.createElement('span');
                   createdSpan.style.cssFloat = 'left';
                   createdSpan.style.fontWeight = 'strong';
                   createdSpan.innerHTML = 'Created: ' + designDetails.dateCreated;
                   detailsDiv.appendChild(createdSpan);
                   detailsDiv.appendChild(document.createElement('br'));
                }
                var selectA = document.createElement('a');
                selectA.innerHTML = 'Select This Design';
                selectA.className = 'ec-designDetailLink';
                selectA.setAttribute('href','#');
                selectA.designId = detailsDiv.designId;
                selectA.designType = designDetails.designType;
                selectA.intent = 'select';
                selectA.fromModal = 'true';
                selectA.backRequired = detailsDiv.backRequired;
                selectA.onclick = ec.design._handleDesignSelection;
                detailsDiv.appendChild(selectA);
                detailsDiv.appendChild(document.createElement('br'));
                if (designDetails.designType == 'customized') {
                    selectA.innerHTML = 'Select to Order';
                    detailsDiv.appendChild(document.createElement('br'));
                    var editA = document.createElement('a');
                    editA.innerHTML = 'Select to Edit';
                    editA.setAttribute('href','#');
                    editA.designId = detailsDiv.designId;
                    editA.designType = designDetails.designType;
                    editA.intent = 'edit';
                    editA.fromModal = 'true';
                    editA.backRequired = detailsDiv.backRequired;
                    editA.onclick = ec.design._handleDesignSelection;
                    detailsDiv.appendChild(editA);
                }
                var clearBr = document.createElement('br');
                clearBr.style.clear = 'both';
                detailsDiv.appendChild(clearBr);
            }

            modalWindow.show(detailsContainer, options);
        }


    },

    formatDetails: function( json ) {

        
        var detailsContainerDiv = document.getElementById('ec-design-details-container');
        var detailsDiv = document.getElementById('ec-design-details');   
        var designDetails = ec.utility.search(ec.jsonDataStore.designCollection.response.design[detailsDiv.designType].design, 'id', detailsDiv.designId);

        var options = {};

        var nameSpan = document.createElement('span');
        nameSpan.innerHTML = designDetails.name;
        nameSpan.style.cssFloat = 'left';
        detailsDiv.appendChild(nameSpan);
        detailsDiv.appendChild(document.createElement('br'));
        detailsDiv.appendChild(document.createElement('br'));
        var thumbnail = document.createElement('img');
        thumbnail.style.border = "1px solid #999999";
        thumbnail.src = designDetails.largeThumbUrl;
        detailsDiv.appendChild(thumbnail);
        var variablesDiv = document.createElement('div');
        variablesDiv.style.cssFloat = 'right';
        detailsDiv.appendChild(variablesDiv);
        variablesDiv.innerHTML = '<strong>Customizable Variables</strong> <br>';
        if (json.response.variables.images.array) {
            if (json.response.variables.images.array instanceof Array) {
                variablesDiv.innerHTML += '<strong>Images</strong> <br>';
                for (i=0; i< json.response.variables.images.array.length;i++) {
                    variablesDiv.innerHTML += json.response.variables.images.array[i] + "<br>";

                }
            }else {
                variablesDiv.innerHTML += '<strong>Images</strong> <br>';
                variablesDiv.innerHTML += json.response.variables.images.array + "<br>";
            }
        } else {
            variablesDiv.innerHTML += '<strong>Images</strong> <br>';
            variablesDiv.innerHTML += 'None <br>';
        }
        if (json.response.variables.text.array instanceof Array) {
            variablesDiv.innerHTML += '<strong>Text</strong> <br>';
            for (i=0; i< json.response.variables.text.array.length;i++) {
                variablesDiv.innerHTML += json.response.variables.text.array[i] + "<br>";

            }
        }else {
            variablesDiv.innerHTML += '<strong>Text</strong> <br>';
            variablesDiv.innerHTML += json.response.variables.text.array + "<br>";
        }
        detailsDiv.appendChild(document.createElement('br'));
        detailsDiv.appendChild(document.createElement('br'));
        var productSpan = document.createElement('span');
        productSpan.style.cssFloat = 'left';
        productSpan.innerHTML = designDetails.product;
        detailsDiv.appendChild(productSpan);

        detailsDiv.appendChild(document.createElement('br'));

        var selectA = document.createElement('a');
        selectA.innerHTML = 'Select This Design';
        selectA.designId = detailsDiv.designId;
        selectA.designType = ec.design.current.libraryType;
        selectA.intent = 'select';
        selectA.fromModal = 'true';
        selectA.backRequired = detailsDiv.backRequired;
        selectA.onclick = ec.design._handleDesignSelection;
        detailsDiv.appendChild(selectA);
        detailsDiv.appendChild(document.createElement('br'));

        var previewPdfA = document.createElement('a');
        previewPdfA.innerHTML = 'View Detailed Preview PDF';
        previewPdfA.target = '_blank';
        previewPdfA.href = '/ec/ajax/design/preview-pdf/designId/'+detailsDiv.designId;
        detailsDiv.appendChild(previewPdfA);

        var clearBr = document.createElement('br');
        clearBr.style.clear = 'both';
        detailsDiv.appendChild(clearBr);

        modalWindow.show(detailsContainerDiv, options);
    },

    openUpload: function(){
        var uploadDiv = document.createElement('div');
        uploadDiv.setAttribute('id', 'uploadDiv');
        uploadDiv.style.width = '392px';
        uploadDiv.style.zIndex  = '2000';
        uploadDiv.style.height = '367px';
        uploadDiv.style.padding = '6px';
        uploadDiv.style.position = "absolute";
        uploadDiv.style.backgroundColor = "#F3F3F3";
        document.body.appendChild(uploadDiv);
        adjustCenteredElement(uploadDiv);

        ec._ajax.getHtml('/ec/upload/upload/type/design', uploadDiv, null);

        var options = {};
        modalWindow.show(uploadDiv, options);
    },
    closeUpload: function(){
        modalWindow.close('uploadDiv');

    },
    
    toggleSides: function(ele){
        var side = ele.options[ele.selectedIndex].value;
    	ec.design.setCurrentDisplaySide(side);
    	ec.design.getLibrary(ec.__designSelector.category.currentCategoryId,ec.design.current.displaySide); 
    	
    },
    
    dimDesigns: function() {
        var dsDiv = document.getElementById('ec-designCollection');
        dsDiv.style.visibility = 'hidden';
        dsDiv.style.zIndex = '1000';
        var waitDiv = document.getElementById('ec-waitHolder');
        ec._dom.onLoad(waitDiv, "Please wait as designs load...");
    },
    
    showDesigns: function() {
        var waitDiv = document.getElementById('ec-waitHolder');
        if (waitDiv.firstChild) waitDiv.removeChild(waitDiv.firstChild);
        if (waitDiv.lastChild) waitDiv.removeChild(waitDiv.lastChild);
        var dsDiv = document.getElementById('ec-designCollection');
        dsDiv.style.visibility = 'visible';
        updateBackImageSize();
        $$get('/ec/design/balloon', 'balloon');
    },
    
    _backToDesignsCallback: function()
    {
        var tabBody = document.getElementById('tab-body');
        ec.__designSelector.setNameForDisplay(tabBody.currentCategoryName);
        ec.__designSelector.switchLibrary('customizableDesigns');
    },

    _handleCloseModal: function(e)
   {
        var target = e?e.target:window.event?window.event.srcElement:null;
        var divToClose = target.parentNode.id;
        modalWindow.close(divToClose);

   }

};

ec.__designSelector = _designSelector;
_designSelector = {};
/**
 * @file components/local/editor.js
 */
var _editor = {
	
	boot: function(json) {
	
       if (json.apiKey) {
            ec.config.setApiKey(json.apiKey);
        
        }
        if (json.apiHost) {
            ec.config.setApiHost(json.apiHost);
        }
        if (json.eztId) {
        	ec.__editor.setCurrentEzt2Id(json.eztId);
        }
        if (json.tempUser){
        	ec.__editor.setCurrentTempUser(json.tempUser);
        }
        if ($byId('backEdited').value == 'false') {
            var frontThumb = $byId('frontThumb');
            if ('object' == typeof frontThumb && frontThumb != null) {
                frontThumb.setAttribute('onclick', 'onFrontTabClick()');
                frontThumb.style.cursor = 'pointer';
            }
            var backThumb = $byId('backThumb');
            if ('object' == typeof backThumb && backThumb != null) {
                backThumb.setAttribute('onclick', 'onBackTabClick()');
                backThumb.style.cursor = 'pointer';
            }
        }
        ec.__editor.refresh(document.getElementById('editorForm'), '/ec/editor/save');
	},
	current: {
		eztId: '',
		tempUser: ''
	},
	
	setCurrentEzt2Id: function( id ) {
		ec.__editor.current.eztId = id;
	},
	setCurrentTempUser: function( tempUser ) {
        ec.__editor.current.tempUser = tempUser;
    },
	
    /**
    * save 
    * @member  editor
    * @public
    * @param {Element}  form  The form that contains the customizable information that needs to be saved. 
    * @param {String}   url   Url of the save action.
    */
    save: function(form, url) {
        ec.__editor.refresh(form, url);
    },
    /**
     * refresh 
     * @member  editor
     * @public
     * @param {Element}  form  The form that contains the customizable information that needs to be saved. 
     * @param {String}   url   Url of the save action.
     */
    refresh: function (form, url) {
        ec.__editor.updateFrontImageHeight();
        ec.__editor.updateBackImageHeight();
        var parameters = ec.utility.form.serialize(form);
        ajaxObject.response = 'JSON';
        ajaxObject.method = 'POST';
        ajaxObject.getRequest({
            parameters: parameters,
            url: url,
            onComplete: function(json){
                $byId('previewImageFront').innerHTML = "<img id=\"frontJpgPreview\" style=\"border:1px solid #999999;\" />";
                $byId('previewImageBack').innerHTML = "<img id=\"backJpgPreview\" style=\"border:1px solid #999999;\" />";
                var frontJpg = document.getElementById( 'frontJpgPreview' );
                frontJpg.setAttribute( 'src', json.front );
                var backJpg = document.getElementById( 'backJpgPreview' );
                backJpg.setAttribute( 'src', json.back );
                var saveMessageDiv = document.getElementById('saveMessageDiv');
                if ('/static/imageserver/mpowertmp/' == json.front || '/static/imageserver/mpowertmp/' == json.back) {
                    jQuery('#previewImageFront').html(
                        '<span style="color:red;font-weight:bold;display:block;">Your print file has encountered an error:</span>'
                        + '    Possible reasons for this are:'
                        + '    <ol>'
                        + '    <li>An image used on this design has been removed from your image library.</li>'
                        + '    <li>Too much text has been entered in any one text box.</li>'
                        + '    <li>Possible issue with a font used on your design.</li>'
                        + '    If checking these issues does not resolve this issue, please call customer support at the number above.'
                        + '</span>');
                    saveMessageDiv.innerHTML = 'changes applied';
                    saveMessageDiv.style.color = 'red';
                    setTimeout(function(){saveMessageDiv.innerHTML = "";}, 5000);
                }
            }
        });
        try {
            ec.__ga.trackEvent('designEditorCustomization');
        } catch (e) {
            if (!window.errors) window.errors = new Array;
            window.errors.push(e);
        }
    },
    /**
    * onTabClick 
    * @member  editor
    * @public
    * @param {String}   tabToShowId Id of the tab you want to show. 
    * @param {String}   tabToHideId Id of the tab you want to hide.
    */
    onTabClick: function( tabToShowId, tabToHideId ) { 
        ec.utility.element.show( tabToShowId );
        ec.utility.element.hide( tabToHideId );
        ec.__editor.updateFrontImageHeight();
        ec.__editor.updateBackImageHeight();
    },
    onSideClick: function (sideToShow) {
        switch (sideToShow) {
            case 'front':
                ec.utility.element.show('textFront');
                ec.utility.element.show('postcardPreviewFront');
                ec.utility.element.show('previewImageFront');
                ec.utility.element.show('instructionsFront');
                ec.utility.element.show('customizableFieldsFront');
                ec.utility.element.show('customizableFieldsCommon');
                
                ec.utility.element.hide('textBack');
                ec.utility.element.hide('postcardPreviewBack');
                ec.utility.element.hide('previewImageBack');
                ec.utility.element.hide('instructionsBack');
                ec.utility.element.hide('customizableFieldsBack');
                
                document.getElementById('frontSide').className = 'side current';
                document.getElementById('backSide').className = 'side';
                break;
            case 'back':
                ec.utility.element.show('textBack');
                ec.utility.element.show('postcardPreviewBack');
                ec.utility.element.show('previewImageBack');
                ec.utility.element.show('instructionsBack');
                ec.utility.element.show('customizableFieldsBack');
                
                ec.utility.element.hide('textFront');
                ec.utility.element.hide('postcardPreviewFront');
                ec.utility.element.hide('previewImageFront');
                ec.utility.element.hide('instructionsFront');
                ec.utility.element.hide('customizableFieldsFront');
                
                document.getElementById('backSide').className = 'side current';
                document.getElementById('frontSide').className = 'side';
                break;
        }
    },
    /**
     * addImage
     * @member  editor
     * @public
     * @param {String}   id    Id of the image to replace.
     * @param {String}   value Value to set the input to.
     * @param {Element}  formId  The id of the form that contains the image that needs to be updated. 
     * @param {String}   url   Url of the save action.
     */
    addImage: function (id, value, formId, url) {
       
        var element = document.getElementById(id);
        var form = document.getElementById(formId);
        decodedValue = decodeURIComponent(value);

        element.value = decodedValue;
        ec.__editor.save(form, url);
    },
    /**
     * removeImage 
     * @member  editor
     * @public
     * @param {String}   id    Id of the image to remove.
     */
    removeImage: function (id) {
        $byId(id).value = '';
        ec.__editor.refresh($byId('projectForm'), '/ec/editor/save');
    },
    /**
     * previewPdf
     * @member  editor
     * @public
     */
    previewPdf: function () {
        var modalWindowDiv = document.createElement('div');
        modalWindowDiv.setAttribute('id', 'modalWindow');
        modalWindowDiv.style.width = "750px";
        //modalWindowDiv.style.height = "500px";
        modalWindowDiv.style.backgroundColor = "#FFFFFF";
        modalWindowDiv.style.zIndex = "2000";
        //modalWindowDiv.style.top = "100px";
        //modalWindowDiv.style.left = "100px";
        modalWindowDiv.style.position = "absolute";
        
        document.body.appendChild(modalWindowDiv);
        adjustCenteredElement(modalWindowDiv);
        
        ajaxObject.method = 'GET';
        ajaxObject.response = 'HTML';
        ajaxObject.getRequest({
            parameters: '',
            url: '/ec/editor/preview',
            onComplete: function( html ){
                modalWindowDiv.innerHTML = html;
            }
        });
        
        var options = {};
        modalWindow.keepCentered = false;
        modalWindow.show(modalWindowDiv, options);
        ec._fx.makeDraggable(modalWindowDiv);
    },
    /**
     * renameProject
     * @member  editor
     * @public
     * @param {String}  projectName     The new name of the project.
     */
    renameProject: function ( projectName ) {
        var renameForm = document.getElementById('renameProjectForm');
        
        ajaxObject.response = 'JSON';
        ajaxObject.method = 'GET';
        ajaxObject.getRequest({
            parameters: {},
            url: '/ec/editor/rename/projectName/'+projectName,
            onComplete: function( json ) {
                var projectNameDisplayElement = document.getElementById('projectNameDisplay');
                var projectNameElement = document.getElementById('projectName');
                var projectRenameElement = document.getElementById('projectReName');
                projectNameDisplayElement.innerHTML = json.response;
                projectNameElement.value = json.response;
                projectRenameElement.value = json.response;
                renameForm.style.display = 'none';
            }
        });
    },
    returnFromAdvancedEditor: function () {
    	ajaxObject.response = 'HTML';
    	ajaxObject.method = 'GET';
    	ajaxObject.getRequest({
            parameters: {},
            url: '/ec/editor/advanced',
            onComplete: function( html ) {
                var editorDiv = document.getElementById('editor');
                editorDiv.innerHTML = html;
            }
        });
    },
    updateFrontImageHeight: function() {
        var previewImageElement = jQuery('#backJpgPreview');
        if (previewImageElement.length > 0) {
            return jQuery('#previewImageFront').height(previewImageElement.get(0).height+2);
        }
    },
    updateBackImageHeight: function() {
        var previewImageElement = jQuery('#frontJpgPreview');
        if (previewImageElement.length > 0) {
            return jQuery('#previewImageBack').height(previewImageElement.get(0).height+2);
        }
    }
}

ec.__editor = _editor;
_editor = {};

/**
 * @file components/local/ga.js
 */
var _ga = {
    eventNames: {},
    // eventUrlRegExp: List of regular expressions that determine how to track the AJAX URL.
    eventUrlRegExp: [
        {category: 'Orderflow', action: 'upload', label: 'customerDesign', regEx: /.*\/ec\/ajax\/design-uploader\/summary.*/},
        {category: 'Orderflow', action: 'upload', label: 'customerList', regEx: /.*\/ec\/ajax\/upload\/update-address.*/},
    ],
    init: function() {
        try {
            jQuery.get('/static/js/ecr/components/local/ga_events.json', function(data) {
                try {
                    ec.__ga.eventNames = eval(data);
                } catch (e) {}
            });
        } catch (e) {}
    },
    sendToGa: function(params) {
        if (!_gaq) {
            return false;
        }
        if (params.length < 4) {
            return false;
        }
        _gaq.push(params);
    },
    trackEvent: function(eventName, argument) {
        var params = [];
        params.push('_trackEvent');
        for (x in this.eventNames) {
            if (this.eventNames[x].eventName == eventName) {
                params.push(this.eventNames[x].category, this.eventNames[x].action, 'number' != typeof argument && 'undefined' != typeof argument ? argument : this.eventNames[x].label);
            }
        }
        // only use the argument if it's a number as Google requires this to be an int.
        if ('number' == typeof argument) {
            params.push(Math.round(argument));
        }
        this.sendToGa(params);
    },
    trackEventByUrl: function(url) {
        // Determine what event is happening based on the url.
        for (x in this.eventUrlRegExp) {
            if (this.eventUrlRegExp[x].regEx) {
                var regEx = new RegExp(this.eventUrlRegExp[x].regEx);
                if (regEx.test(url)) {
                    var params = ['_trackEvent', this.eventUrlRegExp[x].category, this.eventUrlRegExp[x].action, this.eventUrlRegExp[x].label];
                    this.sendToGa(params);
                }
            }
        }
    }
}

ec.__ga = _ga;
_ga = '';
ec.__ga.init();
/**
 * @file components/local/imageManager.js
 */
var _imageManager = {
    open: function(fieldName){
        ec._modal.width = '629px';
        $$modal('/ec/image/index/fieldName/' + fieldName);
    },
    close: function(){
        ec._modal.close();
    },
    enable: function() {

        var inputs = document.getElementsByTagName("input");
        var limit = inputs.length;
        for (var i=0; i < limit; i++) {
           inputs[i].disabled = false;
        }

    },
    imageUpload: function(editor){
       if(document.getElementById('ec-imageLibrary')){
            var savedImages = document.getElementById('ec-imageLibrary');
            savedImages.innerHTML = '';
       }

       if(document.getElementById('ec-imageCategories')){
            var categoryDiv = document.getElementById('ec-imageCategories');
            categoryDiv.innerHTML = '';
       }
       ec.image.setCurrentPageNumber('1');
       var upForm = document.getElementById("uploadForm");
       
       // If we are coming from the editor, then document.domain needs to be set to expresscopy.com
       if (editor) {
           $$get('/ec/upload/upload/type/image-editor', upForm, null);
       } else {
           $$get('/ec/upload/upload/type/image', upForm, null);
       }
    },

    _handleCategoryClick: function(e) {
    	 var target = e?e.target:window.event?window.event.srcElement:null;
    	 if (target.subIndexValue) {
    	     ec.image.setCurrentPageNumber('1');
    	     ec.image._formatSubSubCategories(target.subIndexValue,target.indexValue);
         } else {
             ec.image.setCurrentPageNumber('1');
             ec.image._formatSubCategories(target.indexValue);
    	 }
    },

     _handleBottomLevelCategoryClick: function(e) {
         var target = e?e.target:window.event?window.event.srcElement:null;
         ec.image.setCurrentPageNumber('1');
         ec.image.getLibrary(target.categoryId);
    },

    _handleAssignImageToDesignClick: function(e){
    	var target = e?e.target:window.event?window.event.srcElement:null;
    	ec.__editor.addImage(  target.fieldName,
    	                       target.encodedUri,
    	                       'projectForm',
    	                       '/ec/editor/save');
    	 ec.__imageManager.close();
    }

}

ec.__imageManager = _imageManager;
_imageManager = {};
/**
 * @file components/local/leads.js
 */
var _leads = {
    refresh: function(callbackArg) {
        if (typeof callbackArg != 'function') {
           callbackArg = function(){};
        }
        if (jQuery('#geographicsBody').length > 0) {
            var callback = function() {
                if (jQuery('#geographicsBody').find('.errors').length > 0) {
                    ec._utility.tab.select('tabGeography', 'tab tab-fileType')
                } else {
                    callbackArg();
                }
            };
            if (jQuery('input[name=geographyType]').filter('input:checked').val() == 'address') {
                jQuery.post(
                    '/ec/ajax/leads/geography',
                    jQuery('#addressForm').serialize(),
                    function(data, text, jqXHR) {
                        jQuery('#tab-bodyListConnect').html(data);
                        callback();
                    }
                );
            } else if (jQuery('input[name=geographyType]').filter('input:checked').val() == 'zipcodes') {
                jQuery.post(
                    '/ec/ajax/leads/geography',
                    jQuery('#zipForm').serialize(),
                    function(data, text, jqXHR) {
                        jQuery('#tab-bodyListConnect').html(data);
                        callback();
                    }
                );
            } else {
                callbackArg();
            }
        } else if (jQuery('#demographicsBody').length > 0) {
            jQuery.post(
                '/ec/ajax/leads/demographics',
                jQuery('#demographicsForm').serialize(),
                function(data, text, jqXHR) {
                    callbackArg();
                }
            );
        } else {
            callbackArg();
        }
        // Hack for Chrome -- need to re-render this bar to get Chrome to update its display, render issue.
        jQuery('#tab-headerListConnect').fadeOut(1).fadeIn(1);
    },
    onloadGeography: function() {
        jQuery('#addressForm').change(function(){
            jQuery('input[name=geographyType]:radio').filter('input[value=address]').click();
        });
        jQuery('#zipForm').change(function(){
            jQuery('input[name=geographyType]:radio').filter('input[value=zipcodes]').click();
        });
    },
    updateReview: function() {
        this.refresh(function(){$$get('/ec/leads/review', 'tab-bodyListConnect')});
    },
    updateGeography: function() {
        this.refresh(function(){$$get('/ec/leads/geography', 'tab-bodyListConnect', ec.__leads.onloadGeography)});
    },
    resetDemographics: function() {
        ec._dom.onReload('tab-bodyListConnect', 'please wait...','200', '200'); 
        $$post('/ec/leads/demographics', null, function(){$$get('/ec/leads/demographics', 'tab-bodyListConnect');}, {reset: true});
    },
    updateDemographics: function(callbackArg) {
        this.refresh(function(){$$get('/ec/leads/demographics', 'tab-bodyListConnect')});
    },
    updateListType: function() {
        this.refresh(function(){$$get('/ec/leads/data-product', 'tab-bodyListConnect')});
    },
    validateReview: function() {
        var errorMsg = '';
        
        // verify terms and conditions checked
        if ($byId('terms').checked != true) {
            errorMsg = 'The terms and conditions needs to be agreed and checked.';
        }
        
        // verify requested leads <= available leads
        if (($byId('availableLeads').value != 0) && parseInt($byId('requestedQuantity').value) > parseInt($byId('availableLeads').value)) {
            errorMsg = "Requested quantity can't be greater than number of available leads.";
        }
        
        // verify geography exist
        if ($byId('hasGeography').value == 'false') {
            errorMsg = "Error! Geography must be completed."
        }
        
        if (errorMsg != '') {
            $byId('reviewErrorMessage').innerHTML = errorMsg;
            return false;
        } else {
            return true;
        }
    }
}

ec.__leads = _leads;
_leads = "";
/**
 * @file components/local/menu.js
 */
var _menu = {
    open: function(divId) {
        if (typeof divId == 'object') {
            div = divId;
        } else {
            div = document.getElementById(divId);
        }
        div.style.left = '0';
    },
    close: function(divId) {
        if (typeof divId == 'object') {
            div = divId;
        } else {
            div = document.getElementById(divId);
        }
        div.style.left = '-999em';
    }
}
ec._menu = _menu;
_menu = "";
/**
 * @file components/local/options.js
 */
var _options = {
    setAllowFileRevisionOption: function(allowFileRevision) {
        $$post('/ec/product/set-allow-file-revision',
            'allowFileRevision',
            null,
            {'allowFileRevision': allowFileRevision}
        );
    },
    schedule: function() {
        ec.__options.hide('startToday',this);
        ec.__options.show('scheduleCalendar',this);
    },
    setMailingOption: function(optionId) {
        $$post('/ec/product/set-mailing-option' + optionId,
            $byId('productOptions'),
            ec.__options.updateProductOptions,
            {'id': optionId}
        );
    },
    setColorOption: function(optionId) {
        $$post('/ec/product/set-color-option',
            $byId('productOptions'),
            ec.__options.updateProductOptions,
            {'id': optionId}
        );
    },
    setStockOption: function(optionId) {
        $$post('/ec/product/set-stock-option',
            $byId('productOptions'),
            ec.__options.updateProductOptions,
            {'id': optionId}
        );
    },
    addBinderyOption: function(optionId) {
        $$post('/ec/product/add-bindery-option',
            $byId('productOptions'),
            ec.__options.updateProductOptions,
            {'id': optionId}
        );
    },
    removeBinderyOption: function(optionId) {
        $$post('/ec/product/remove-bindery-option',
            $byId('productOptions'),
            ec.__options.updateProductOptions,
            {'id': optionId}
        );
    },
    setGenericAddressee: function(optionId) {
        var parameters = {};
        if (optionId) {
            parameters.genericAddresseeId = optionId;
        }
        $$post(
            '/ec/delivery/set-generic-addressee',
            'genericAddressee',
            null,
            parameters
        );
    },
    addProofOption: function(optionId) {
            $$post('/ec/product/add-proof',
            $byId('productOptions'), 
            function(){
                ec.__options.updateProductOptions;
                if ($byId('faxedProofPhone_areaCode')) {
                    $byId('faxedProofPhone_areaCode').focus();
                }
            },
            {'id': optionId}
        );
    },
    removeProofOption: function(optionId) {
        $$post('/ec/product/remove-proof',
            $byId('productOptions'), 
            ec.__options.updateProductOptions
        );
    },
    setFaxedProofPhoneNumber: function(areaCodeElement, prefixElement, suffixElement) {
        var parameters = {};
        var areaCode = $byId(areaCodeElement).value;
        var prefix = $byId(prefixElement).value;
        var suffix = $byId(suffixElement).value;
        parameters.phoneNumber = $byId(areaCodeElement).value + $byId(prefixElement).value + $byId(suffixElement).value;
        $$post(
            '/ec/product/set-faxed-proof-phone-number',
            'faxedProofPhoneMessage',
            null,
            parameters
        );
    },
    setDirectMail: function(optionId) {
        ec.__options.deliveryDisableNavigation();
        $$post('/ec/delivery/set-direct-mail',
            $byId('deliveryOptions'),
            ec.__options.updateDeliveryOptions,
            {'id': optionId}
        );
    },
    setDirectMailFirstClass: function() {
        ec.__options.deliveryDisableNavigation();
        $$post("/ec/delivery/set-direct-mail-first-class",
            $byId('deliveryOptions'),
            ec.__options.updateDeliveryOptions);
    },
    setDirectMailStandard: function() {
        ec.__options.deliveryDisableNavigation();
        $$post("/ec/delivery/set-direct-mail-standard",
            $byId('deliveryOptions'),
            ec.__options.updateDeliveryOptions);
    },
    setPrintAndAddress: function() {
        ec.__options.deliveryDisableNavigation();
        $$post("/ec/delivery/set-print-and-address-and-ship",
            $byId('deliveryOptions'),
            ec.__options.updateDeliveryOptions);
    },
    setPrintOnly: function() {
        ec.__options.deliveryDisableNavigation();
        $$post("/ec/delivery/set-print-and-ship",
            $byId('deliveryOptions'),
            ec.__options.updateDeliveryOptions);
    },
    show: function(elementId, callingElement) {
        ec.utility.element.show(elementId);
        callingElement.innerHTML = "hide";
        callingElement.onclick = function() {
            ec.__options.hide(elementId, callingElement);
        };
    },
    hide: function(elementId, callingElement) {
        ec.utility.element.hide(elementId);
        callingElement.innerHTML = "change";
        callingElement.onclick = function() {
            ec.__options.show(elementId, callingElement);
        };
    },
    addAddressList: function(id) {
        ec.__options.deliveryDisableNavigation();
        var addressFileIdCountElement = $byId('addressFile' + id + 'Count');
        if (null != addressFileIdCountElement && addressFileIdCountElement.value < 1) {
            alert('You have selected a mailing list with an Address Count of 0.' +
            ' Please update the number of addresses on this file.  If you are unsure of the number of addresses' +
            ' simply click the download file link for reference.');
            $byId(id).checked = false;
        } else {
            $$post('/ec/address-list/add-list',
                $byId('addressLists'), 
                ec.__options.updateDeliveryOptions,
                {'id': id}
            );
        }
    },
    removeAddressList: function(id) {
        ec.__options.deliveryDisableNavigation();
        $$post('/ec/address-list/remove-list',
            $byId('addressLists'),
            ec.__options.updateDeliveryOptions,
            {'id': id}
        );
    },
    renameAddressList: function(id, name) {
        $$post('/ec/address-list/rename/',
            $byId('addressLists'),
            ec.__options.updateDeliveryOptions,
            {'id': id, 'name': name}
        );
    },
    changeCount: function(id, newCount) {
        $$post('/ec/address-list/change-count/', 
                'addressLists',
                ec.__options.updateDeliveryOptions,
                {'id': id, 'count': newCount}
        );
    },
    checkAddressListCount: function(count) {
        if (count < 1) {
            alert('Please enter an amount for the Address Count.  If you are unsure of the number of addresses,' +
                  ' please click on download file to find out.');
        }
    },
    setMailToMe: function(id) {
        $$post('/ec/address-list/set-mail-to-me',
            $byId('addressLists'),
            ec.__options.updateDeliveryOptions
        );
        ec._utility.element.show('mailToMeAddress');
    },
    unsetMailToMe: function(id) {
        $$post('/ec/address-list/unset-mail-to-me',
            $byId('addressLists'),
            ec.__options.updateDeliveryOptions
        );
        ec._utility.element.hide('mailToMeAddress');
    },
    addPrintOnlyAdditionalPieces: function(input) {
        $$post('/ec/delivery/add-print-only-additional-pieces',
            $byId('deliveryOptions'),
            ec.__options.updateDeliveryOptions,
            {'quantity': input.value}
        );
    },
    removePrintOnlyAdditionalPieces: function() {
        $$post('/ec/delivery/remove-print-only-additional-pieces',
                $byId('deliveryOptions'),
                ec.__options.updateDeliveryOptions
        );
    },
    updateDeliveryOptions: function() {
        var cassSectionCallback = function() {
            $$post('/ec/delivery/cass-options',
                $byId('cassOptions'),
                ec.__options.deliveryEnableNavigation
            );
        };
        $$post('/ec/order/small-cart', 
            $byId('smallCart'), 
            cassSectionCallback
        );
    },
    updateProductOptions: function() {
        var summarySectionCallback = function() {
            $$post('/ec/product/summary-section',
                $byId('summarySection')
            );
        };
        $$post('/ec/order/small-cart',
            $byId('smallCart'),
            summarySectionCallback
        );
    },
    printOnlyUpdateQuantity: function(input) {
        $$post('/ec/delivery/quantity',
            $byId('quantity'),
            ec.__options.updateDeliveryOptions,
            {'quantity': input.value}
        );
    },
    printOnlyAdditionalPiecesUpdateQuantity: function(input) {
        $$post('/ec/delivery/add-print-only-additional-pieces',
            $byId('deliveryOptions'),
            ec.__options.updateDeliveryOptions,
            {'quantity': input.value}
        );
    },
    deliveryNext: function()
    {
        var deliveryOptionsForm = $byId('deliveryOptionsForm');
        var quantityInput = $byId('invoiceItemQuantityInput');
        var submitForm = true;
        if (quantityInput) {
            deliveryOptionsForm.quantity.value = $byId('invoiceItemQuantityInput').value;
        }

        // check cass options, if present
        if ($byId('cassOptionsForm') != null) {
            if (!$byId('cassOptionsForm').elements[0].checked && !$byId('cassOptionsForm').elements[2].checked) {
                alert('Please select CASS certification options.');
                $byId('cassSelectionVariance').focus();
                var submitForm = false;
            } else {
                if ($byId('cassKeepDuplicatesCheckbox').checked) {
                    $byId('cassKeepDuplicates').value = true;
                } else {
                    $byId('cassKeepDuplicates').value = false;
                }
                $$submit('cassOptionsForm', '/ec/delivery/cass-options', 'cassOptions');
            }
        }

        // submit mailToMeAddressForm if needed, then followed by deliveryOptionsForm
        if ($byId('mailToMeAddress') != null && $byId('mailToMeAddress').style.display !== 'none') {
            var mailToMeAddressCallback = function() {
                if (ec.getBrowser() == "IE7" || ec.getBrowser() == "IE6"){
                    var mailToMeAddressErrors = getElementsByClassNameForIE('errors', $byId('mailToMeAddressForm'));
                } else {
                    var mailToMeAddressErrors = $byId('mailToMeAddressForm').getElementsByClassName('errors');
                }
                
                if (mailToMeAddressErrors.length > 0) {
                    $byId('name').focus();
                    window.location.hash = 'mailToMeAddress'; // goes mailing address section
                } else if (submitForm) {
                    // no errors, so submit remaining form
                    deliveryOptionsForm.submit();
                }
            };
            $$submit('mailToMeAddressForm', '/ec/delivery/mail-to-me-address', 'mailToMeAddress', mailToMeAddressCallback);
        } else if (submitForm) {
            // shippingAddress present, so submit it
            if ($byId('shippingAddressBody') != null) {
                var shippingAddressCallBack = function() {
                    if (ec.getBrowser() == "IE7" || ec.getBrowser() == "IE6"){
                        var shippingAddressErrors = getElementsByClassNameForIE('errors', $byId('shippingAddressForm'));
                    } else {
                        var shippingAddressErrors = $byId('shippingAddressForm').getElementsByClassName('errors');
                    }
                    // check for errors
                    if (submitForm && shippingAddressErrors.length <= 0) {
                        // no errors, so submit remaining form
                        deliveryOptionsForm.submit();
                    }
                }
                $$submit('shippingAddressForm', '/ec/delivery/shipping-address', 'shippingAddressBody', shippingAddressCallBack);
            } else {
                // mailToMe not used, so just submit deliveryOptionsForm
                deliveryOptionsForm.submit();
            }
        }
    },
    deliveryDisableNavigation: function()
    {
        $byId('topNextButton').style.display = 'none';
        $byId('bottomNextButton').style.display = 'none';
        var buttons = document.getElementsByClassName('backButton');
        for (i in buttons) {
            if (typeof buttons[i] == 'object') {
                buttons[i].style.display = 'none';
            }
        }
    },
    deliveryEnableNavigation: function()
    {
        $byId('topNextButton').style.display = 'inline';
        $byId('bottomNextButton').style.display = 'inline';
        var buttons = document.getElementsByClassName('backButton');
        for (i in buttons) {
            if (typeof buttons[i] == 'object') {
                buttons[i].style.display = 'inline';
            }
        }
    }
};

ec.__options = _options;
_options = {};
/**
 * @file components/local/promotion.js
 */
var _promotion = {
    /**
     * refresh 
     * @member  editor
     * @public
     * @param {Object}   form     The form with the promotion information.
     * @param {Object}   element  The element to update with the HTML response.
     */
    apply: function (form, element) {
        $$submit(
            form,
            '/ec/order/promotion',
            element,
            function(){
                ec.__checkout.refreshInvoiceTotal();
                if (jQuery('#promotionText').html().length > 0) {
                    // failed
                    try {
                        ec.__ga.trackEvent('promotionValidationFailed');
                    } catch (e) {
                        if (!window.errors) window.errors = new Array;
                        window.errors.push(e);
                    }
                } else {
                    // succeeded
                    try {
                        ec.__ga.trackEvent('promotionApplied');
                    } catch (e) {
                        if (!window.errors) window.errors = new Array;
                        window.errors.push(e);
                    }
                }
            }
        );
    }
};

ec.__promotion = _promotion;
_promotion = '';
/**
 * @file components/local/tab.js
 */
var _tab = {
    select: function(tabId){
        var tabs = document.getElementsByClassName('tab-fileType');
        
        for(var index in tabs){
            tabs[index].setAttribute('class', 'tab-fileType');
        }
        
        $byId(tabId).setAttribute('class', 'tab-fileType selected');
    }
}

ec.__tab = _tab;
_tab = '';
/**
 * @file components/local/uploader.js
 */
var __uploader = function() {

    var _selectedFront = {
        id: '',
        productId: ''
    };
    var _selectedBack = {
        id: '',
        productId: ''
    };

    function _resetSteps(className) {
        var steps = document.getElementsByClassName(className);
        for(var index in steps){
            steps[index].className = className;
        }
    }

    function _selectDesign(designId, side) {
            var element = $byId('uploadedDesign-' + designId); 
            var uploadedDesigns = document.getElementsByClassName('ec-design ' + side);

            for(var index in uploadedDesigns){
                if (index !== "inArray") {
                    uploadedDesigns[index].style.border = "none";
                    uploadedDesigns[index].style.backgroundColor = "#E0E0E0";
                }
            }
            if(element) {
                element.style.border = "1px solid #333333";
                element.style.backgroundColor = "#FFFFFF";
            }
    }

    function _showNextButtons() {
        $byId('nextButtonSummaryTop').style.visibility = "visible";
        $byId('nextButtonSummaryBottom').style.visibility = "visible";
    }

    return {
        /**
        *  The load function is used by ec.js to load this object onto the main ec ojbect.
        **/
        load: function() {
            ec.uploader = this;
            __uploader = "use ec.uploader";
        },
        steps: {
            hideSteps: function() {
                $byId('fileUploadSteps').style.display = "none";
            },
            changeStep: function(step) {
                _resetSteps('progressButton');
                switch(step) {
                    case '1':
                        $byId('progressStep1').className = "progressButton progressButtonSelected";
                    break;
                    case '2':
                        $byId('progressStep1').className = "progressButton progressButtonCompleted";
                        $byId('progressStep2').className = "progressButton progressButtonSelected";
                    break;
                    case '3':
                        try {
                            ec.__ga.trackEvent('orderStarted');
                        } catch (e) {
                            if (!window.errors) window.errors = new Array;
                            window.errors.push(e);
                        }
                        $byId('progressStep1').className = "progressButton progressButtonCompleted";
                        $byId('progressStep2').className = "progressButton progressButtonCompleted";
                        $byId('progressStep3').className = "progressButton progressButtonSelected";
                    break;
                    case '4':
                        $byId('progressStep1').className = "progressButton progressButtonCompleted";
                        $byId('progressStep2').className = "progressButton progressButtonCompleted";
                        $byId('progressStep3').className = "progressButton progressButtonCompleted";
                        $byId('progressStep4').className = "progressButton progressButtonSelected";
                    break;
                }
            }
        },
        showSpecs: function(element) {
            var title = element[element.selectedIndex].innerHTML.toString().trim();
            var productId = element.value;
            var addressableProducts = new Array('1', '2', '3', '9');
            var hasBack = new Array('1', '2', '3', '9', '10', '11');
            var frontTabText = new Array();
            frontTabText['11'] = 'Front / Back';
            frontTabText['default'] = 'Front';
            var backTabText = new Array();
            backTabText['11'] = 'Inside';
            backTabText['default'] = 'Back';

            if (addressableProducts.inArray(productId)) {
                $byId('expressToAddress').style.display = 'block';
            } else {
                $byId('expressToAddress').style.display = 'none';
            }

            if(hasBack.inArray(productId)) {
                $byId('specsBack').style.display = 'block';
            } else {
                $byId('specsBack').style.display = 'none';
            }

            if (productId) {
                if (frontTabText[productId]) {
                    $byId('specsFrontLink').innerHTML = frontTabText[productId];
                } else {
                    $byId('specsFrontLink').innerHTML = frontTabText['default'];
                }
                if (backTabText[productId]) {
                    $byId('specsBackLink').innerHTML = backTabText[productId];
                } else {
                    $byId('specsBackLink').innerHTML = backTabText['default'];
                }
                $byId('specs').style.width = '48%';
                $byId('designSpecs').style.display = 'block';
                $byId('uploadDesignStep').style.display = 'block';
                $byId('designSpecImages').style.display = 'block';
                $byId('stepOneUpload').style.borderRight = '1px solid #C0C0C0';
                window.uploadFormFrame.document.getElementById('productId').value = productId;
                ec.utility.tab.select('designSpecification', 'tab tabs-uploader'); 
                var callback = function() {
                    $$get('/specs-preview-front-' + productId, 'designSpecsPreview');
                }

                if ($byId('expressToAddress').style.display == 'block') {
                    if ($byId('expressToAddressCheckBox').checked == true ) {
                        if($byId('uspsSpecs')) $byId('uspsSpecs').style.display = "block";
                        ec.utility.tab.select('specsBack', 'tab tabs-specsPreview');
                        var callback = function() {
                            $$get('/specs-preview-back-' + productId, 'designSpecsPreview');
                        }
                        $$get('/specs-' + element.value + '', 'specs', callback);
                    } else {
                        if($byId('uspsSpecs')) $byId('uspsSpecs').style.display = "none";
                        ec.utility.tab.select('specsFront', 'tab tabs-specsPreview');
                        $$get('/specs-' + element.value + '', 'specs', callback);
                    }
                } else {
                    if($byId('uspsSpecs')) $byId('uspsSpecs').style.display = "none";
                    ec.utility.tab.select('specsFront', 'tab tabs-specsPreview');
                    $$get('/specs-' + element.value + '', 'specs', callback);
                }
            }
        },
        toggleUspsSpecs: function() {
            var productId = $byId('productSelectionOption').value;
            if ($byId('expressToAddressCheckBox').checked == true ) {
                if($byId('uspsSpecs')) $byId('uspsSpecs').style.display = "block";
                ec.utility.tab.select('specsBack', 'tab tabs-specsPreview');
                $$get('/specs-preview-back-' + productId, 'designSpecsPreview');
            } else {
                if($byId('uspsSpecs')) $byId('uspsSpecs').style.display = "none";
                ec.utility.tab.select('specsFront', 'tab tabs-specsPreview');
                $$get('/specs-preview-front-' + productId, 'designSpecsPreview');
            }
        },
        selectFront: function(designId, productId) {
            _selectDesign(designId, 'front');

            _selectedFront.id = designId;
            _selectedFront.productId = productId;

            if (_selectedFront.id && _selectedBack.id) {
                _showNextButtons();
            }
        },
        selectBack: function(designId, productId) {
            _selectDesign(designId, 'back');

            _selectedBack.id = designId;
            _selectedBack.productId = productId;

            if (_selectedFront.id && _selectedBack.id) {
                _showNextButtons();
            }
        },
        finish: function() {

            if(_selectedFront.productId && _selectedBack.productId) {
                if(_selectedFront.productId !== _selectedBack.productId) {
                    alert("The front and back designs that you selected do not match in size (product type). " +
                        "Please select a front and back that are of the same size (product type).  If you do not "  +
                        "have a front and back that match in size, then you may either click on the button 'Return " + 
                        "to saved and customizable designs' or select 'Choose a previously saved or customzable " +
                        "design' option for either the front or back.");
                    return;
                }
            }

            var frontLater;
            var backLater
            var frontOnly;
            
            ec._dom.onLoad('bodyDiv', 'Please wait...');
            
            if (_selectedFront.id == '990099') {
                _selectedFront.id = "";
                frontLater = true;
            }
            if (_selectedBack.id == '990088') {
                _selectedBack.id = "";
                backLater = true;
            }
            if (_selectedBack.id == '990077') {
                _selectedBack.id = "";
                frontOnly = true;
            }
            try {
                ec.__ga.trackEvent('designFileUploaded');
            } catch (e) {
                if (!window.errors) window.errors = new Array;
                window.errors.push(e);
            }
            var location;
            if (_selectedFront.id && _selectedBack.id) {
                location = "/ec/design/add-to-invoice/frontId/" + _selectedFront.id + "/backId/" + _selectedBack.id + "/frontDesignType/uploaded/backDesignType/uploaded";
                window.location.href = location;
            } else if (_selectedFront.id && frontOnly) {
                location = "/ec/design/add-to-invoice/frontId/" + _selectedFront.id + "/frontDesignType/uploaded";
                window.location.href = location;
            } else if (backLater && !frontLater) {
                var callback = function() {window.location.href = "/ec/design/index/option/myDesigns/change/back"};
                parameters = {'frontId':_selectedFront.id, 'frontDesignType': 'uploaded', 'frontDesignIntention': 'select', 'intention': 'select', 'displaySide': 'front', 'designId':_selectedFront.id};
                $$post('/ec/design/select', null, callback, parameters);
            } else if (frontLater && !backLater) {
                if (typeof ec.design == "object") ec.design.current.finished = "";
                var callback = function() {
                    if (typeof ec.design == "object") ec.design.current.finished = false;
                    window.location.href = "/ec/design/index/option/myDesigns/change/front"}; 
                parameters = {'designId':_selectedBack.id, 'side': 'back', 'backRequired': 'no', 'intention': 'select', 'backDesignType': 'uploaded', 'displaySide': 'back'};
                $$post('/ec/design/select', null, callback, parameters);
            } else if (frontLater && backLater) {
                location = "/ec/design/index/option/myDesigns";
                window.location.href = location;
            }
        },
        updateProduct: function() {
            if ($byId('productSelectionOption').value > 0) {
                $byId('productSelectionOption').onchange();
            }
        }
    }
};

ec.uploader = __uploader();

