/*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$
 
    le.monogram.js
    
    Core monogram functionality.  This file includes objects that are instantiated
    in the product page data preload.  It also contains the main monogram UI
    object.

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*/

/*=================================

    Object to hold monogram options
    styles - array of styles
    locations - array of locations
    
=================================*/
function monoOpts(defaultLocation, styleCodes, locationCodes) {
	this.defaultLocation = defaultLocation;
    this.styleCodes = styleCodes;
    this.locationCodes = locationCodes;
}

/*=======================================

    Object to hold monogram style options
    fullName - full name of the style
    imageURL - location of preview image
    
======================================*/
function monoStyleOpts(fullName, imageURL, reversed, minLength, maxLength) {
    this.fullName = fullName;
    this.imageURL = imageURL;
    this.reversed = reversed;
    this.minLength = minLength;
    this.maxLength = maxLength;
}

/*=======================================================

    Core monogram functionality
    
    num - Buy grid number
    threadColor - thread color code read from the sku
    
=======================================================*/
function monogram(num,theBuyGrid,beginThreadColor) {
	var theBuyGrid = theBuyGrid;
	var threadColor;
    var thisMonogram            = this;
    var baseURL                 = "http://aka.landsend.com/images/monogram/"; // base URL for monogram images
    var applied                 = false;
    var updating                = false;
    var invalidChars            = false;
    
    // for resetting the monogram options
    var thisMonogramCheckbox    = document.getElementById("monogramChooser_prd_" + num).getElementsByTagName("input")[0];
    
    // Containers
    var monogramModule          = document.getElementById("monogramSelector_prd_" + num);
    var theForm                 = document.getElementById("monogramForm_prd_" + num);
    var container               = document.getElementById("monogramContainer_prd_" + num);
    var step0Container          = document.getElementById("monogramStep_0_prd_" + num);
    var step1Container          = document.getElementById("monogramStep_1_prd_" + num);
    var step2Container          = document.getElementById("monogramPageStep_2_prd_" + num);
    var controls                = document.getElementById("monogramLinks_prd_" + num);
    
    // Containers for building options dynamically
    var styleSelectorContainer      = document.getElementById("monogramStyleSelector_prd_" + num);
    var locationSelectorContainer   = document.getElementById("monogramLocationSelector_prd_" + num);
    var wordHintContainer           = document.getElementById("monogramWordHint_prd_" + num).getElementsByTagName("span")[0];
    var multiLineHintContainer      = document.getElementById("monogramMultiLineHint_prd_" + num).getElementsByTagName("span")[0];
    
    // selectors and their options
    var typeSelector            = document.getElementById("monogramType_prd_" + num).getElementsByTagName("input");
    var styleSelector;
    var locationSelector; 
    var locationOptions         = new Array();
    var singleInitialContainer  = document.getElementById("singleInitialSelector_prd_" + num);
    var singleInitialSelector   = singleInitialContainer.getElementsByTagName("input")[0];
    var threeInitialContainer   = document.getElementById("initialsSelector_prd_" + num);
    var threeInitialSelector    = threeInitialContainer.getElementsByTagName("input");
    var wordContainer           = document.getElementById("wordSelector_prd_" + num);
    var wordSelector            = wordContainer.getElementsByTagName("input")[0];
    var multiLineContainer      = document.getElementById("multiLineSelector_prd_" + num);
    var multiLineSelector       = multiLineContainer.getElementsByTagName("input");
    
    // navigation - start counting at zero
    var step0PreviousButton     = document.getElementById("monogramStep1PrevButton_prd_" + num).getElementsByTagName("a")[0];
    var step1PreviousButton     = document.getElementById("monogramStep2PrevButton_prd_" + num).getElementsByTagName("a")[0];
    var step1NextButton         = document.getElementById("monogramStep2NextButton_prd_" + num).getElementsByTagName("a")[0];
    var step2NextButton         = document.getElementById("monogramStep3NextButton_prd_" + num).getElementsByTagName("a")[0];
    
    // navigation image map
    var stepImageMap            = document.getElementById("monogramMapCoordinates_prd_" + num).getElementsByTagName("area");
    
    // monogram controls
    var specialRequests         = controls.getElementsByTagName("a")[0];
    var cancelMonogram          = controls.getElementsByTagName("a")[1];
    var applyMonogramButton     = document.getElementById("monogramApplyButton_prd_" + num).getElementsByTagName("a")[0];
    var updateMonogramButton    = document.getElementById("monogramUpdateButton_prd_" + num).getElementsByTagName("a")[0];
    var startOver               = document.getElementById("monogramStartOver_prd_" + num);
    
    // recap fields to update
    var recap                   = {
                      container : document.getElementById("monogramRecap_prd_" + num),
                           type : document.getElementById("monogramRecapTextType_prd_" + num),
                           text : document.getElementById("monogramRecapTextContent_prd_" + num),
                          style : document.getElementById("monogramRecapStyleContent_prd_" + num),
                       location : document.getElementById("monogramRecapLocationContent_prd_" + num),
                    threadColor : document.getElementById("monogramRecapThreadContent_prd_" + num),
                          links : document.getElementById("monogramRecapLinks_prd_" + num),
                     updateLink : document.getElementById("monogramRecapLinks_prd_" + num).getElementsByTagName("a")[0],
                     removeLink : document.getElementById("monogramRecapLinks_prd_" + num).getElementsByTagName("a")[1],
                        message : document.getElementById("monogramRecapMessage_prd_" + num)
    };
    
    // containers for monogram preview
    var previewWindow           = {
                      container : document.getElementById("monogramPreviewWindow_prd_" + num),
                  singleInitial : document.getElementById("monogramPreviewWindowInitial_prd_" + num),
                  threeInitials : document.getElementById("monogramPreviewWindowThreeInitials_prd_" + num),
                           word : document.getElementById("monogramPreviewWindowWord_prd_" + num),
                      multiLine : document.getElementById("monogramPreviewWindowMultiLine_prd_" + num),
                        message : document.getElementById("monogramPreviewWindowMessage_prd_" + num)
    };
    
    // thread color recap variables for step1
    doDebug("[constructor] Thread color: " + beginThreadColor);
    if (beginThreadColor) {
    	threadColor = beginThreadColor;
        var step1ThreadColorHeader  = document.getElementById("monogramThreadHeader_prd_" + num);
        var step1ThreadColorRecap   = document.getElementById("monogramThreadColor_prd_" + num);
        step1ThreadColorRecap.innerHTML = monoThreadColorAssoc[threadColor];
        show(step1ThreadColorHeader);
        show(step1ThreadColorRecap);
    }
    
    // user's selection
    var selection               = {
                           type : "",
                          style : "",
                       location : "",
                         siText : "",
                       wordText : "",
                multiInitialArr : [],
                   multiLineArr : [],
                          price : 0,
                           done : false
    };
    
    var locationOptions;
    
    // error and info message containers
    var mainErrorContainer          = document.getElementById("monogramError_prd_" + num);
    var typeErrorContainer          = document.getElementById("monogramTypeError_prd_" + num);
    var styleErrorContainer         = document.getElementById("monogramStyleError_prd_" + num);
    var locationErrorContainer      = document.getElementById("monogramLocationError_prd_" + num);
    var singleInitialErrorContainer = document.getElementById("monogramSingleInitialError_prd_" + num);
    var threeInitialsErrorContainer = document.getElementById("monogramInitialsError_prd_" + num);
    var wordErrorContainer          = document.getElementById("monogramWordError_prd_" + num);
    var multiLineErrorContainer     = document.getElementById("monogramMultiLineError_prd_" + num);
    
    // utility variables
    var styleClicked                = false;
    var modifyFirstRunThrough       = false;
    var isEngraving					= false;
    
    // public variables
    this.selection              = selection;
    this.applied                = applied;
    
    this.registerEvents = function() {
        step0PreviousButton.onclick     = this.goToStep0;
        step1NextButton.onclick         = this.goToStep1;
        step1PreviousButton.onclick     = this.goToStep1;
        step2NextButton.onclick         = this.goToStep2;
        specialRequests.onclick         = this.specialRequestsPopup;
        cancelMonogram.onclick          = this.removeMonogram;
        applyMonogramButton.onclick     = this.applyMonogram;
        updateMonogramButton.onclick    = this.applyMonogram;
        recap.updateLink.onclick        = this.goToStep0;
        recap.removeLink.onclick        = this.removeMonogram;
        startOver.onclick               = this.goToStep0;
        stepImageMap[0].onclick         = this.goToStep0;
        stepImageMap[1].onclick         = this.goToStep1;
        stepImageMap[2].onclick         = this.goToStep2;
        
        this.buildTypeSelector();
        this.buildInitialSelector();
        this.buildWordSelector();
        this.buildThreeInitialSelector();
        this.buildMultiLineSelector();

    };
    
    this.buildTypeSelector = function() {
        var i;
        
        for (i = 0; i < typeSelector.length; i++) {
            if (typeSelector[i].checked) {
                selection.type = typeSelector[i].value;
            }
            
            typeSelector[i].onclick = this.typeSelect;
        }
        styleSelector = document.getElementById("monogramStyleSelector_prd_" + num).getElementsByTagName("input");
        locationSelector = document.getElementById("monogramLocationSelector_prd_" + num).getElementsByTagName("select")[0];
        thisMonogram.buildRecap();
    };
    
    this.buildStyleSelector = function() {
        var i;
        
        for (i = 0; i < styleSelector.length; i++) {
            if (styleSelector[i].value == selection.style) {
                styleSelector[i].checked = "checked";
            }

            styleSelector[i].onclick = this.styleSelect;
        }
        thisMonogram.buildRecap();
    };
    
    this.buildLocationSelector = function() {
    	if (typeof(locationSelector) == "undefined" || locationSelector == null) {
    		return;
    	}
    	//selection.location = locationSelector.options[i].value;
        var locOptArr = locationSelector.getElementsByTagName("option");
        for (var i = 0; i < locOptArr.length; i++) {
            locationOptions[i] = locOptArr[i].value;
        } 
		this.selectLocation(selection.location);
        doDebug("[monogram.buildLocationSelector] " + selection.location + " is the monogram location.");
        locationSelector.onchange = this.locationSelect;
    };
    
    this.buildInitialSelector = function() {
        if (singleInitialSelector.value) {
            selection.siText = singleInitialSelector.value.slice(0,1).toUpperCase();
            doDebug("[buildInitialSelector] You typed: " + selection.siText);
            thisMonogram.singleInitialPreview(selection.style, selection.siText);
            selection.done = true;
            thisMonogram.buildRecap();
        }
        singleInitialSelector.onkeyup = this.singleInitialSelect;
    };
    
    this.buildWordSelector = function() {
        if (wordSelector.value) {
            selection.wordText = wordSelector.value.slice(0, monoStyleAssoc[num][selection.style].maxLength);
            selection.done = true;
        }
        wordSelector.onkeyup = this.wordSelect;
    };
    
    this.buildThreeInitialSelector = function() {
        var i;
                
        for (i = 0; i < threeInitialSelector.length; i++) {
            var linePosition = parseInt(threeInitialSelector[i].id.split("_")[3]);
            
            if (threeInitialSelector[i].value) {
                selection.multiInitialArr[linePosition] = threeInitialSelector[i].value.slice(0,1).toUpperCase();
                thisMonogram.threeInitialPreview(selection.style, selection.multiInitialArr[linePosition], linePosition);
                selection.done = true;
            }
            
            doDebug("[buildThreeInitialSelector] Your monogram will be: " + selection.multiInitialArr.join(","));
            
            threeInitialSelector[i].onkeyup = this.threeInitialSelect;
        }
        thisMonogram.buildRecap();
    };
    
    this.buildMultiLineSelector = function() {
        var i;
        
        for (i = 0; i < multiLineSelector.length; i++) {
            var linePosition = parseInt(multiLineSelector[i].id.split("_")[3]);
            
            if (multiLineSelector[i].value) {
                selection.multiLineArr[linePosition] = multiLineSelector[i].value.slice(0,parseInt(monogramMultiLineLength));
                selection.done = true;
            }
            
            doDebug("[buildMultiLineSelector] Your monogram will be: " + selection.multiLineArr.join("<br />"));
            
            multiLineSelector[i].onkeyup = thisMonogram.multiLineSelect;
        }
        thisMonogram.buildRecap();
    };
    
    this.typeSelect = function() {
        if (this.checked) {
            selection.type = this.value;
            doDebug("[monogram.typeSelect] You chose " + selection.type + " type of monogramming.");
        }
        styleSelector = document.getElementById("monogramStyleSelector_prd_" + num).getElementsByTagName("input");
        locationSelector = document.getElementById("monogramLocationSelector_prd_" + num).getElementsByTagName("select")[0];
        thisMonogram.buildRecap();
        document.getElementById("monogramInitialsError_prd_" + num).className = document.getElementById("monogramInitialsError_prd_" + num).className.replace(" errorHiLight", "");
    };
    
    this.setThreadColor = function(color){
    	threadColor = color;
 		if (threadColor != null)  {   	
	        var step1ThreadColorRecap   = document.getElementById("monogramThreadColor_prd_" + num);
	        step1ThreadColorRecap.innerHTML = monoThreadColorAssoc[threadColor];
		    recap.threadColor.innerHTML = monoThreadColorAssoc[threadColor];
	    }
    };
    
    this.styleSelect = function() {
        if (this.checked) {
            selection.style = this.value;
            styleClicked = true;
            doDebug("[monogram.styleSelect] You chose " + selection.style + " as the font.");
        }
        hide(styleErrorContainer);
        thisMonogram.showPreview(selection.type);
        thisMonogram.buildRecap();
        document.getElementById("monogramStyleHeader_prd_" + num).className = document.getElementById("monogramStyleHeader_prd_" + num).className.replace(" errorHiLight", "");
    };
    
    this.locationSelect = function() {
		var idx = this.selectedIndex;
        selection.location = locationOptions[parseInt(idx)];
 	    doDebug("[monogram.locationSelect] You chose " + selection.location + " as the monogram location.");
        hide(locationErrorContainer);
        thisMonogram.buildRecap();
        document.getElementById("monogramLocationHeader_prd_" + num).className = document.getElementById("monogramLocationHeader_prd_" + num).className.replace(" errorHiLight", "");
    };
    
    this.singleInitialSelect = function(event) {
		var e = event || window.event;
 		var keyPressed = e.keyCode;
        if (thisMonogram.checkCharacters(keyPressed, this.value.slice(0,1), 1) === true) {
            selection.siText = this.value.slice(0,1).toUpperCase();
            doDebug("[singleInitialSelect] You typed: " + selection.siText);
            thisMonogram.singleInitialPreview(selection.style, selection.siText);
            selection.done = true;
            thisMonogram.buildRecap();
            hide(singleInitialErrorContainer);
            document.getElementById("monogramSingleInitialHeader_prd_" + num).className = document.getElementById("monogramSingleInitialHeader_prd_" + num).className.replace(" errorHiLight", "");
        } else {
            this.select();
            showErrorPopup(messages.error[14].getMessageText(true));
            singleInitialErrorContainer.innerHTML = messages.error[14].getMessageText();
            show(singleInitialErrorContainer);
        }
    };
    
    this.threeInitialSelect = function(event) {
       // start counting at 0
        var linePosition = parseInt(this.id.split("_")[3]);
        doDebug("[threeInitialSelect] The line position is " + linePosition);
		var e = event || window.event;
 		var keyPressed = e.keyCode;
		if (thisMonogram.checkCharacters(keyPressed, this.value.slice(0,1), 1) === true) {
            selection.multiInitialArr[linePosition] = this.value.slice(0,1).toUpperCase();
            thisMonogram.threeInitialPreview(selection.style, selection.multiInitialArr[linePosition], linePosition);
            
            doDebug("[threeInitialSelect] You typed: " + selection.multiInitialArr[linePosition] + " at line " + linePosition);
            doDebug("[threeInitialSelect] Your monogram will be: " + selection.multiInitialArr.join(","));
            selection.done = true;
            thisMonogram.buildRecap();
            hide(threeInitialsErrorContainer);
            document.getElementById("monogramInitialsError_prd_" + num).className = document.getElementById("monogramInitialsError_prd_" + num).className.replace(" errorHiLight", "");;
        } else {
            this.select();
            showErrorPopup(messages.error[14].getMessageText(true));
            threeInitialsErrorContainer.innerHTML = messages.error[14].getMessageText();
            show(threeInitialsErrorContainer);
        }
    };
   
    this.wordSelect = function(event) {
		var e = event || window.event;
 		var keyPressed = e.keyCode;
        if (thisMonogram.checkCharacters(keyPressed, this.value.slice(0, parseInt(monogramWordLength)), 2) === true) {
            selection.wordText = this.value.slice(0, parseInt(monogramWordLength));
            doDebug("[wordSelect] You typed: " + selection.wordText);
            selection.done = true;
            thisMonogram.buildRecap();
            hide(wordErrorContainer);
            document.getElementById("monogramWordHeader_prd_" + num).className = document.getElementById("monogramWordHeader_prd_" + num).className.replace(" errorHiLight", "");
        } else {
            showErrorPopup(messages.error[15].getMessageText(true));
            wordErrorContainer.innerHTML = messages.error[15].getMessageText();
            show(wordErrorContainer);
            selection.done = false;
        }
    };
    
    this.multiLineSelect = function(event) {
        // start counting at 0
        var linePosition = parseInt(this.id.split("_")[3]);
        doDebug("[multiLineSelect] The line position is " + linePosition);
		var e = event || window.event;
 		var keyPressed = e.keyCode;
        if (thisMonogram.checkCharacters(keyPressed, this.value.slice(0,parseInt(monogramMultiLineLength)), 2) === true) {
            selection.multiLineArr[linePosition] = this.value.slice(0,parseInt(monogramMultiLineLength));
            doDebug("[multiLineSelect] You typed: " + selection.multiLineArr[linePosition] + " at line " + linePosition);
            doDebug("[multiLineSelect] Your monogram will be: " + selection.multiLineArr.join(","));
            selection.done = true;
            thisMonogram.buildRecap();
            hide(multiLineErrorContainer);
            document.getElementById("monogramMultiLineHeader_prd_" + num).className = document.getElementById("monogramMultiLineHeader_prd_" + num).className.replace(" errorHiLight", "");
        } else {
            showErrorPopup(messages.error[14].getMessageText(true));
            multiLineErrorContainer.innerHTML = messages.error[14].getMessageText();
            show(multiLineErrorContainer);
        }
    };
    
    this.selectType = function(typeCode) {
        var i;
        for (i = 0; i < typeSelector.length; i++) {
            if (typeSelector[i].value == typeCode) {
                typeSelector[i].checked = "checked";
                selection.type = typeSelector[i].value;
                doDebug("[selectType] Monogram type: " + selection.type);
            }
        }
    };
    
    this.selectStyle = function(styleCode) {
        var i;
        for (i = 0; i < styleSelector.length; i++) {
            if (styleSelector[i].value == styleCode) {
                styleSelector[i].checked = "checked";
                selection.style = styleSelector[i].value;
                doDebug("[selectStyle] Monogram style: " + selection.style);
                
            }
        }
        if (selection.style == null || selection.style == "" || selection.style == undefined) {
            selection.style = styleCode;
        }
        styleClicked = true;
        modifyFirstRunThrough = true;
    };
    
    this.selectLocation = function(locationCode) {
        if (locationSelector != null) {
            var i;
            for (i = 0; i < locationSelector.options.length; i++) {
                if (locationSelector.options[i].value == locationCode) {
                    locationSelector.options[i].selected = "selected";
                    selection.location = locationSelector.options[i].value;
                    doDebug("[selectLocation] Monogram location: " + selection.location);
                }
            }
        }
        if (selection.location == null || selection.location == "" || selection.location == undefined) {
            selection.location = locationCode;
        }
    };
    
    this.selectText = function(diffSelObj) {
        var i;
        
        switch (diffSelObj.selection.type) {
            case "Single Initial":
                selection.siText = diffSelObj.selection.siText;
                doDebug("[selectText] Single Initial Text: " + selection.siText);
                singleInitialSelector.value = selection.siText;
                thisMonogram.singleInitialPreview(selection.style, selection.siText);
            break;
            case "Initials":
                selection.multiInitialArr = diffSelObj.selection.multiInitialArr;
                doDebug("[selectText] Initials Text: " + selection.multiInitialArr.join(","));
                for (i = 0; i < threeInitialSelector.length; i++) {
                    threeInitialSelector[i].value = diffSelObj.selection.multiInitialArr[i];
                    thisMonogram.threeInitialPreview(selection.style, selection.multiInitialArr[i], i);
                }
            break;
            case "Word":
                selection.wordText = diffSelObj.selection.wordText;
                doDebug("[selectText] Word Text: " + selection.wordText);
                wordSelector.value = selection.wordText;
                thisMonogram.showPreview("Word");
            break;
            case "Multi-Line":
                selection.multiLineArr = diffSelObj.selection.multiLineArr;
                doDebug("[selectText] Multi=line Text: " + selection.multiLineArr.join(","));
                for (i = 0; i < multiLineSelector.length; i++) {
                    multiLineSelector[i].value = diffSelObj.selection.multiLineArr[i];
                }
                thisMonogram.showPreview("Multi-Line");
            break;
        }
        selection.done = true;
        thisMonogram.buildRecap();
    };
    
    this.typePreviewSwitcher = function() {
        try {
            switch (selection.type) {
                case "Single Initial":
                    thisMonogram.generateStyleOptions("Single Initial");
                    thisMonogram.generateLocationOptions("Single Initial");
                    thisMonogram.showPreview("Single Initial");
                    doDebug("[typeSelect] Single initial preview to be shown.");
                    break;
                case "Initials":
                    thisMonogram.generateStyleOptions("Initials");
                    thisMonogram.generateLocationOptions("Initials");
                    thisMonogram.showPreview("Initials");
                    doDebug("[typeSelect] Three initials preview to be shown.");
                    break;
                case "Word":
                    thisMonogram.generateStyleOptions("Word");
                    thisMonogram.generateLocationOptions("Word");
                    //thisMonogram.showPreview("Word");
                    doDebug("[typeSelect] Word preview to be shown.");
                    break;
                case "Multi-Line":
                    thisMonogram.generateStyleOptions("Multi-Line");
                    thisMonogram.generateLocationOptions("Multi-Line");
                    //thisMonogram.showPreview("Multi-Line");
                    doDebug("[typeSelect] Multi-line initial preview to be shown.");
                    break;
            }
        } catch (err) {
            doDebug("[typePreviewSwitcher] " + err);
        }

        thisMonogram.buildLocationSelector();
        thisMonogram.buildStyleSelector();
    };
    
    this.generateStyleOptions = function(style) {
        var styleOpts = monogramOptions[num][style].styleCodes;
        var i;
        
        /*
            Check to see if the container matches what is going to be generated.  If it matches,
            do nothing.  If it doesn't match, it means that the options are different than what
            they were before, and a new style needs selected.  Set styleClicked = false.
        */
        var oldContainer = styleSelectorContainer.innerHTML;
        
        styleSelectorContainer.innerHTML = "";
        for (i = 0; i < styleOpts.length; i++) {
            if (!monoStyleAssoc[num][styleOpts[i]].fullName.match(/Engraving/)) {
            	isEngraving = false;
           		 styleSelectorContainer.innerHTML +=
                "<div id=\"monogramStyleOption_opt_" + i + "_prd_" + num + "\" class=\"monogramStyleOption\">" + 
                "<input name=\"monoStyle\" value=\"" + styleOpts[i] + "\" type=\"radio\" /> " + 
                "<span class=\"vasContentText\">" + monoStyleAssoc[num][styleOpts[i]].fullName + "</span> " +
                "<span><img src=\"" + monoStyleAssoc[num][styleOpts[i]].imageURL + "\" alt=\"" + monoStyleAssoc[num][styleOpts[i]].fullName + "\" /></span>" + 
                "</div>";
            } else {
            	isEngraving = true;
				styleSelectorContainer.innerHTML +=            
                "<div id=\"monogramStyleOption_opt_" + i + "_prd_" + num + "\" class=\"monogramStyleOption\">" + 
                "<input name=\"monoStyle\" value=\"" + styleOpts[i] + "\" type=\"radio\" /> " + 
                "<span class=\"vasContentText\">" + monoStyleAssoc[num][styleOpts[i]].fullName + "</span> " +
                "<span>&nbsp;</span>" + 
                "</div>";
            }
        }
        
        if (oldContainer != styleSelectorContainer.innerHTML && modifyFirstRunThrough == false) {
            styleClicked = false;
        } else {
            styleClicked = true;
        }
        modifyFirstRunThrough = false;
    };
    
    this.generateLocationOptions = function(style) {
        locOpts = monogramOptions[num][style].locationCodes;
		var defaultLocation = monogramOptions[num][style].defaultLocation;
		var locHeader = document.getElementById("monogramLocationHeader_prd_" + num);
        locationSelectorContainer.innerHTML = "";

 		var orderedLocationOptions = new Array(locOpts.length);
		var inc = 1;
		for (var i=0;i<locOpts.length;i++) {
			if (locOpts[i] === defaultLocation) {
				orderedLocationOptions[0] = locOpts[i];
				inc=0;
			}
			else {
				orderedLocationOptions[i+inc] = locOpts[i];
			}
		}
		if (inc == 1) { // bad data - default location isn't in list of locations, remove null first option
			orderedLocationOptions.splice(0,1);
		}
		if (orderedLocationOptions.length == 1) {
        	locHeader.innerHTML = "Location:";
        	locationSelectorContainer.innerHTML=monoLocAssoc[orderedLocationOptions[0]];
        	selection.location = orderedLocationOptions[0];
        } else {
        	locHeader.innerHTML = "Select location:";
	        locationSelector = document.createElement("select");
	        locationSelectorContainer.appendChild(locationSelector);
	        var opt = document.createElement("option");
	        opt.value = "";
	        locationSelector.appendChild(opt);
	        locationSelector.options[0].text = "Select";
	        for (var i = 0; i < orderedLocationOptions.length; i++) {
            	var opt = document.createElement("option");
            	opt.value = orderedLocationOptions[i];
            	locationSelector.appendChild(opt);
            	locationSelector.options[locationSelector.length-1].text = monoLocAssoc[orderedLocationOptions[i]];
        	}
		}
    };
    
    this.destroyLocationOptions = function() {
        locationSelectorContainer.getElementsByTagName("select").innerHTML = "";
    }

    this.specialRequestsPopup = function() {
        LE_popup(this.href);
        return false;
    };
    
    this.removeMonogram = function() {
        hide(mainErrorContainer);
        monogramModule.getElementsByTagName("span")[0].className = monogramModule.getElementsByTagName("span")[0].className.replace(" errorHiLight", "");
        selection = {};
        selection.price = 0;
        thisMonogramCheckbox.checked = false;
        thisMonogram.applied = false;
        theBuyGrid.selection.monogrammed = false;
        theBuyGrid.selection.monogram.price= 0;
        theBuyGrid.selection.getExtendedPrice();
        theBuyGrid.buildRecap();
        multiHide([step0Container, step1Container, step2Container, recap.container, controls]);
        recap.message.innerHTML = "The monogram has been removed.";
        if (applied === true) {
            show(recap.message);
        }
        // if we have an error message for having a monogram and a school logo - hide it.
        if (theBuyGrid.selection.schoolUniformmed && 
        	(theBuyGrid.selection.schoolUniform.logo != "" && theBuyGrid.selection.schoolUniform.logo != "-1")) {
        	multiHide([theBuyGrid.schoolUni.schoolUniformError,monogramModule]);
        	recap.message.innerHTML = "";
        }
        theForm.reset();
        doDebug("[removeMonogram] Monogram form has been reset.");
        return false;
    };
    
    this.buildRecap = function() {
        recap.type.innerHTML = selection.type + ": ";
        switch (selection.type) {
            case "Single Initial":
                recap.text.innerHTML = selection.siText;
            break;
            case "Initials":
                recap.text.innerHTML = selection.multiInitialArr.join("");
            break;
            case "Multi-Line":
                recap.text.innerHTML = selection.multiLineArr.join("<br />");
            break;
            default:
                recap.text.innerHTML = selection.wordText;
            break;
        }
        if (selection.style != "" && selection.style != null) {
            recap.style.innerHTML = monoStyleAssoc[num][selection.style].fullName;
        }
        recap.location.innerHTML = monoLocAssoc[selection.location];
        if (threadColor) {
            recap.threadColor.innerHTML = monoThreadColorAssoc[threadColor];
        }
    };
        
    this.singleInitialPreview = function(typeCode, letter) {
        letter = letter.toLowerCase();
        typeCode = typeCode.toLowerCase();
        var imageURL = baseURL + typeCode + "/" + typeCode + "_2_" + letter + ".gif";
        var previewImage = previewWindow.singleInitial.getElementsByTagName("img")[0];
        
        if (previewImage !== null) {
            previewImage.src = imageURL;
        }
        
        if (letter == "" || !letter.match(/^[a-z]*$/i)) {
            previewImage.src = "http://aka.landsend.com/images/clear.gif";
        }
    };
    
    this.threeInitialPreview = function(typeCode, letter, position) {
        if (monoStyleAssoc[num][typeCode].reversed == true && position == 1) {
            position = 2;
        } else if (monoStyleAssoc[num][typeCode].reversed == true && position == 2) {
            position = 1;
        }
        
        var urlPos = parseInt(position) + 1; // the image counting is one off of how I count
                
        var initialHolder = previewWindow.threeInitials.getElementsByTagName("img");
        letter = letter.toLowerCase();
        typeCode = typeCode.toLowerCase();
        var imageURL = baseURL + typeCode + "/" + typeCode + "_" + urlPos + "_" + letter + ".gif";

        if (letter == "" || thisMonogram.checkCharacters(0,letter, 1) == false) {
            imageURL = "http://aka.landsend.com/images/clear.gif";
        }
        
        doDebug("[threeInitialLivePreview] typeCode: " + typeCode);
        doDebug("[threeInitialLivePreview] letter: " + letter);
        doDebug("[threeInitialLivePreview] position: " + position);
        doDebug("[threeInitialLivePreview] Image URL: " + imageURL);
        
        if (initialHolder !== null) {
            show(previewWindow.message);
            initialHolder[parseInt(position)].src = imageURL;
            hide(previewWindow.message);
        }
    };
    

    this.checkCharacters = function(keyPressed, str, monoType) {
		// ignore the following keys
		if (keyPressed == 8 ||			// BACKSPACE
			keyPressed == 9 ||			// TAB
			keyPressed == 13||			// ENTER
			keyPressed == 16 ||			// SHIFT
			keyPressed == 20 ||			// CAPSLOCK
			keyPressed==46				// DELETE
			) 			
		{
			return true;
		}
       	if (monoType == 1) {
			var charRegEx = /^[A-Za-z]/;
   		} else if (monoType == 2) {
    	    var charRegEx = /^[A-Za-z0-9#\-\s\.,\'\/&]*$/
	    } else {
	    	return false;
       	}
   		if (str.match(charRegEx) !== null) {
            return true;
   		} else {
 			return false;
 		}
    };

    /*/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
    
        Navigation and other show/hide functions
        
    /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\*/
    
    this.goToStep0 = function() {
        thisMonogram.destroyLocationOptions();
        multiHide([step1Container, step2Container, recap.container, locationSelector]);
        multiShow([step0Container, controls]);
        return false;
    };
    
    this.goToStep1 = function() {
        thisMonogram.typePreviewSwitcher();
        multiHide([step0Container, step2Container]);
        multiShow([step1Container, locationSelector]);
        return false;
    };
    
    this.checkIfStyleChecked = function() {
        var opts = styleSelectorContainer.getElementsByTagName("input");
        var isChecked;
        var i;
        
        if (opts.length < 1) {
            return false;
        }
        
        for (i = 0; i < opts.length; i++) {
            if (opts[i].checked) {
                thisMonogram.styleSelect();
                return true;
            }
        }
        return false;
    }
    
    this.goToStep2 = function() {
   
        if (selection.style != "" && selection.style != null && thisMonogram.checkIfStyleChecked() === true	&&	selection.location != "" && selection.location != null) 
        {
            var i;
            var hideArray = [singleInitialContainer, threeInitialContainer, wordContainer, multiLineContainer];
            multiHide([step0Container, step1Container]);
            show(step2Container);
            
            switch (selection.type) {
                case "Single Initial":
                    multiHide(hideArray);
                    thisMonogram.singleInitialPreview(selection.style, singleInitialSelector.value);
                    show(singleInitialContainer);
                    break;
                case "Initials":
                    multiHide(hideArray);
                    for (i = 0; i < threeInitialSelector.length; i++) {
                        thisMonogram.threeInitialPreview(selection.style, threeInitialSelector[i].value, i);
                    }
                    show(threeInitialContainer);
                    break;
                case "Word":
                    multiHide(hideArray);
                    show(wordContainer);
                    break;
                case "Multi-Line":
                    multiHide(hideArray);
                    show(multiLineContainer);
                    break;
            }
            
            if (updating === true) {
                hide(document.getElementById("monogramApplyButton_prd_" + num));
                show(document.getElementById("monogramUpdateButton_prd_" + num));
            } else {
                show(document.getElementById("monogramApplyButton_prd_" + num));
                hide(document.getElementById("monogramUpdateButton_prd_" + num));
            }
        } else {
        	if (selection.style == "" || selection.style == null || thisMonogram.checkIfStyleChecked() === false) {
  	          	showErrorPopup(messages.error[10].getMessageText(true));
            	styleErrorContainer.innerHTML = messages.error[10].getMessageText();
            	document.getElementById("monogramStyleHeader_prd_" + num).className += " errorHiLight";
            	show(styleErrorContainer);
        	} 
        	else {
        	    showErrorPopup(messages.error[37].getMessageText(true));
	          	locationErrorContainer.innerHTML = messages.error[37].getMessageText();
          		document.getElementById("monogramLocationHeader_prd_" + num).className += " errorHiLight";
           		show(locationErrorContainer);
 			}
        }
        return false;
    };
    
    this.showPreview = function(previewType) {
        var imageURL;
        var previewImage;
        
        if (isEngraving == true) {
        	hide(previewWindow.container);
        	
        	switch (previewType){
            case "Word":
                wordHintContainer.innerHTML = "( up to " + monoStyleAssoc[num][selection.style].maxLength + " characters per line )";
                wordSelector.size = parseInt(monoStyleAssoc[num][selection.style].maxLength);
                wordSelector.maxLength = parseInt(monoStyleAssoc[num][selection.style].maxLength);
                break;
            case "Multi-Line":
                var i;
                multiLineHintContainer.innerHTML = "( up to " + monoStyleAssoc[num][selection.style].maxLength + " characters per line )";
                
                for (i = 0; i < multiLineSelector.length; i++) {
                    multiLineSelector[i].size = parseInt(monoStyleAssoc[num][selection.style].maxLength);
                    multiLineSelector[i].maxLength = parseInt(monoStyleAssoc[num][selection.style].maxLength);
                }
                break;
            default:
                break;        	
        	
        	}
        	
        	return;
        }
        
        show(previewWindow.container);
        switch (previewType) {
            case "Single Initial":
                multiHide([previewWindow.threeInitials, previewWindow.word, previewWindow.multiLine]);
                show(previewWindow.singleInitial);
                break;
            case "Initials":
                multiHide([previewWindow.singleInitial, previewWindow.word, previewWindow.multiLine]);
                show(previewWindow.threeInitials);
                break;
            case "Word":
                multiHide([previewWindow.singleInitial, previewWindow.threeInitials, previewWindow.multiLine]);
                wordHintContainer.innerHTML = "( up to " + monoStyleAssoc[num][selection.style].maxLength + " characters per line )";
                show(previewWindow.word);
                imageURL = baseURL + selection.style.toLowerCase() + "/" + selection.style.toLowerCase() + "_sample_name.gif";
                wordSelector.size = parseInt(monoStyleAssoc[num][selection.style].maxLength);
                wordSelector.maxLength = parseInt(monoStyleAssoc[num][selection.style].maxLength);
                previewImage = previewWindow.word.getElementsByTagName("img")[0];
                doDebug("[showPreview(\"word\")] Image URL: " + imageURL);
                if (previewImage !== null) {
                    previewImage.src = imageURL;
                }
                break;
            case "Multi-Line":
                var i;
                
                multiHide([previewWindow.singleInitial, previewWindow.threeInitials, previewWindow.word]);
                multiLineHintContainer.innerHTML = "( up to " + monoStyleAssoc[num][selection.style].maxLength + " characters per line )";
                
                for (i = 0; i < multiLineSelector.length; i++) {
                    multiLineSelector[i].size = parseInt(monoStyleAssoc[num][selection.style].maxLength);
                    multiLineSelector[i].maxLength = parseInt(monoStyleAssoc[num][selection.style].maxLength);
                }
                
                show(previewWindow.multiLine);
                imageURL = baseURL + selection.style.toLowerCase() + "/" + selection.style.toLowerCase() + "_sample_name.gif";
                previewImage = previewWindow.multiLine.getElementsByTagName("img")[0];
                doDebug("[showPreview(\"multiLine\")] Image URL: " + imageURL);
                if (previewImage !== null) {
                    previewImage.src = imageURL;
                }
                break;
            default:
                break;
        }
    };
    
    this.checkLength = function() {
        if (selection.type == "Initials") {
            // handle the length of the monogram initials
            if (parseInt(selection.multiInitialArr.join("").length) < 2) {
                showErrorPopup(messages.error[18].getMessageText(true));
                show(threeInitialsErrorContainer);
                threeInitialsErrorContainer.innerHTML = messages.error[18].getMessageText();
                document.getElementById("monogramInitialsError_prd_" + num).className += " errorHiLight";
                return false;
            }
            
            if (parseInt(selection.multiInitialArr.join("").length) > 3) {
                showErrorPopup(messages.error[17].getMessageText(true,monoStyleAssoc[num][selection.style].maxLength));
                show(threeInitialsErrorContainer);
                threeInitialsErrorContainer.innerHTML = messages.error[17].getMessageText(false,monoStyleAssoc[num][selection.style].maxLength);
                document.getElementById("monogramInitialsError_prd_" + num).className += " errorHiLight";
                return false;
            }
        } else {
        	if (selection.type == "Word") {
	        	if (selection.wordText.length === 0) {
		            showErrorPopup(messages.error[11].getMessageText(true));
            		show(wordErrorContainer);
            		wordErrorContainer.innerHTML = messages.error[11].getMessageText();
            		document.getElementById("monogramWordHeader_prd_" + num).className += " errorHiLight";
            		return false;
            	} 
            } else {
            	if (selection.type == "Multi-Line") {
            		text = selection.multiLineArr[0] + selection.multiLineArr[1] + selection.multiLineArr[2];
		        	if (text.length === 0) {
		            	showErrorPopup(messages.error[11].getMessageText(true));
            			show(multiLineErrorContainer);
            			wordErrorContainer.innerHTML = messages.error[11].getMessageText();
            			document.getElementById("monogramMultiLineHeader_prd_" + num).className += " errorHiLight";
            			return false;
					}
            	} else {
         			if (selection.siText.length === 0) {
		            	showErrorPopup(messages.error[11].getMessageText(true));
           				show(singleInitialErrorContainer);
            			singleInitialErrorContainer.innerHTML = messages.error[11].getMessageText();
            			document.getElementById("monogramSingleInitialHeader_prd_" + num).className += " errorHiLight";
           				return false;
            		}
            	}
            }
        }
        return true;
    };
    
    this.applyMonogram = function() {
        if (selection.done === true && thisMonogram.checkLength() === true) {
            multiHide([step0Container, step1Container, step2Container, controls]);
            multiShow([recap.container, recap.links]);
            applied = true;
            updating = true;
            selection.price = thisMonogramCheckbox.value;
            doDebug("[applyMonogram] Monogram Price: " + selection.price);
            theBuyGrid.setMonogramPrice();
            hide(mainErrorContainer);
            thisMonogram.applied = true;
            monogramModule.getElementsByTagName("span")[0].className = monogramModule.getElementsByTagName("span")[0].className.replace(" errorHiLight", "");
        } else if (invalidChars === true) {
            showErrorPopup(messages.error[15].getMessageText(true));
            mainErrorContainer.innerHTML = messages.error[15].getMessageText();
            document.getElementById("monogramSingleInitialHeader_prd_" + num).className += " errorHiLight";
            document.getElementById("monogramInitialsError_prd_" + num).className += " errorHiLight";
            document.getElementById("monogramWordHeader_prd_" + num).className += " errorHiLight";
            document.getElementById("monogramMultiLineHeader_prd_" + num).className += " errorHiLight";
            show(mainErrorContainer);
        } else if (selection.done === false) {
            showErrorPopup(messages.error[11].getMessageText(true));
            singleInitialErrorContainer.innerHTML = messages.error[11].getMessageText();
            threeInitialsErrorContainer.innerHTML = messages.error[11].getMessageText();
            wordErrorContainer.innerHTML = messages.error[11].getMessageText();
            multiLineErrorContainer.innerHTML = messages.error[11].getMessageText();
            multiShow([singleInitialErrorContainer, threeInitialsErrorContainer, wordErrorContainer, multiLineErrorContainer]);
            document.getElementById("monogramSingleInitialHeader_prd_" + num).className += " errorHiLight";
            document.getElementById("monogramInitialsError_prd_" + num).className += " errorHiLight";
            document.getElementById("monogramWordHeader_prd_" + num).className += " errorHiLight";
            document.getElementById("monogramMultiLineHeader_prd_" + num).className += " errorHiLight";
        }

        return false;
    };
    
    this.registerEvents();
    multiShow([container, step0Container, controls]);
    hide(recap.message);
    hide(previewWindow.message);
}
