var pageControllerObject;

function controllerFactory() {
   pageControllerObject = new pageController();
   pageControllerObject.onReady();
}

function pageController() {

   // controller constructor
   
   // swatches stuff
   var swatchesObject;
   if (window.colorStyleImages) {
      if (colorStyleImages.mainImages) {
         swatchesObject = new swatchesClass(colorStyleImages.mainImages.length);
      }
   }

   this.swatchesObject = swatchesObject; // make swatchesObject a public member
   this.colorChange = colorChange; // make colorChange() a public member
   this.menuChange = menuChange; // make menuChange() a public member

   // search stuff
   if(window.jsonData){
      var searchObject = new searchClass(jsonData);
      this.searchObject = searchObject;
   }

   //menus
   var menuObject = new menuClass();
   this.menuObject = menuObject;

   // if the colorMenu doesn't exist, but the swatches do
   // then we are on a page (like the BO/OOS page) that needs to maintain the color state by a means other than the color menu
   if (menuObject.getColor() == "false" && swatchesObject) {
      // create a new public variable (and initialize it) that will contain the colorCode for the currently selected color
      this.backOrderColorCode = -1;
   }

   // image swap
   // create a new imageSwap instance with the appropriate array in the imageJson as a parameter
   if (window.colorStyleImages) {
      if (colorStyleImages.mainImages) {
            var imageSwapObj = new imageSwapClass(colorStyleImages.mainImages);
      }
   }

   // color text swap
   var colorTextSwapObj;
   if ( document.getElementById("colorName") && window.jsonData && jsonData.attributeArrays) {
      var lastIndex = jsonData.attributeArrays.length - 1;
      colorTextSwapObj = new colorTextSwap(jsonData.attributeArrays[lastIndex]);
      this.colorTextSwapObj = colorTextSwapObj;
   }

   //FJIK & GRID
   //if(window.jsonData && document.getElementById("gridPopRequestLink") && document.getElementById("gridPop") ){
   this.fjik = false;
   this.fproxy = false;
   this.menuForm = false;
   window.fjik = this.fjik;
   window.fproxy = this.fproxy;
   window.menuForm = this.menuForm;
   if(window.jsonData){
      //request page model
      var pageModelControl = new pageModelController(this, menuNamesArray);
      this.pageModelControl = pageModelControl;
      window.pageModelControl = pageModelControl;
      this.pageModel = pageModelControl.determineInitPageModel(window.jsonData);
      window.pageModel = this.pageModel;
      this.pageModel = pageModel;

      if(window.crossCommFlag == true){


         //Find largest drop down width
         this.largestResultString = "";
         var sum = 0;
         var d = 0;
         for(var i in jsonData.metaTypes){
            //if(jsonData.metaTypes[i][2] != 0 && i !=0){
            if(i !=0 ){
               d++;
               sum+=jsonData.metaTypes[i][0].length;
            }
         }
         var average = sum/d;
         for (var i =0; i< average; i++){
            this.largestResultString += "|";
         }



         for(var i in jsonData.attributeArrays){
            this.largestOptionString = "";
            for(var s in jsonData.attributeArrays[i]){
               if(jsonData.attributeArrays[i][s].length > this.largestOptionString.length){
                  this.largestOptionString = jsonData.attributeArrays[i][s];
               }
            }
         }
         this.largestOptionDescription = "";
         for(var i in jsonData.attributeDescriptions){
            if(jsonData.attributeDescriptions[i].length>this.largestOptionDescription.length){
               this.largestOptionDescription = jsonData.attributeDescriptions[i];
            }
         }
         window.largestResultString = this.largestResultString;

         //Menu Controller for cross menu communication.

         this.menuForm = new menuController(jsonData.attributeArrays,this,menuNamesArray);
         window.menuForm = this.menuForm;
         var scope = this;
         this.menuForm.onActivity = function(eventName){
            if(eventName == "focus"){
               if(pageControllerObject.fproxy){
                  if(scope.fproxy.state == "visible"){
                     scope.fproxy.toggleGrid();
                  }
               }
            }
            if(eventName == "change"){
               if(scope){
                  scope.menuChange();
               }
            }

            if (document.getElementById("buy") ) {
               var buyInputElement = document.getElementById("buy");
               buyInputElement.setAttribute("value","Y");
               buyInputElement = null; // remove reference to DOM to prevent memory leak in IE
            }
         }
      }





      if(document.getElementById("gridPopRequestLink") && document.getElementById("gridPop")){
         var uid = new Date().getTime();

         this.fjik =  new FlashProxy(uid, '/Flash/fjik/JavaScriptFlashGateway.swf');
         window.fjik = this.fjik;

         this.so = new SWFObject("/Flash/availabilityGrid/swf/dataGrid.swf", "mymovie", "532", "320", "6", "#FFFFFF");
         this.so.skipDetect = true;
         this.so.addVariable("pageController", "pageControllerObject");
         this.so.addVariable("parentObject", "fproxy");
         this.so.addVariable("parentCloseMethod", "toggleGrid");
         this.so.addVariable("lcId", uid);
         this.so.addParam("scale","noscale");

         //Add slot texts

         this.so.addVariable("slotText1",gridTextSlots.instruct1);
         this.so.addVariable("slotText3",gridTextSlots.select);
         this.so.addVariable("slotText4",gridTextSlots.close);
         this.so.addVariable("slotText6",gridTextSlots.instruct2_1);
         this.so.addVariable("slotText7",gridTextSlots.instruct2_2);
         if(itemDesc){
            this.so.addVariable("slotText0",gridTextSlots.title+": "+gridTextSlots.itemDescription);
         }else{
            this.so.addVariable("slotText0",gridTextSlots.title);
         }


         this.gridPopDivID = "gridPop";
         this.popOut = document.getElementById(this.gridPopDivID);

         this.fproxy = new flashGridController(uid, this.so, this.popOut);
         this.fproxy.setCommObject(this.fjik);
         //describe getters available to flash
         var flashController = this.fproxy;
         //set custom methods for flash

         this.fproxy.getChosenValues = function(){

            if (document.getElementById("buy") ) {
               var buyInputElement = document.getElementById("buy");
               buyInputElement.setAttribute("value","Y");
               buyInputElement = null; // remove reference to DOM to prevent memory leak in IE
            }
            flashController.fjik.call("acceptJSON",pageModelControl.getChosenValues(),"chosenInfo");
            //document.title = "test";
         }
         this.fproxy.acceptNewMenuValues = function(chosenValues){
            window.toggleOK = false;
            if (document.getElementById("achart") ) {
               var chartInputElement = document.getElementById("achart");
               chartInputElement.setAttribute("value",1);
               chartInputElement = null; // remove reference to DOM to prevent memory leak in IE
            }
            for(var i in chosenValues){
               pageModelControl.setChosenValue(i,chosenValues[i]);
            }
         }
         //set generic fetch methods for Flash
         this.fproxy.getStockJSON = this.fproxy.flashEventFactory("acceptJSON", jsonData, "stockInfo");
         if(window.colorStyleImages){
            var thumbs = colorStyleImages.thumbs;
         }else{
            var thumbs = {};
         }
         this.fproxy.getImageInfo = this.fproxy.flashEventFactory("acceptJSON", thumbs, "imageInfo");
         this.fproxy.getPageModel = this.fproxy.flashEventFactory("acceptJSON", pageModel, "pageInfo");

         //describe JS methods available to Flash
         this.fproxy.closeGridFromFlash = this.fproxy.JSEventFactory("toggleGrid");
         window.fproxy = this.fproxy;
      }
   }

   // Larger view/view on model popup
   var viewlargerwindow;
   this.launchLargerView = launchLargerView;
   this.closeLargerView = closeLargerView;
   
   // Zoom popup
   var zoomwindow;
   this.launchZoom = launchZoom;
   this.closeZoom = closeZoom;

   // stuff to do onLoad:

   menuChange();  // makes sure everything (eg. swatches) are in sync with the menus
   attachEventsControllerInit();

   // Controller functions

   this.doOnLoad = doOnLoad; // make the below function visible as a public method of this class
   function doOnLoad() {
   	//alert("in doOnLoad() ");

      window.cacheTitle = document.title;

      if(document.getElementById("gridPopRequestLink") && document.getElementById("gridPop"))
      {
         //alert('doc has gridPopRequestLink and gridPop');
         var testFJIK = new FJIKTester();
         testFJIK.onSuccess = function(){
            if(document.getElementById("availChartLink")){
               var popAnchorHolder = document.getElementById("availChartLink");
               popAnchorHolder.style.display = "inline";
               var popAnchor = document.getElementById("gridPopRequestLink");
               popAnchor.onclick = function(){};
               popAnchor.setAttribute("href" , "javascript:pageControllerObject.fproxy.toggleGrid();void(0);");
            }

            if(document.getElementById("availChartLink2")){
               var popAnchor2Holder = document.getElementById("availChartLink2");
               popAnchor2Holder.style.display = "inline";
               var popAnchor2 = document.getElementById("gridPopRequestLink2");
               popAnchor2.onclick = function(){};
               popAnchor2.setAttribute("href" , "javascript:pageControllerObject.fproxy.toggleGrid();void(0);");
            }
            window.scrollAnchor = function(desty){
               ss.INTERVAL = setInterval('ss.scrollWindow('+25+','+desty+',"'+""+'")',10);
            }
             var allLinks = document.getElementsByTagName('a');

             for (var i=0;i<allLinks.length;i++) {
               var lnk = allLinks[i];
               if ((lnk.href && lnk.href.indexOf('#') != -1) &&
                   ( (lnk.pathname == location.pathname) ||
                ('/'+lnk.pathname == location.pathname) ) &&
                   (lnk.search == location.search)) {
                  if(document.getElementsByName(lnk.href.split('#')[1])[0]){
                        lnk.href="javascript:scrollAnchor("+document.getElementsByName(lnk.href.split('#')[1])[0].offsetTop+");";
               }

               }
             }
             //alert("calling setZoomLinks() from flash detection code block");
             setZoomLinks();
         }
         testFJIK.runFlashTest();
      }
      else
      {
        //alert("calling setZoomLinks() from non-flash detection code block");
      	setZoomLinks();	// We call this explicitly if the flash object doesn't call it onSuccess();
      }

      newDiv = document.createElement('div');
      newDiv.setAttribute('id',"obscurum");
      document.body.appendChild(newDiv);
      newDiv.style.visibility = "hidden";
      newDiv.style.zIndex = 999;
      newDiv.style.position = "absolute";
      newDiv.style.left = 0;
      newDiv.style.top = 0;
      newDiv.style.background = "url('"+imagePath+"spacer.gif"+"')";
      window.toggleOK = true;
      newDiv.onclick = function(){
         if(pageControllerObject.fproxy && window.toggleOK){
            pageControllerObject.fproxy.toggleGrid();
         }
      }
      newDiv = null; // remove reference to DOM to prevent memory leak in IE
      if(window.jsonData && window.crossCommFlag == true){
         if(window.jsonData.attributeArrays.length  >1 && this.largestResultString.length>0){
            var str = this.largestOptionString+" ("+this.largestResultString+")";
            this.menuWidth = str.getWidth();
            window.menuWidth = this.menuWidth;
            this.optionWidth = this.largestOptionDescription.getWidth();
            window.optionWidth = this.optionWidth;
            if (this.menuForm){
               if(this.menuWidth  > this.optionWidth + 40){
                  this.menuForm.resizeMenus(this.menuWidth);
               }else{
                  this.menuForm.resizeMenus(this.optionWidth+40);
               }
            }
         }
         this.menuForm.checkMenuSizes();
      }
	  
		// For Multi Shipto
		if (window.multiShipTo) {
			multiShipTo.updateLink();
		}
      resetFlag();
      preloadGlobalNav();
      prodTabController.resizeTabContainer('tabHeightReferenceElement', 256);
      attachEventsBodyOnload();
	  createStorePickupList();
   }

	function setZoomLinks()
	{
		var userHasFlash = isUserFlashEnabled();
		
		
		// For Zoom
		if ((!displayZoomLink) || (speed == 0) || (!window.zmUrl) || (!userHasFlash))
		{
			//alert("No zoom for you!\nspeed = |" + speed + "|\nuserHasFlash = |" + userHasFlash + "|\ndisplayZoomLink = |" + displayZoomLink + "|\nwindow.zmUrl = |" + window.zmUrl + "|");
			if (document.getElementById("zmvlAnchor2"))
			{
				var zmvlAnchor2 = document.getElementById("zmvlAnchor2");
				zmvlAnchor2.href = "javascript:pageControllerObject.launchLargerView(vlUrl);";
				//alert(zmvla.tagName);
				//alert("set zmvlAnchor2 to |" + vlUrl + "|");
			}
			if (document.getElementById("zmvlAnchor3"))
			{
				var zmvlAnchor3 = document.getElementById("zmvlAnchor3");
				zmvlAnchor3.innerHTML = vlText;
				zmvlAnchor3.href = "javascript:pageControllerObject.launchLargerView(vlUrl);";
				//alert("set zmvlAnchor3.innerHTML to |" + vlText + "|\nset zmvlAnchor3.href = |" + vlUrl + "|");
			}
			if (document.getElementById("zmvlImage"))
			{
				var zmvlImage = document.getElementById("zmvlImage");
				zmvlImage.alt = vlText;
				//alert("set zmvlImage to |" + vlText + "|");
			}
			// Set the Addl View (view on model) url
			if (document.getElementById("vmAnchor1"))
			{
				var vmAnchor1 = document.getElementById("vmAnchor1");
				vmAnchor1.href = "javascript:pageControllerObject.launchLargerView(vmUrl);";
			}
			if (document.getElementById("vmAnchor2"))
			{
				var vmAnchor2 = document.getElementById("vmAnchor2");
				vmAnchor2.href = "javascript:pageControllerObject.launchLargerView(vmUrl);";
			}
			if (document.getElementById("vlAnchor1"))
			{
				var vlAnchor1 = document.getElementById("vlAnchor1");
				vlAnchor1.href = "javascript:pageControllerObject.launchLargerView(vlUrl);";
			}
		}
		else
		{
			if (document.getElementById("vlAnchor1")) {
				// need to set the main image link
				var vlAnchor1 = document.getElementById("vlAnchor1");
				vlAnchor1.href = "javascript:pageControllerObject.launchZoom(zmUrl);";
			}
			
			//alert("Zoom for you!\nspeed = |" + speed + "|\nuserHasFlash = |" + userHasFlash + "|\ndisplayZoomLink = |" + displayZoomLink + "|\nwindow.zmUrl = |" + window.zmUrl + "|");
		}
		
		if (document.getElementById("zmvlSection"))
		{
			var zmvlSection = document.getElementById("zmvlSection");
			zmvlSection.style.visibility = "visible";
			zmvlSection.style.display = "inline";
			//alert("set zmvlSection to inline");
		}
		if (document.getElementById("zmvlAnchor2"))
		{
			var zmvlAnchor2 = document.getElementById("zmvlAnchor2");
			zmvlAnchor2.style.visibility = "visible";
			zmvlAnchor2.style.display = "inline";
			zmvlAnchor2.style.className = "listLink";
			//alert("set zmvlAnchor2 to inline");
		}
		if (document.getElementById("zmvlAnchor3"))
		{
			var zmvlAnchor3 = document.getElementById("zmvlAnchor3");
			zmvlAnchor3.style.visibility = "visible";
			zmvlAnchor3.style.display = "inline";
			zmvlAnchor3.style.className = "listLink";
			//alert("set zmvlAnchor3 to inline");
		}
		if (document.getElementById("vmAnchor1"))
		{
			var vmAnchor1 = document.getElementById("vmAnchor1");
			vmAnchor1.style.visibility = "visible";
			vmAnchor1.style.display = "inline";
			vmAnchor1.style.className = "listLink";
			//alert("set vmAnchor1 to inline");
		}
		if (document.getElementById("vmAnchor2"))
		{
			var vmAnchor2 = document.getElementById("vmAnchor2");
			vmAnchor2.style.visibility = "visible";
			vmAnchor2.style.display = "inline";
			vmAnchor2.style.className = "listLink";
			//alert("set vmAnchor2 to inline");
		}
		document.getElementById("popupSection").style.visibility = "visible";
		document.getElementById("popupSection").style.display = "inline";
		

		//alert("painting zoom and view larger links. userHasFlash = |" + userHasFlash + "|, speed = |" + speed + "|, window.zmUrl = |" + window.zmUrl + "|");
	}

   function colorChange(colorCode) {
      if(this.menuForm){
         this.menuForm.onFocus();
      }
      //pageControllerObject.menuForm.onChangeMenu();
      if (menuObject) {
         // update menu selection
         menuObject.updateColorMenu(colorCode);

         // obtain menu values in order to conduct a search
         var size1 = menuObject.getSize1();
         var size2 = menuObject.getSize2();

         // do a search
         if (searchObject) {
            var searchResultArray;
            if (window.menuNamesArray) {
               searchResultArray = searchObject.searchStockType(colorCode, size1, size2, menuNamesArray);
            } else {
               searchResultArray = searchObject.searchStockType(colorCode, size1, size2);
            }
            setDefaultShipMsgVisibility(searchResultArray);
            setDirectShipMsgVisibility(searchResultArray);
         }
      }
      if (this.backOrderColorCode) {
         this.backOrderColorCode = colorCode;
      }

      // image swap
      if ((imageFunctionIndicator == "1" || imageFunctionIndicator == "2"  || imageFunctionIndicator == "4") && document.getElementById("menuColor")) {

         // only swap image if imageFunctionIndicator in (1,2,4)
         if (imageSwapObj) {
            imageSwapObj.swap(colorCode);
         }

         if (colorTextSwapObj) {
            colorTextSwapObj.swap(colorCode);
         }

         // image swap in View Larger popup, if it exists
         if (viewlargerwindow) { // first check if the popup window is present
            if (!viewlargerwindow.closed) { // for IE
               if (viewlargerwindow.pageControllerObject && viewlargerwindow.productId == self.productId ) { // then check that the popup still contains the page we expect it to
                  if (viewlargerwindow.pageControllerObject.imageSwapObj) {
                     viewlargerwindow.pageControllerObject.imageSwapObj.swap(colorCode);
                  }
                  if (viewlargerwindow.pageControllerObject.colorTextSwapObj) {
                     viewlargerwindow.pageControllerObject.colorTextSwapObj.swap(colorCode);
                  }
               }
            }
         }
         
         // image swap in Zoom popup, if it exists
         if (zoomwindow) { // first check if the popup window is present
            if (!zoomwindow.closed) { // for IE
              if (zoomwindow.pageControllerObject && zoomwindow.productId == self.productId ) { // then check that the popup still contains the page we expect it to
                if (zoomwindow.pageControllerObject.altViewSelected) {
                	zoomwindow.pageControllerObject.zoomImageSwap(colorCode, 1);
                } else {
                	zoomwindow.pageControllerObject.zoomImageSwap(colorCode);
                }
                if (zoomwindow.pageControllerObject.colorTextSwapObj) {
                	zoomwindow.pageControllerObject.colorTextSwapObj.swap(colorCode);
                }
                if (zoomwindow.pageControllerObject.zoomAltThumbsObject) {
                    zoomwindow.pageControllerObject.zoomAltThumbsObject.showHideSwatches(false);
                    zoomwindow.pageControllerObject.zoomAltThumbsObject.resetThumbnails();
                    zoomwindow.pageControllerObject.zoomAltThumbsObject.selectMainThumbnail();
                    zoomwindow.pageControllerObject.altViewSelected = 0;
                }  
              }
            }
         }         
         
         
      }
   }

   function menuChange() {
      // obtain menu values
      if (menuObject) {
         var colorCode = menuObject.getColor();
         var size1 = menuObject.getSize1();
         var size2 = menuObject.getSize2();

         // reset all swatches
         if (swatchesObject) {
            swatchesObject.setAllInStock();
         }

         // reset all larger view popup swatches
         if (viewlargerwindow) { // first check if the popup window is present
            if (!viewlargerwindow.closed) { // for IE
               if (viewlargerwindow.pageControllerObject && viewlargerwindow.productId == self.productId) { // then check that the popup still contains the page we expect it to
                  if (viewlargerwindow.pageControllerObject.swatchesObject) {
                     viewlargerwindow.pageControllerObject.swatchesObject.setAllInStock();
                  }
               }
            }
         }
         
         // reset all zoom popup swatches
         if (zoomwindow) { // first check if the popup window is present
            if (!zoomwindow.closed) { // for IE
               if (zoomwindow.pageControllerObject && zoomwindow.productId == self.productId) { // then check that the popup still contains the page we expect it to
                  if (zoomwindow.pageControllerObject.swatchesObject) {
                     zoomwindow.pageControllerObject.swatchesObject.setAllInStock();
                     zoomwindow.pageControllerObject.swatchesObject.deactivateLink(colorCode);
                  }
               }
            }
         }

         // the below is verbose to make the following condition statement more readable
         // size1Present is true if the size1 menu exists
         var size1Present = ( size1 != "false" );
         // size1PresentAndChosen is true if the size1 menu exists and a size1 size is selected
         var size1PresentAndChosen = !( ( size1 == -1 ) || ( size1 == "false") );
         // size2Present is true if the size2 menu exists
         var size2Present = ( size2 != "false" );
         // size2PresentAndChosen is true a size2 menu exists and a size2 size is selected
         var size2PresentAndChosen = !( ( size2 == -1 ) || ( size2 == "false") );
         // colorsPresent is true if the color menu exists
         var colorsPresent = (colorCode != "false");
         // colorsPresentAndChosen is true if the color menu exists and a color is selected
         var colorsPresentAndChosen = !( ( colorCode == -1 ) || ( colorCode == "false") );


         // do a search for each possible color, to find out if any of them are out of stock
         // for any that are out of stock, update and disable the swatches appropriately
         if (searchObject && window.crossCommFlag == true) {
            if ( (size1PresentAndChosen && colorsPresent && !size2Present)
              || (size1PresentAndChosen && colorsPresent && size2PresentAndChosen) ) {

               var allColorsArray = searchObject.getAllColorCodes();
               for (var x in allColorsArray) {
                  var searchResultArray;
                  if (window.menuNamesArray) {
                     searchResultArray = searchObject.searchStockType(x, size1, size2, menuNamesArray);
                  } else {
                     searchResultArray = searchObject.searchStockType(x, size1, size2);
                  }

                  if ( searchResultArray[0] == false ) { // if no result (ie item is not available)

                     // disable the swatch for this color
                     if (swatchesObject) {
                        if (window.jsonData) {
                           if (jsonData.NAString) {
                              swatchesObject.setOutOfStock( x, jsonData.NAString );
                           }
                        }
                     }

                     // disable the view larger popup's swatches too
                     if (viewlargerwindow) { // first check if the popup window is present
                        if (!viewlargerwindow.closed) { // for IE
                           if (viewlargerwindow.pageControllerObject && viewlargerwindow.productId == self.productId ) { // then check that the popup still contains the page we expect it to
                              if (viewlargerwindow.pageControllerObject.swatchesObject) {
                                 if (window.jsonData) {
                                    if (jsonData.NAString) {
                                       viewlargerwindow.pageControllerObject.swatchesObject.setOutOfStock( x, jsonData.NAString );
                                    }
                                 }
                              }
                           }
                        }
                     }
                     
                     // disable the zoom popup's swatches too
                     if (zoomwindow) { // first check if the popup window is present
                        if (!zoomwindow.closed) { // for IE
                           if (zoomwindow.pageControllerObject && zoomwindow.productId == self.productId ) { // then check that the popup still contains the page we expect it to
                              if (zoomwindow.pageControllerObject.swatchesObject) {
                                 if (window.jsonData) {
                                    if (jsonData.NAString) {
                                       zoomwindow.pageControllerObject.swatchesObject.setOutOfStock( x, jsonData.NAString );
                                    }
                                 }
                              }
                           }
                        }
                     }
                     
                  }
                  else if ( searchResultArray[1] == false ) { // if sold out

                     // disable the swatch for this color, and append the sold out text
                     if (swatchesObject) {
                        swatchesObject.setOutOfStock( x, searchResultArray[0] ); // searchResultArray[0] contains the status text
                     }

                     // likewise for the view larger popup's swatches
                     if (viewlargerwindow) { // first check if the popup window is present
                        if (!viewlargerwindow.closed) { // for IE
                           if (viewlargerwindow.pageControllerObject && viewlargerwindow.productId == self.productId) { // then check that the popup still contains the page we expect it to
                              if (viewlargerwindow.pageControllerObject.swatchesObject) {
                                 viewlargerwindow.pageControllerObject.swatchesObject.setOutOfStock( x, searchResultArray[0] );
                              }
                           }
                        }
                     }
                     
                     // likewise for the zoom popup's swatches
                     if (zoomwindow) { // first check if the popup window is present
                        if (!zoomwindow.closed) { // for IE
                           if (zoomwindow.pageControllerObject && zoomwindow.productId == self.productId ) { // then check that the popup still contains the page we expect it to
                              if (zoomwindow.pageControllerObject.swatchesObject) {
                                       zoomwindow.pageControllerObject.swatchesObject.setOutOfStock( x, searchResultArray[0] );
                              }
                           }
                        }
                     }
                     
                  }
               }
            }
            var searchResultArray;
            if (window.menuNamesArray) {
               searchResultArray = searchObject.searchStockType(colorCode, size1, size2, menuNamesArray);
            } else {
               searchResultArray = searchObject.searchStockType(colorCode, size1, size2);
            }
            setDefaultShipMsgVisibility(searchResultArray);
            setDirectShipMsgVisibility(searchResultArray);
         }
      }

      if (colorCode != -1) { // if the colorMenu was set to it's label, don't do anything
         // main image swap
         if ((imageFunctionIndicator == "1" || imageFunctionIndicator == "2"  || imageFunctionIndicator == "4") && document.getElementById("menuColor")) {

         // only swap image if imageFunctionIndicator in (1,2,4)

            if (imageSwapObj) {
               imageSwapObj.swap(colorCode);
            }

            if (colorTextSwapObj) {
               colorTextSwapObj.swap(colorCode);
            }

            // image swap in View Larger popup, if it exists
            if (viewlargerwindow) { // first check if the popup window is present
               if (!viewlargerwindow.closed) { // for IE
                  if (viewlargerwindow.pageControllerObject && viewlargerwindow.productId == self.productId ) { // then check that the popup still contains the page we expect it to
                     if (viewlargerwindow.pageControllerObject.imageSwapObj) {
                        viewlargerwindow.pageControllerObject.imageSwapObj.swap(colorCode);
                     }
                     if (viewlargerwindow.pageControllerObject.colorTextSwapObj) {
                        viewlargerwindow.pageControllerObject.colorTextSwapObj.swap(colorCode);
                     }

                  }
               }
            }
            
            // image swap in Zoom popup, if it exists
            if (zoomwindow) { // first check if the popup window is present
               if (!zoomwindow.closed) { // for IE
                 if (zoomwindow.pageControllerObject && zoomwindow.productId == self.productId ) { // then check that the popup still contains the page we expect it to
               	 	var colorChanged = 0;
               	 	if (colorCode != zoomwindow.pageControllerObject.curColorCode) {
               	 		colorChanged = 1;
               	 	}

               	 	if (zoomwindow.pageControllerObject.altViewSelected) {
                		zoomwindow.pageControllerObject.zoomImageSwap(colorCode, 1);
                	} else {
                		zoomwindow.pageControllerObject.zoomImageSwap(colorCode);
                	}                 
                   	if (zoomwindow.pageControllerObject.colorTextSwapObj) {
                       		zoomwindow.pageControllerObject.colorTextSwapObj.swap(colorCode);
                   	}
	                if (zoomwindow.pageControllerObject.zoomAltThumbsObject && colorChanged ) {
	                    zoomwindow.pageControllerObject.zoomAltThumbsObject.showHideSwatches(false);
	                    zoomwindow.pageControllerObject.zoomAltThumbsObject.resetThumbnails();
	                    zoomwindow.pageControllerObject.zoomAltThumbsObject.selectMainThumbnail();
	                    zoomwindow.pageControllerObject.altViewSelected = 0;
	                }             
                 }
               }
            }    
              
         }
      }
   }

   // the following method launches the View On Model / View Larger popup
   // it takes the url as a parameter so the JSP can easily update what url the popup is located at, by
   // simply updating the onclick of the calling anchor tag in the html
   function launchLargerView(url,windowName) {

      windowName = windowName ? windowName : 'popup';
      // for IE, must check if window is already open
      if (viewlargerwindow && !viewlargerwindow.closed && viewlargerwindow.location) {
         viewlargerwindow.location.href = url;
      }
      else {
         //viewlargerwindow=window.open(url,windowName,"scrollbars=yes");
         viewlargerwindow=window.open(url,windowName,'resizable=yes,scrollbars=yes,titlebar=no,toolbar=no,status=no,dependant,menubar=no,width=830,height=746,top=25,left=100');
         if (!viewlargerwindow.opener) viewlargerwindow.opener = self;
      }
      if (window.focus) { viewlargerwindow.focus(); }
   }
   function closeLargerView() {
      if (viewlargerwindow) {
         if (!viewlargerwindow.closed) {
            viewlargerwindow.close();
         }
      }

   }
   
   
   // the following method launches the Zoom popup
   // it takes the url as a parameter so the JSP can easily update what url the popup is located at, by
   // simply updating the onclick of the calling anchor tag in the html
   function launchZoom(url,windowName) {

      windowName = windowName ? windowName : 'zoompopup';
      // for IE, must check if window is already open
      if (zoomwindow && !zoomwindow.closed && zoomwindow.location) {
         zoomwindow.location.href = url;
      }
      else {
         zoomwindow=window.open(url,windowName,'resizable=yes,scrollbars=yes,titlebar=no,toolbar=no,status=no,dependant,menubar=no,width=624,height=746,top=25,left=100');
         if (!zoomwindow.opener) zoomwindow.opener = self;
      }
      if (window.focus) { zoomwindow.focus(); }
   }
   function closeZoom() {
      if (zoomwindow) {
         if (!zoomwindow.closed) {
            zoomwindow.close();
         }
      }

   }

   // private methods

   // This function makes the default shipping time message visible when the
   // user selects some combination of product attributes that are in stock
   // and, conversely, makes the message invisible when either not all attributes
   // are selected, or, the attributes selected are not in stock
   function setDefaultShipMsgVisibility(searchResultArray) {
      if ( document.getElementById("defaultShipMsg") ) {
         var shipMsgElement = document.getElementById("defaultShipMsg");
         if ( searchResultArray[0] == false ) {
            shipMsgElement.style.display = "none";
         }
         else if ( searchResultArray[2] == 0 ) { // if in stock
            shipMsgElement.style.display = "block";
         }
         else {
            shipMsgElement.style.display = "none";
         }
         shipMsgElement = null; // remove reference to DOM to prevent memory leak in IE
      }
   }

   function setDirectShipMsgVisibility(searchResultArray) {
      var shipMsgElement1;
      var shipMsgElement2;
      var shipMsgElement3;

      if ( document.getElementById("directShipMsg") ) {
         shipMsgElement1 = document.getElementById("directShipMsg");
      }
      if ( document.getElementById("openParen") ) {
         shipMsgElement2 = document.getElementById("openParen");
      }
      if ( document.getElementById("closedParen") ) {
         shipMsgElement3 = document.getElementById("closedParen");
      }

      if ( searchResultArray[0] == false ) { // if not available
         if (shipMsgElement1) { shipMsgElement1.style.display = "inline"; }
         if (shipMsgElement2) { shipMsgElement2.style.display = "inline"; }
         if (shipMsgElement3) { shipMsgElement3.style.display = "inline"; }
      }
      else if ( (searchResultArray[2] != 0) && (searchResultArray[2] != 1) ) { // if backordered
         if (shipMsgElement1) { shipMsgElement1.style.display = "none"; }
         if (shipMsgElement2) { shipMsgElement2.style.display = "none"; }
         if (shipMsgElement3) { shipMsgElement3.style.display = "none"; }
      }
      else { // if sold out or in stock
         if (shipMsgElement1) { shipMsgElement1.style.display = "inline"; }
         if (shipMsgElement2) { shipMsgElement2.style.display = "inline"; }
         if (shipMsgElement3) { shipMsgElement3.style.display = "inline"; }
      }
      shipMsgElement1 = null; // remove reference to DOM to prevent memory leak in IE
      shipMsgElement2 = null; // remove reference to DOM to prevent memory leak in IE
      shipMsgElement3 = null; // remove reference to DOM to prevent memory leak in IE

   }

   // These are the events that are attached to dom elements when the controller is initialized
   function attachEventsControllerInit() {

      // Attach the menuChange() event to the menus
      var menuSelectElement;
      if(window.menuForm == false){
         if ( document.getElementById("menu_0") ) {
            menuSelectElement = document.getElementById("menu_0");
            if(!menuSelectElement.onchange){
               menuSelectElement.onchange = function(){ pageControllerObject.menuChange();};
            }
         }
         if ( document.getElementById("menu_1") ) {
            menuSelectElement = document.getElementById("menu_1");
            if(!menuSelectElement.onchange){
               menuSelectElement.onchange = function(){ pageControllerObject.menuChange();};
            }
         }
         if ( document.getElementById("menuColor") ) {
            menuSelectElement = document.getElementById("menuColor");
            if(!menuSelectElement.onchange){
               menuSelectElement.onchange = function(){ pageControllerObject.menuChange();};
            }
         }
         menuSelectElement = null; // remove reference to DOM to prevent memory leak in IE
      }
   }

   // These are the events that are attached to DOM elements upon body onload
   function attachEventsBodyOnload() {
	/*
      if (window.vlUrl) {
         if ( document.getElementById("vlAnchor1") ) {
            document.getElementById("vlAnchor1").href = 'javascript:pageControllerObject.launchLargerView("' + vlUrl + '");';
            document.getElementById("vlAnchor1").className="listLink";
         }
         if ( document.getElementById("vlAnchor2") ) {
            document.getElementById("vlAnchor2").href = 'javascript:pageControllerObject.launchLargerView("' + vlUrl + '");';
            document.getElementById("vlAnchor2").className="listLink";
         }
         if ( document.getElementById("vlAnchor3") ) {
            document.getElementById("vlAnchor3").href = 'javascript:pageControllerObject.launchLargerView("' + vlUrl + '");';
            document.getElementById("vlAnchor3").className="listLink";
         }
      }
      if (window.vmUrl) {
         if ( document.getElementById("vmAnchor1") ) {
            document.getElementById("vmAnchor1").href = 'javascript:pageControllerObject.launchLargerView("' + vmUrl + '");';
            document.getElementById("vmAnchor1").className="listLink";
         }
         if ( document.getElementById("vmAnchor2") ) {
            document.getElementById("vmAnchor2").href = 'javascript:pageControllerObject.launchLargerView("' + vmUrl + '");';
            document.getElementById("vmAnchor2").className="listLink";
         }
      }
	*/
      if (window.efUrl) {
         if ( document.getElementById("efAnchor1") ) {
            document.getElementById("efAnchor1").href = efUrl;
            document.getElementById("efAnchor1").className = "listLink";
         }
         if ( document.getElementById("efAnchor2") ) {
            document.getElementById("efAnchor2").href = efUrl;
            document.getElementById("efAnchor2").className = "listLink";
         }
      }
      if (window.availColorsUrl) {
         if ( document.getElementById("availColorsAnchor") ) {
            document.getElementById("availColorsAnchor").href = availColorsUrl;
            document.getElementById("availColorsAnchor").className = "listLink";
         }
      }
   /*
      if (window.zmUrl) {
      	if (document.getElementById("zmAnchor1") ) {
      		document.getElementById("zmAnchor1").href = 'javascript:pageControllerObject.launchZoom("' + zmUrl + '");';
      		document.getElementById("zmAnchor1").className = "listLink";
      	}
      	if (document.getElementById("zmAnchor2") ) {
      		document.getElementById("zmAnchor2").href = 'javascript:pageControllerObject.launchZoom("' + zmUrl + '");';
      		document.getElementById("zmAnchor2").className = "listLink";
      	}
      	if (document.getElementById("zmAnchor3") ) {
      		document.getElementById("zmAnchor3").href = 'javascript:pageControllerObject.launchZoom("' + zmUrl + '");';
      		document.getElementById("zmAnchor3").className = "listLink";
      	}
      }
   */
   }

   function createStorePickupList() {
   	var selects = document.getElementsByTagName('select');
	var len = selects.length;
	for(var i = 0; i < len; i++) {
		var opts = selects[i].options.length;
		for(var j = 0; j < opts; j++) {
			if(selects[i].options[j].disabled) {
				selects[i].options[j].disabled = 'true';
				selects[i].options[j].style.color = '#ccc';
			}
		}
	}
   }
}

