/*$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

    le.buy.js - core objects for purchasing an item

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$*/

/*=================================================

    Global array used with every instance of a sku.

=================================================*/

var monthArray = new Array();
monthArray[0] = ["", ""];
monthArray[1] = ["January", "Jan."];
monthArray[2] = ["February", "Feb."];
monthArray[3] = ["March", "Mar."];
monthArray[4] = ["April", "Apr."];
monthArray[5] = ["May", "May"];
monthArray[6] = ["June", "Jun."];
monthArray[7] = ["July", "Jul."];
monthArray[8] = ["August", "Aug."];
monthArray[9] = ["September", "Sept."];
monthArray[10] = ["October", "Oct."];
monthArray[11] = ["November", "Nov."];
monthArray[12] = ["December", "Dec."];

// Used to make sure that newly inserted buy grid is accounted for 
// in the array that maintains that order (as they appear on the page).
// This function is dependent on the addBuyGridToPage function and the 
// global variable - previouslySelectedBuyGridKey
function insertOrderedBuyGridKey(key){
	var i;
	if(previouslySelectedBuyGridKey == null){
		buyGridKeyOrder.push(key);
	}else{
		var length = buyGridKeyOrder.length;
		for(i = 0;i < length;i++){
			if(buyGridKeyOrder[i] == previouslySelectedBuyGridKey){
				buyGridKeyOrder.splice(i,0,key);
				break;
			}
		}
	}
}

function errorHandler(){
	 showErrorPopup(messages.error[33].getMessageText(true));
}

var buyGridsAlreadyRequested = new Object();

function flipBuyGrids(newBuyGridKey,currentBuyGridNumber,currentBuyGrid){
    var funcName = "[flipBuyGrids] ";
	currentBuyGridUrl = newBuyGridKey;

	var url;
	doDebug(funcName+newBuyGridKey);
	if(multiItem){
		url = hostname + newBuyGridKey + "?multiItem=true";
	}else{
		url = hostname + newBuyGridKey;
	}
	
		try {
			// load the new buy grid and then flip them
			if(sA[newBuyGridKey] == null && ! buyGridsAlreadyRequested[newBuyGridKey]){
				buyGridsAlreadyRequested[newBuyGridKey] = true;
				var flipper = new Flipper();
				flipper.addBuyGridToPage.currentBuyGridNumber = currentBuyGridNumber;
				flipper.addBuyGridToPage.newBuyGridKey = newBuyGridKey;
				flipper.addBuyGridToPage.currentBuyGrid = currentBuyGrid;
            	var loader = new contentLoader(url,flipper.addBuyGridToPage,errorHandler,"GET","");
			}
			// if buy grid already loaded then simply flip current and requested buy grid			
			else if(sA[newBuyGridKey] != null){	
				var currentBuyGridElement = document.getElementById("productGrid_prd_" + currentBuyGridNumber);
				var newBuyGridElement = document.getElementById("productGrid_prd_" + sA[newBuyGridKey].buyGridNum);
				
				// reset radio button to correct value
				var mainFeatureTypeChips = document.getElementById("mainFeatureTypeSelector_prd_" + sA[newBuyGridKey].buyGridNum).getElementsByTagName("input");
	            for (i = 0; i < mainFeatureTypeChips.length; i++) {
	                if(mainFeatureTypeChips[i].value == newBuyGridKey){
	                   mainFeatureTypeChips[i].checked = true;             
	                }
	            }
	            
				removeMonogramingOnFitTypeChange(buyGrids[newBuyGridKey],currentBuyGrid.selection);
				makeBuyGridSelections(buyGrids[newBuyGridKey],currentBuyGrid.selection);

				// set active flag
				buyGrids[newBuyGridKey].currentlyActive = true;
				currentBuyGrid.currentlyActive = false
											
				hide(currentBuyGridElement);
				show(newBuyGridElement);
				
				// send new style metric
				buyGrids[newBuyGridKey].sendChangeStyleMetric();		
            }
        } catch (err) {   
        	showErrorPopup(messages.error[33].getMessageText(true));
        }	
}