function onStoreSelectFocus(e) {
   	var len = e.options.length;
   	for(var i = 0; i < len; i++) {
   		if(e.options[i].disabled) {
   			e.options[i].disabled = 'true';
   			e.options[i].style.color = '#ccc';
   		}
   	}
}
   
function onStoreSelect(e) {
   	var len = e.options.length;
   	for(var i = 0; i < len; i++) {
   		if(e.options[i].selected && e.options[i].disabled) {
   			e.options[i].selected = 'false';
   			e.options[0].selected = 'true';
   			return;
   		}
   	}
}

pageController.prototype.onReady = function(){
   if(this.menuForm){
      this.menuForm.onFocus();
      this.menuForm.onChangeMenu();
   }
}

/**
 * This prototype (class) stands on it's own and is used for page metrics
 * @author ryanma
 */
var prodMetricObj = {
   tabUsageFlg:true,
   availabilityOpensFlg:true,
   hashLinksUsedFlg:true,

   tab2UsageFirstClk:false,
   tab3UsageFirstClk:false,
   availabilityOpensFirstClk:false,
   ddsUsedFirstClk:false,
   ymacUsedFirstClk:false,
   rvpUsedFirstClk:false,
   trackTabUsage:function(index){
      if(this.tabUsageFlg){
         if(index==2 && !this.tab2UsageFirstClk) {
            this.tab2UsageFirstClk=true;
            s_prop4="Product Page - Tab "+index;
            s_products="";
            s_events="";
            void(sendAnalyticsEvent(''));
         } else if(index==3 && !this.tab3UsageFirstClk) {
            this.tab3UsageFirstClk=true;
            s_prop4="Product Page - Tab "+index;
            s_products="";
            s_events="";
            void(sendAnalyticsEvent(''));
         }
      }
   },
   trackAvailabilityOpens:function(){
      if(this.availabilityOpensFlg){
         if(!this.availabilityOpensFirstClk){
            this.availabilityOpensFirstClk=true;
            s_prop4="Product Page - Full Availability Opened";
            s_products="";
            s_events="";
            void(sendAnalyticsEvent(''));
         }
      }
   },
   trackHashLinksUsed:function(hashLinkType){
      if(this.hashLinksUsedFlg){
         if(hashLinkType=='DDS' && !this.ddsUsedFirstClk){
            this.ddsUsedFirstClk=true;
            s_prop4="Product Page "+hashLinkType+" Link";
            s_products="";
            s_events="";
            void(sendAnalyticsEvent(''));
         } else if(hashLinkType=='YMAC' && !this.ymacUsedFirstClk){
            this.ymacUsedFirstClk=true;
            s_prop4="Product Page "+hashLinkType+" Link";
            s_products="";
            s_events="";
            void(sendAnalyticsEvent(''));
         } else if(hashLinkType=='RVP' && !this.rvpUsedFirstClk){
            this.rvpUsedFirstClk=true;
            s_prop4="Product Page "+hashLinkType+" Link";
            s_products="";
            s_events="";
            void(sendAnalyticsEvent(''));
         }
      }
   }

};