// This method is used to remove monogram related selections on fit type change
function removeMonogramingOnFitTypeChange(buyGrid,currentSelection){
	
	if(buyGrid.monogramSelector == null && currentSelection.monogrammed){
		showErrorPopup(messages.error.monogramNotAvailableStyleChange);
	}
	else if(currentSelection.monogrammed){
		showErrorPopup( messages.error[35].getMessageText(true));
	}
	
	// reset flag to false
	currentSelection.monogrammed = false;
	currentSelection.monogram = {};
	// remove any monogram information from page
	if(buyGrid.monogramIt != null){
		buyGrid.monogramIt.removeMonogram();
	}
}

function Flipper(){
	this.addBuyGridToPage = function(request)  {
	    var funcName = "[addBuyGridToPage] ";
		var errorContainer = document.getElementById("shipBuyError");
		doDebug(funcName);
		try{	
			// get text version of buy grid / data
			var data = request.responseText;
		    var buyGridHolder = document.getElementById('productGrids');
		    
		    // parse buy grid / data into a temp holder
		    var tempHolder = document.createElement('span');
		    tempHolder.innerHTML = data;
		    var newBuyGridElement = tempHolder.getElementsByTagName('div')[0];
		    
		    // pull the script out and add it to the page
		  	var start = (data.search(/StartJavaScriptData/) + 54);
		  	var end = (data.search(/EndJavaScriptData/) - 14);
		  	var length = end - start;
		  	var script = data.substr(start,length);
		  	// required for correct ordering of buy grid keys
		  	previouslySelectedBuyGridKey = arguments.callee.currentBuyGrid.key;
		  	eval(script);
		    
		    // only flip if this is really the buy grid the user wants to see
		    if(arguments.callee.newBuyGridKey == currentlySelectedFit['T' + sA[arguments.callee.currentBuyGrid.key].productNumber]){
			    // hide the current buy grid
			    var currentBuyGridElement = document.getElementById("productGrid_prd_" + arguments.callee.currentBuyGridNumber);
			    hide(currentBuyGridElement);    
		    }else{
		    	// hide the new buy grid (the user has moved on to another buy grid (fit type))
		    	hide(newBuyGridElement);    	
		    }

			// insert new visible or hidden buy grid (needs to be made part of the page either way)
			buyGridHolder.insertBefore(newBuyGridElement,currentBuyGridElement);

			// create javascript buy grid
			createNewBuyGridFactory(arguments.callee.newBuyGridKey);
	
			// set active flag
			if(arguments.callee.newBuyGridKey == currentlySelectedFit['T' + sA[arguments.callee.currentBuyGrid.key].productNumber]){
				buyGrids[arguments.callee.newBuyGridKey].currentlyActive = true;
			}else{
				buyGrids[arguments.callee.newBuyGridKey].currentlyActive = false;	
			}			
			arguments.callee.currentBuyGrid.currentlyActive = false;
			
			// apply current settings to new buy grid
			removeMonogramingOnFitTypeChange(buyGrids[arguments.callee.newBuyGridKey],arguments.callee.currentBuyGrid.selection);	
			makeBuyGridSelections(buyGrids[arguments.callee.newBuyGridKey],arguments.callee.currentBuyGrid.selection);
			
			var action = getQueryVariable("action");
	  		if (action == "modify") {
				buyGrids[arguments.callee.newBuyGridKey].displayModifyItemButtons();
	        }
	    }catch(error)
	    {   
	    	doDebug(error);
	        showErrorPopup(messages.error[33].getMessageText(true));
	    }
	}
}

function createNewBuyGridFactory(buyGridI){
        var funcName = "[createNewBuyGridFactory] ";
        doDebug(funcName+"making new sbg(" + buyGridI + ")");
    	doDebug(funcName+"making new sbg(" + sA[buyGridI].buyGridNum + ")");
    	buyGrids[buyGridI] = new sbg(sA[buyGridI].buyGridNum,buyGridI);
    	//if (document.getElementById("sizeWaist_prd_" + sA[buyGridI].buyGridNum) != null) {
    		//buyGrids[buyGridI].pantsHemmingSelector = new hem(sA[buyGridI].buyGridNum, buyGrids[buyGridI]);
    	//}
}