/**
 * Begin Menu and Grid Controls
 * @author jberg
 */
String.prototype.getWidth = function(styleObject){
   if(!window.widthTester){
      window.widthTester = document.createElement("span");
      window.widthTester.style.visibility = "hidden";
   }
   document.body.appendChild(window.widthTester);
   for(var i in styleObject){
      window.widthTester.style[i] = styleObject[i];
   }
   window.widthTester.innerHTML = this;
   var w = window.widthTester.offsetWidth;
   document.body.removeChild(window.widthTester);
   return w;

}




function dropDownController(drop,attributeArray, controller){
   this.controller = controller;
   this.drop = drop;
   this.attributeArray = attributeArray;
   var scope = this;
   this.drop.onfocus = function(){
      scope.controller.onFocus(this);
      this.onmousedown = function(){};
   }
   this.drop.onmousedown = function(){
      scope.controller.onFocus(this);
   }
   this.drop.onchange = function(){
      scope.controller.onChangeMenu(this);
   }

}
//Static Members
dropDownController.disabledOptionSelected = function(who){
      if(!who){
         who = this.drop;
      }
      var selectedItem = who.options[who.selectedIndex];
      if(selectedItem.disabled == true || who.selectedIndex == 0){
         return true;
      }
      return false;
}
//Dynamic Members
dropDownController.prototype.resetDrop = function(){
   for(var n = 0;n<this.attributeArray.length;n++){
      var optionToEdit = this.drop.options[n+1];
      optionToEdit.text = this.attributeArray[n];
      optionToEdit.disabled = false;
      optionToEdit.style.color = "#000000";
   }
};
dropDownController.prototype.disableOption = function(optionIndex,propertyArray){
   var optionToEdit = this.drop.options[optionIndex];
   optionToEdit.disabled = true;
   optionToEdit.style.color = "#cccccc";
   this.appendOptionText(optionIndex,propertyArray);
};
dropDownController.prototype.enableOption = function(optionIndex,propertyArray){
   var optionToEdit = this.drop.options[optionIndex];
   optionToEdit.disabled = false;
   optionToEdit.style.color = "#000000";
   this.appendOptionText(optionIndex,propertyArray);
};
dropDownController.prototype.appendOptionText = function(optionIndex,propertyArray){
   var optionToEdit = this.drop.options[optionIndex];
   optionToEdit.text = this.attributeArray[optionIndex-1];
   if(propertyArray[0].length>0){
      optionToEdit.text += " ("+propertyArray[0]+")";
      if(propertyArray[1] == true){
         optionToEdit.style.color = "#000000";
      }
   }
};
dropDownController.prototype.resetSingleOption = function(optionIndex){
   var optionToEdit = this.drop.options[optionIndex];
   optionToEdit.text = this.attributeArray[optionIndex-1];
   optionToEdit.style.color = "#000000";
   optionToEdit.disabled = false;
};