function displayStyle(displayStyleNumber, mediaCode, checkDigit, minPrice, maxPrice, customFlag,originalMinPrice,originalMaxPrice,isMasterStyle) {
  this.displayStyleNumber = displayStyleNumber;
  this.mediaCode          = mediaCode;
  this.checkDigit         = checkDigit;
  this.minPrice           = minPrice;
  this.maxPrice           = maxPrice;
  this.originalMaxPrice   = originalMaxPrice;
  this.originalMinPrice   = originalMinPrice;
  this.customFlag         = customFlag;
  this.isMasterStyle	  = isMasterStyle;
}

function sku(skuNumber, displayStyleNumber, mediaCode, checkDigit, featureCode, sizeCode, colorCode, prevPrice, price, inventoryStatus, backorderDate, monoThreadColorCode, minInseam, maxInseam, minCuff, maxCuff, sizeCode1, sizeCode2,promoTypeCode) {
    var getBackorderDate;
    
    this.skuNumber = skuNumber;
    this.displayStyleNumber = displayStyleNumber;
    this.mediaCode = mediaCode;
    this.checkDigit = checkDigit;
    this.featureCode = featureCode;
    this.sizeCode = sizeCode;
    this.colorCode = colorCode;
    this.prevPrice = prevPrice;
    this.price = price;
    this.inventoryStatus = inventoryStatus;
    this.backorderDate = backorderDate;
    this.monoThreadColorCode = monoThreadColorCode;
    this.minInseam = minInseam;
    this.maxInseam = maxInseam;
    this.minCuff = minCuff;
    this.maxCuff = maxCuff;
    this.sizeCode1 = sizeCode1;
    this.sizeCode2 = sizeCode2;
    this.promoTypeCode = promoTypeCode;
    
    if (backorderDate !== undefined && backorderDate !== "" && backorderDate !== null) {
        this.parseBackorderDate = function() {
            var dateArr = backorderDate.split("-");
            var year = dateArr[0];
            var monthNumber = dateArr[1];
            var monthName = monthArray[parseFloat(monthNumber)][0];
            var monthAbbr = monthArray[parseFloat(monthNumber)][1];
            var day = dateArr[2];
            
            this.year = year;
            this.monthNumber = monthNumber;
            this.monthName = monthName;
            this.monthAbbr = monthAbbr;
            this.day = day;
        };

        getBackorderDate = new this.parseBackorderDate();
        this.getBackorderDate = getBackorderDate;
    }
    
    this.toString = function() {
        var str = skuNumber + ".:." 
        		+ displayStyleNumber + ".:." 
                + mediaCode + ".:." 
                + checkDigit + ".:." 
                + featureCode + ".:."
                + sizeCode + ".:." 
                + colorCode + ".:."
                + price + ".:."
                + prevPrice + ".:."
                + inventoryStatus + ".:."
                + backorderDate + ".:."
                + monoThreadColorCode + ".:."
                + minInseam + ".:."
                + maxInseam + ".:."
                + minCuff + ".:."
                + maxCuff + ".:."
                + sizeCode1 + ".:."
                + sizeCode2;
                
        return str;
    };
}

function colorInvStatus(code,status) {
  var thisColorInvStatus = this;
  this.colorCode = code;
  this.invStatus = status;
 
  this.toString = function() {
        var str = thisColorInvStatus.colorCode + "/" +
                  thisColorInvStatus.invStatus;
                  
        return str;
  };
  
  this.getStatus = function() {
      return thisColorInvStatus.invStatus;
  };
  this.getColorCode = function() {
      return thisColorInvStatus.colorCode;
  };
  
  this.compareInventory = function(clrInvStatObj) {
      var thisStatus = this.getStatus();
      var thatStatus = clrInvStatObj.getStatus();
      if (thisStatus == "A") {
          return this;
      }
      if (thatStatus == "A") {
          return clrInvStatObj;
      }
      if (thisStatus == "B") {
         return this;
      }
      if (thatStatus == "B") {
         return clrInvStatObj;
      }
      if (thisStatus == "N") {
          return this;
      }
      if (thatStatus == "N") {
          return clrInvStatObj;
      }
      return this;
  };
}