function flashGridController(uid,so, popOut){
   this.so = so;
   this.uid = uid;
   this.state = "hidden";
   this.loaded = false;
   this.gridPopDivID = "gridPop";
   this.popOut = popOut;
}
flashGridController.prototype.setCommObject = function(commObject){
   this.fjik = commObject;
}
flashGridController.prototype.delayUpdate = function(){
   var cacheTitle = document.title;
   this.getChosenValues();
   document.title = cacheTitle;
}
flashGridController.prototype.toggleGrid = function(){
   window.toggleOK = true;
   document.title = window.cacheTitle;
   if(this.state == "hidden"){
      this.state = "visible";
      if(this.loaded == true){
         setTimeout("fproxy.delayUpdate()",750);
      }
      prodMetricObj.trackAvailabilityOpens(); //RMA
   }else{
      this.state = "hidden";
      if(pageControllerObject.menuForm){
         pageControllerObject.menuForm.onFocus();
         pageControllerObject.menuForm.onChangeMenu();
      }
   }
   this.popOut.style.visibility = this.state;
   if(this.loaded === false){
      this.writeFlash(this.gridPopDivID);
      this.loaded = true;
   }
   var bodyWidth;
   var bodyHeight;
   var scrollh = document.body.scrollHeight;
   var offh = document.body.offsetHeight
   if (scrollh > offh){
      bodyWidth = document.body.scrollWidth;
      bodyHeight = document.body.scrollHeight;
   }else{
      bodyWidth = document.body.offsetWidth;
      bodyHeight = document.body.offsetHeight;
   }
   var obscurer = document.getElementById("obscurum");
   obscurer.style.width = bodyWidth.toString()+"px";
   obscurer.style.height = bodyHeight.toString()+"px";
   obscurer.style.visibility = this.state;
   obscurer = null; // remove reference to DOM to prevent memory leak in IE
   this.popOut.style.zIndex = 1000;
};
flashGridController.prototype.writeFlash = function(divID){
   this.so.write(divID);
};
flashGridController.prototype.flashEventFactory = function(flashMethodName,JSObjectReference,parameters){
   var flashcontroller = this;
   return function(){

      flashcontroller.fjik.call(flashMethodName,JSObjectReference,parameters);

   }
}
flashGridController.prototype.JSEventFactory = function(JSMethodName,parameters){
   var flashcontroller = this;
   return function(){
      flashcontroller.call(JSMethodName,parameters);
   }
}