function size1InvStatus(code,status) {
  var thisSizeInvStatus = this;
  this.sizeCode1 = code;
  this.invStatus = status;
 
  this.toString = function() {
        var str = thisSizeInvStatus.sizeCode1 + "/" +
                  thisSizeInvStatus.invStatus;           
        return str;
  };
  
  this.getStatus = function() {
      return thisSizeInvStatus.invStatus;
  };
  this.getSizeCode = function() {
      return thisSizeInvStatus.sizeCode1;
  };
  
  this.compareInventory = function(szInvStatObj) {
      var thisStatus = this.getStatus();
      var thatStatus = szInvStatObj.getStatus();
      if (thisStatus == "A") {
          return this;
      }
      if (thatStatus == "A") {
          return szInvStatObj;
      }
      if (thisStatus == "B") {
         return this;
      }
      if (thatStatus == "B") {
         return szInvStatObj;
      }
      if (thisStatus == "N") {
          return this;
      }
      if (thatStatus == "N") {
          return szInvStatObj;
      }
      return this;
  };
}
function size2InvStatus(code,status) {
  var thisSizeInvStatus = this;
  this.sizeCode2 = code;
  this.invStatus = status;
 
  this.toString = function() {
        var str = thisSizeInvStatus.sizeCode2 + "/" +
                  thisSizeInvStatus.invStatus;           
        return str;
  };
  
  this.getStatus = function() {
      return thisSizeInvStatus.invStatus;
  };
  this.getSizeCode = function() {
      return thisSizeInvStatus.sizeCode2;
  };
  
  this.compareInventory = function(szInvStatObj) {
      var thisStatus = this.getStatus();
      var thatStatus = szInvStatObj.getStatus();
      if (thisStatus == "A") {
          return this;
      }
      if (thatStatus == "A") {
          return szInvStatObj;
      }
      if (thisStatus == "B") {
         return this;
      }
      if (thatStatus == "B") {
         return szInvStatObj;
      }
      if (thisStatus == "N") {
          return this;
      }
      if (thatStatus == "N") {
          return szInvStatObj;
      }
      return this;
  };
}