function menuController(attributeArrays,controller,availableMenus){
   this.attributeArrays = attributeArrays;
   this.controller = controller;
   this.availableMenus = availableMenus;
   this.selectedItems = [];
   this.focusedIndex = -1;
   this.focusedObject = {};
   for(var i = 0;i<this.availableMenus.length;i++){
      this["drop"+i] = document.getElementById(this.availableMenus[i]);
      var newDrop = this["drop"+i];
      this["dropDown"+i] = new dropDownController(newDrop,this.attributeArrays[i],this);
      newDrop.controller = this["dropDown"+i];
      newDrop.uid = i;
   }
}

// Added by RMA
menuController.prototype.resizeMenus = function(newWidth) {
   for(var i = 0;i<this.availableMenus.length;i++){
      this["drop"+i] = document.getElementById(this.availableMenus[i]);
      var newDrop = this["drop"+i];
      newDrop.style.width = newWidth.toString()+"px";
   }

}

menuController.prototype.cacheUserChoices = function(who){
      this.focusedObject = who;
      if(!who){
         who = this.getDefaultFocusedObject();
      }
      for(var i = 0; i<this.attributeArrays.length;i++){
            if(who === this["drop"+i]){
               this.focusedIndex = i;
            }
         this.selectedItems[i] = this["drop"+i].selectedIndex-1;

      }
}
menuController.prototype.getDefaultFocusedObject = function(){
   //If no focused object exists we assume a default
   this.focusedObject = this["drop"+(this.availableMenus.length-1)];
   return this.focusedObject;
}
menuController.prototype.onChangeMenu = function(who){
   if(!who){
      who = this.getDefaultFocusedObject();
   }
   if(who.selectedIndex != -1){
      this.cacheUserChoices(who);
      var selectedItem = who.options[who.selectedIndex];
      if(selectedItem.disabled == true || who.selectedIndex == 0){
         who.selectedIndex = 0;
         for(var i = 0; i<this.attributeArrays.length;i++){
            if(this.focusedIndex != i){
               this["dropDown"+i].resetDrop();
            }
         }
      }
      if(this.onActivity){
         this.onActivity("change");
      }
      this.checkMenuSizes();
   }else{
      who.selectedIndex = 0;
   }
}