/*===============================================================

    A generic selection object with some functions for purchasing

===============================================================*/
function selectionObj() {
    var thisSelection = this;
   
    this.buyGridNumber = ""; 
    this.sku = {};
    this.style = "";
    this.styleText = "";
    this.viewID = "";
    this.itemNumber = "";
    this.featureCodes = [];
    this.featureNames = [];
    this.colorCode = "";
    this.sizeCode = "";
    this.sizeCode1 = "";
    this.sizeCode2 = "";
    this.giftBox = false;
    this.giftBoxPrice = 0;
    this.monogrammed = false;
    this.monogram = {};
    this.quantity = 1;
    this.shipTo = "";
    this.shipToNickname = "";
    this.shoppingBagPrice = 0;
    this.prevPrice = "";
    this.price = 0;
    this.schoolUniformmed = false;
    this.schoolUniform = {};
    this.productImageURL = "";
    this.hemmed = false;
    this.hemming = {
        finished : true,
          length : "",
          cuffed : false
    };
    this.dropShipDayPhone = "";
    this.dropShipDayPhoneExt = "";
    this.dropShipAltPhone = "";
    this.dropShipAltPhoneExt = "";
    this.removeItemFromPurchase = false;
    this.updated = false;
    // returned by a CGI for modify
    this.itemID = "";
    
    this.copy = function () {
    	var newSelection = new selectionObj();
    	newSelection.buyGridNumber = this.buyGridNumber;
    	newSelection.sku = this.sku;
    	newSelection.style = this.style;
		newSelection.styleText = this.styleText;
		newSelection.viewID =  this.viewID;
		newSelection.itemNumber = this.itemNumber;
		newSelection.featureCodes = this.featureCodes;
		newSelection.featureNames = this.featureNames;
		newSelection.colorCode = this.colorCode;
		newSelection.sizeCode = this.sizeCode;
		newSelection.sizeCode1 = this.sizeCode1;
		newSelection.sizeCode2 = this.sizeCode2;
		newSelection.giftBox = this.giftBox;
		newSelection.giftBoxPrice = this.giftBoxPrice;
		newSelection.monogrammed = this.monogrammed;
		newSelection.monogram = this.monogram;
		newSelection.quantity = this.quantity;
		newSelection.shipTo = this.shipTo;
		newSelection.shipToNickname = this.shipToNickname;
		newSelection.shoppingBagPrice = this.shoppingBagPrice;
		newSelection.prevPrice = this.prevPrice;
		newSelection.price = this.price;
		newSelection.schoolUniformmed = this.schoolUniformmed;
		newSelection.hemmed = this.hemmed;
		newSelection.hemming.finished = this.hemming.finished;
		newSelection.hemming.length = this.hemming.length;
		newSelection.hemming.cuffed = this.hemming.cuffed;
		newSelection.productImageURL = this.productImageURL;
    	
    	return newSelection;
    }    
    
    /*==================================
        The total price of the selection
    ==================================*/
    this.getExtendedPrice = function() {
        var monoPrice = 0;
        var schoolUniPrice = 0;
        var hemmingPrice = 0;
        var giftBoxPrice = 0;

        if (thisSelection.monogram.price != null && !isNaN(thisSelection.monogram.price)) {
            monoPrice = parseFloat(thisSelection.monogram.price);
        }

        if (thisSelection.schoolUniform.price != null && !isNaN(thisSelection.schoolUniform.price)) {
            schoolUniPrice = parseFloat(thisSelection.schoolUniform.price);
        }
        
        if (thisSelection.hemming.price != null && !isNaN(thisSelection.hemming.price)) {
            hemmingPrice = parseFloat(thisSelection.hemmingSelection.price);
        }
        
        if (thisSelection.giftBoxPrice != null && !isNaN(thisSelection.giftBoxPrice )) {
            giftBoxPrice = parseFloat(thisSelection.giftBoxPrice);
        }        
        
        return parseFloat(parseFloat(thisSelection.quantity) * (parseFloat(thisSelection.price) + monoPrice + schoolUniPrice + hemmingPrice + giftBoxPrice));
    };
    
    // helps with some funky behavior
    this.extendedPrice = this.getExtendedPrice();
    
    this.toString = function() {
        var str = thisSelection.sku + ".:." +
                  thisSelection.style + ".:." +
                  thisSelection.styleText + ".:." +
                  thisSelection.viewID + ".:." +
                  thisSelection.itemNumber + ".:." +
                  thisSelection.featureCodes.join(",") + ".:." +
                  thisSelection.featureNames.join(",") + ".:." +
                  thisSelection.colorCode + ".:." +
                  thisSelection.sizeCode + ".:." +
                  thisSelection.sizeCode1 + ".:." +
                  thisSelection.sizeCode2 + ".:." +
                  thisSelection.giftBox + ".:." +
                  thisSelection.giftBoxPrice + ".:." +
                  thisSelection.monogrammed + ".:." +
                  thisSelection.monogram + ".:." +
                  thisSelection.quantity + ".:." +
                  thisSelection.shipTo + ".:." +
                  thisSelection.shipToNickname + ".:." +
                  thisSelection.prevPrice + ".:." +
                  thisSelection.price + ".:." +
                  thisSelection.schoolUniformmed + ".:." +
                  thisSelection.schoolUniform + ".:." +
                  thisSelection.hemmed + ".:." +
                  thisSelection.hemming;
                  
        return str;
    };
}

/*============================================================================

    Builds an item number based on a style number, media code and check digit.

============================================================================*/

function buildItemNumber(styleNumber, mediaCode, checkDigit) {
    var itemNumber = "" + styleNumber + mediaCode + checkDigit;
    var itemNumberPart1 = itemNumber.slice(0, (itemNumber.length - 4));
    var itemNumberPart2 = itemNumber.slice((itemNumber.length - 4), itemNumber.length);
    itemNumber = itemNumberPart1 + "-" + itemNumberPart2;
    
    if (itemNumber.length < 10) {
        var i;
        var cycles = (10 - itemNumber.length);

        for (i = 0; i < cycles; i++) {
            itemNumber = "0" + itemNumber;
        }
    }
    
    return itemNumber;
}