menuController.prototype.checkMenuSizes = function(){
   if(window.largestResultString.length>0){
   for(var i = 0; i<this.attributeArrays.length;i++){
      var longestString ="";
      var dropToEdit = this["dropDown"+i];
      for(var n=0; n<dropToEdit.attributeArray.length;n++){
         var searchStr = "";
         for(var j =0;j<this.selectedItems.length;j++){
            if(i!=j){
               searchStr+=this.selectedItems[j];
            }else{
               searchStr+=n;
            }
            if(j < (this.selectedItems.length-1)){
               searchStr+="|";
            }
         }
         if(searchStr.indexOf("-")<0){
            var resultArray = this.controller.pageModelControl.searchStockType(searchStr);
            if(resultArray[0].length + dropToEdit.attributeArray[n].length > longestString.length){
               longestString = resultArray[0]+" "+dropToEdit.attributeArray[n];
            }
         }
      }
      var testWidth = longestString.getWidth()+40;
      if(testWidth > parseInt(dropToEdit.drop.style.width) && testWidth> window.optionWidth ){
         dropToEdit.drop.style.width = testWidth.toString()+"px";
      }
   }
   }
}

menuController.prototype.isolateFocusedObject = function(){
   //Make sure only the currently focused drop down shows the update
   for(var i = 0; i<this.attributeArrays.length;i++){
      if(this.focusedIndex != i){
         if(this["drop"+i].selectedIndex>0){
            this["dropDown"+i].resetDrop();
         }
      }
   }
}

menuController.prototype.onFocus = function(who,noIsolate){

   if(this.onActivity){
      this.onActivity("focus");
   }

   this.cacheUserChoices(who);


   var dropToEdit = this.focusedObject.controller;
   var longestString = "";
   for(var i=0; i<dropToEdit.attributeArray.length;i++){
      var searchStr = "";
      for(var j =0;j<this.selectedItems.length;j++){
         if(j!=this.focusedIndex){
            searchStr+=this.selectedItems[j];
         }else{
            searchStr+=i;
         }

         if(j < (this.selectedItems.length-1)){
            searchStr+="|";
         }
      }
      if(searchStr.indexOf("-")<0){
         var resultArray = this.controller.pageModelControl.searchStockType(searchStr);
         if(resultArray[1] == true){
            dropToEdit.enableOption(i+1,resultArray);
         }else{
            dropToEdit.disableOption(i+1,resultArray);
         }
      }
   }
   if(this.onNewOptions){
      this.onNewOptions();
   }
   if(!noIsolate){
      this.isolateFocusedObject();
   }

};


function pageModelController(controller,availableMenus){
   this.controller = controller;
   this.pageModel = {};
   this.chosenValues = {};
   this.availableMenus = availableMenus;
   for(var i = 0;i<this.availableMenus.length;i++){
      this["drop"+i] = document.getElementById(this.availableMenus[i]);
   }
}
pageModelController.prototype.searchStockType = function(searchStr) {
   var stat = [this.json.NAString,false,0];
   var metaTypeArray = this.json.metaTypes;
   for (var s in metaTypeArray) {
      var context = this.json[s.toString()];
      if(context != undefined && new Object(","+context.toString()+",").indexOf(","+searchStr+",") > -1){
         if(s == 0){
            stat = ["",true,0];
         }else{
            stat = metaTypeArray[s];
         }
         break;
      }
   }
   return stat;
};

pageModelController.prototype.determineInitPageModel = function(json){
   this.json = json;
   this.pageModel.optionArray=null;
   this.pageModel.colorStyleArray=null;
   this.pageModel.rowHeaderArray=null;
   for(var i = 0; i< this.availableMenus.length;i++){
      if(this.availableMenus[i]== "menuColor"){
         this.pageModel.colorStyleArray= i;
      }else{
         if(this.availableMenus.length!=2){
            if(this.pageModel.optionArray==null){
               this.pageModel.optionArray = i;
            }else{
               this.pageModel.rowHeaderArray = i;
            }
         }else{
            this.pageModel.rowHeaderArray = i;
         }
      }
   }
   if(this.pageModel.colorStyleArray == null){
      this.pageModel.optionArray=null;
      this.pageModel.colorStyleArray=null;
      this.pageModel.rowHeaderArray=null;
      for(var i = 0; i< this.availableMenus.length;i++){
         if(i == 0){
            this.pageModel.colorStyleArray = i;
         }
         if(i == 1){
            this.pageModel.rowHeaderArray = i;
         }
         if(i == 2){
            this.pageModel.optionArray = i;
         }
      }
   }
   return this.pageModel;
};
pageModelController.prototype.togglePageModelRow_Option = function(){
   if(this.pageModel.optionArray === 0){
      this.pageModel.optionArray=1;
      this.pageModel.rowHeaderArray=0;
   }else{
      this.pageModel.optionArray=0;
      this.pageModel.rowHeaderArray=1;
   }
};
pageModelController.prototype.setChosenValue = function(objectName,objectValue){
      this.chosenValues[objectName] = objectValue;
      if(this.pageModel[objectName] != null){
         //var dropDown = this.controller.menuForm["dropDown"+this.pageModel[objectName]];
         //var drop = this.controller.menuForm["drop"+this.pageModel[objectName]];
         var drop = this["drop"+this.pageModel[objectName]];
         drop.selectedIndex = objectValue+1;
      }
};
pageModelController.prototype.getChosenValues = function(){
   // alert("get chosen values called");
      var chosenValues ={};
      for (var i in this.pageModel){
         if(this.pageModel[i] != null){
            chosenValues[i] = this["drop"+this.pageModel[i]].selectedIndex-1;
         }
      }
      document.title = window.cacheTitle;
      return chosenValues;
};

function FJIKTester(){
   this.gridPopDivID = "gridPop";
   //alert("in FJIKTester()");

}
FJIKTester.prototype.runFlashTest = function(){
   var test = document.createElement("div");
   document.body.appendChild(test);
   this.popOutTest = test;
   this.popOutTest.id = "testFlash";
   var tuid = new Date().getTime();
   var testFlashProxy = new FlashProxy(tuid, '/Flash/fjik/JavaScriptFlashGateway.swf');
   testGetJSON = function(){
      testFlashProxy.call("receiveJSON");
   }
   var scope = this;
   onJSON = function(obj){


         if(scope.onSuccess){
            //alert("Flash tested OK");
            scope.onSuccess();
         } else {
         	scope.onFailure();
        }
         scope.popOutTest.style.visibility = "hidden";
         scope.popOutTest.style.border = "2px solid #999999";
         document.body.removeChild(test);


   }


   this.to = new SWFObject("/Flash/availabilityGrid/swf/jsonTester.swf", "tester", "1", "1", "6", "#FFFFFF");
   this.to.addVariable("lcId", tuid);
   this.popOutTest.style.border = "";
   this.popOutTest.style.visibility = "visible";
    this.to.write(this.popOutTest.id);

}

doDetection = function(){

};


multiShipTo =  {
	
	submitted:false,
	prevState:0,
	
	updateLink: function() {
			
		if (!document.data.quantity) {
			return;	
		}
		
		// get quantity
		var qty = document.data.quantity.value;
		
		// need to remove period from qty because it shares the same
		// keycode value as the Delete key
		if (qty.indexOf(".") > -1) {
			if (qty.length == 1) {
				qty = '';	
			} else {
				if (qty.indexOf(".") == 0) {
					qty = qty.substr(1,1);
				} else {
					qty = qty.substr(0,1);
				}	
			}
			
			document.data.quantity.value = qty;
		}
		
		// see if state changed
		var currentState = 0;
		if (qty == '' || qty.indexOf(".") > -1 || Number(qty) == 1 || Number(qty) == 0) {
			currentState = 1;
		} else {
			currentState = 2;
		}
		
		if (this.prevState == currentState) {
			return;	// state did not change, return
		}
		
		// set prevState to currentState
		this.prevState = currentState;
		
		if (document.getElementById("multiShipToBlock")) {
			
			// make sure multiShipToBlock is visible
			document.getElementById("multiShipToBlock").style.display = "block";
			
			// get the target element
			var element = document.getElementById("multiShipAnchor");
		
			// remove all children from element
			while (element.firstChild) {
				element.removeChild(element.firstChild);
			}
			
			// start building link
			var docfrag = document.createDocumentFragment();
			
			if (qty == '' || qty.indexOf(".") > -1 || Number(qty) == 1 || Number(qty) == 0) {
				
				// no link
				element.className = "inactive";
				docfrag.appendChild(document.createTextNode(multiShipToConfig.linkText));
				
			} else {
				
				// redirect to MIOP link
				element.className = "";
				var anchor = document.createElement("a");
				anchor.href = "javascript:multiShipTo.redirectToMultiItemOrder()";
				anchor.className =  "listLink";
				anchor.appendChild(document.createTextNode(multiShipToConfig.linkText));
				docfrag.appendChild(anchor);
						
			}
		
			element.appendChild(docfrag);
		}
	},

	redirectToMultiItemOrder: function() { 
		
		if (this.submitted) return;
		
		var val = document.data.quantity.value;
		var maxExceeded = null;
		
		// display confirm box if qty > maxQty (10)
		if (val != '' && Number(val) > multiShipToConfig.maxQty) { 
			var answer = confirm(multiShipToConfig.confirmText)
			if (answer){
				maxExceeded = "Y";
			} else {
				return;
			}
		}
		
		var qty = 0;
		if (maxExceeded != null) {
			qty = multiShipToConfig.maxQty;
		} else {
			qty = Number(document.data.quantity.value);
		}
		
		if (qty == 0) return;
		
		var hostName = multiShipToConfig.hostName;
		var cmdPath = multiShipToConfig.cmdPath;
			
		var langId = document.data.langId.value;
		var storeId = document.data.storeId[1].value;
		var catalogId = document.data.catalogId[1].value;
				
		var categoryId = document.data.categoryId.value;
		var catalog_id = document.data.catalog_id.value;
		var feat = document.data.feat.value;
		var from = document.data.from.value;
		var prodId = document.data.service_product_rn.value;
		var cat4 = document.data.cat4.value;
		var parentCategory = document.data.parentCategory.value;
		
		var nickname = document.data.nickname.value;
		var addr_rn = "";
		if (document.data.addr_rn.selectedIndex != -1) {
			
			addr_rn = document.data.addr_rn.options[document.data.addr_rn.selectedIndex].value		
		}
		
		var guideId = null;
		var moduleId = null;
		var noDept = null;
		if (document.data.guideId) {
			guideId = document.data.guideId.value;
			moduleId = document.data.moduleId.value;
			noDept = document.data.noDept.value;
		}
		
		var cuffs = null;
		if (document.data.cuffsradio) {
			var len = document.data.cuffsradio.length;
			for (var j=0; j<len; ++j) {
				if (document.data.cuffsradio[j].checked) {
					cuffs = document.data.cuffsradio[j].value;
				}
			}
		}
	
		var psv = null;
		if (document.data.psv) {
			if (document.data.psv.length) {
				var len = document.data.psv.length;
			} else {
				var len = 1;
			}
			
			if (len == 1) {
				if (document.data.psv.checked) {
					psv = document.data.psv.value;
				}	
			} else {
				for (var j=0; j<len; ++j) {
					if (document.data.psv[j].checked) {
						psv = document.data.psv[j].value;
					}
				}
			}
		}
		
		var qString = "?storeId="+storeId
			+"&langId="+langId
			+"&catalogId="+catalogId
			+"&multiShipTo=Y"
			+"&from="+from
			+"&feat="+feat
			+"&cat4="+cat4
			+"&parentCategory="+parentCategory;
					
		if (guideId != null) {
			qString += "&guideId="+guideId
				+"&moduleId="+moduleId
				+"&noDept="+noDept;
		}
		
		if (maxExceeded != null) {
			qString += "&gtMax=Y";
		}	
	
		// set categoryId, catalog_id, prodId and services for each qty item
		for (var i=0; i < qty; i++) {
					
	 		qString += "&cg_"+i+"="+categoryId;
			qString += "&c_"+i+"="+catalog_id;
			qString += "&pr_"+i+"="+prodId;
			
			if (cuffs != null) {
				qString += "&cuffsradio_"+i+"="+cuffs;
			}
			
			if (psv != null) {
				qString += "&psv_"+i+"="+psv;
			}		
		}
		
		// add nickname or addr_rn to first item only
		if (nickname != "") {
			qString += "&nickname_0=" + nickname;
		} else if (addr_rn != "") {
			qString += "&addr_rn_0=" + addr_rn;
		}
		
		// get value of attr and finishing select boxes
		for (var i=0;i<= document.data.length-1;i++) 
		{
			if( (document.data.elements[i].type == 'select-one')
		 	&& (document.data.elements[i].name != 'addr_rn') 
		 	&& (document.data.elements[i].selectedIndex != -1) 
		 	&& (document.data.elements[i].options[document.data.elements[i].selectedIndex].value != "default")) 
			{
				var attrName =  document.data.elements[i].name;
				var attrValue = escape(document.data.elements[i].options[document.data.elements[i].selectedIndex].value);
				var miopName = "";
				var seq;
				if (attrName.indexOf("attrValue") > -1) {
					var index = attrName.lastIndexOf('_');
					seq = attrName.substring(index+1);
					//miopName = 'atV_' + attrName.substring(index+1)+'_';
					miopName = 'atV_';
				} else {
					miopName = attrName + "_";
				}
				for (var j=0; j < qty; j++) {
					if (miopName == 'atV_') {
						qString += "&"+miopName+j+"_"+seq+"="+attrValue;
					} else {
						qString += "&"+miopName+j+"="+attrValue;
					}
					
				}
			}
		}
				
		var url = multiShipToConfig.hostName + multiShipToConfig.cmdPath + "ShowMultiItemOrder" + qString;
	 	
		this.submitted = true;
	  	
		window.location=url;
	  	
	}
};

