CustomPalette_Class= function() {

      this.CurrentPaletteCode=""
      this.RadioButtonID="custpaleteradio";
      this.InstructionLayerID="CUSTOM_PALETTE_INSTRUCTIONS";
      this.PalettePageName="create-palette.aspx?pcode=";
      this.MessageToDisplayIfNoneSelected='Please select a palette';
      this.CustomTemplateMaxShade=0;
      this.CustomTemplateRule='';
      this.PlaceHolderID='DragablePlaceHolderDiv_ON';
      this.OOSLayerId='CustomTemplate_OOS';
      this.PathToImage="/img/product/swatch/dd/";
      this.spacerImage='spacer.gif';
      this.VariantCode='';
      this.ParentCode='';
      this.CurrentvariantsInPalette='';
      //this.CurrentImageIdsInPalette=''
      this.PaletteRowsLayerID='PALETTE_ROWS_ID';
      this.TotalPriceLayerID='PALETTE_TOTAL_PRICE';
      this.DeafultPaletteUPC='';
      this.DeafultPaletteUPCLayerID='DEFAULT_PALETTE_UPC'
      //this.DefaultStockWebLayerID='DEFAULT_PALETTE_STOCKWEB';
      this.IsDefaultPaletteRemoved=false;
      //this.StockTresHold=4;
      this.BasketPageURL='/_us/_en/checkout/index_basket_browse.aspx';
      this.ResolveDefaultPalette=function() {
     
       if (this.IsDefaultPaletteRemoved==false) {    //   if not removed perform this action.
              if (this.DeafultPaletteUPC=="") {       //   if not populated yet
                    var _obj=$get(this.DeafultPaletteUPCLayerID);
                     if (_obj!=null) {
                         var _defUpc =_obj.innerHTML;
                         if (_defUpc!='') {
                             this.DeafultPaletteUPC=_defUpc
                             this.IsDefaultPaletteRemoved=false;
                                 if ( this.CurrentvariantsInPalette!='') {
                                             this.CurrentvariantsInPalette= this.CurrentvariantsInPalette + ":";
                                 }
                                 this.CurrentvariantsInPalette= this.CurrentvariantsInPalette +  this.DeafultPaletteUPC;
                         
                         }
                     
                     }
               }
         }
      
        
      }
     
     this.SetCurrentCode=function(_Code){
        this.CurrentPaletteCode=_Code;
     }
    
    this.ShowInstructions=function(){
         _CoreModalPopUp._PopupControlID=this.InstructionLayerID;
         _CoreModalPopUp.ShowModal();
         var obj=$get(this.InstructionLayerID);
         if (obj!=null) {
         
            obj.style.top="30px";
         }
         
         
    }
    
    this.HideInstructions=function(){
         _CoreModalPopUp.Hide();
    }
    
    this.GoToPaletteScreen=function() {
       if (this.GetSelectedPaletteCode()=='') {
              alert(this.MessageToDisplayIfNoneSelected);
       }
       else {
       
              document.location.href=this.PalettePageName + this.CurrentPaletteCode;
       }
       
    
    }
    
    
    this.DoTextureFilter=function(variantArray,variantSubGroupArray,filter) {
                this.DoHidePlaceHolder();
                // initialize the Variant Sub groups 
                for ( var k=0; k < variantSubGroupArray.length; k++)
                     variantSubGroupArray[k].style.display = '';
                var x;
                for(x in variantArray ){
                    if ( variantArray[x].attributes["texture"].value == filter )
                        variantArray[x].style.display = '';
                    else
                        variantArray[x].style.display = 'none';    
                }
                // hidiing the sub group variants DIV/heading if after filetring there is no variants visible
                var IsAllVisbile = false;
                for ( var i=0; i < variantSubGroupArray.length; i++ ){
                    var divArray = variantSubGroupArray[i].getElementsByTagName('div');            
                    for ( var j=0; j<divArray.length; j++ ){
                        if ( divArray[j].className.indexOf('ShadesSwatchDiv') != -1 && divArray[j].style.display == '')
                               IsAllVisbile = true;
                    }
                    if ( ! IsAllVisbile ) 
                        variantSubGroupArray[i].style.display = 'none';
                    IsAllVisbile = false;           
                }
       
        }
        
      this.ClearTextureFilter=function(variantArray,variantSubGroupArray) {
                // initialize the Variant Sub groups 
                for ( var k=0; k < variantSubGroupArray.length; k++)
                     variantSubGroupArray[k].style.display = '';
                
                for(var x in variantArray ){
                      variantArray[x].style.display = '';
 
                }
                this.DoHidePlaceHolder();
               
        }  
      
      //
       this.DoHidePlaceHolder=function() {
               var obj1 =$get( this.PlaceHolderID)
               obj1.style.visibility='hidden';
       
       
       }     
   
  
   this.ShowThumbNailShade=  function (obj, _code,_parentPrdCode,_StockWeb) {
       var _stock=parseInt(_StockWeb);
       var _shadeAltName=this.GetVariantName(_code);
       if(_stock >=4) {
             this.DoHideOOS();
            this.VariantCode=_code;
            this.ParentCode=_parentPrdCode;
            //
            var obj1 =$get( this.PlaceHolderID)
            var x=findPosX(obj);
            var y=findPosY(obj);
            if (obj1!=null) {
                     obj1.innerHTML="<img class=\"png\" src=\"/img/product/swatch/" + _code + "_RO.png\" alt=\"" + _shadeAltName + "\" title=\"" +  _shadeAltName +"\" />";
                     PositionLayerByRelativeObject(obj,$get('DragablePlaceHolderDiv_ON'),-12,-12);
        
             }
        }
        else {
          //alert("This shade is temporary unavailable. Please select another shade.");
          this.DoHidePlaceHolder();
          this.DoShowOOS(obj);
        }
   
    } 
    
    
    this.DoShowOOS=function(obj) {
       
        var obj1 =$get( this.OOSLayerId)
        //obj1.style.visibility='visible';
        if (obj1!=null) {
                PositionLayerByRelativeObject(obj,$get(this.OOSLayerId),-12,-12);
        }
    
    }
    
     this.DoHideOOS=function() {
       
        var obj1 =$get( this.OOSLayerId)
        if (obj1!=null) {
                obj1.style.visibility='hidden';
        }
    
    }
    

   
    this.RemoveShadeFromPalette=function(_varCode) {
       // alert('this feature is under construction, checkout at the end of this week');
       // return;
        if (_varCode==this.DeafultPaletteUPC) {
                    this.IsDefaultPaletteRemoved=true; //set default as removed and not to be added again till page is refreshged
                    this.DoActualRemove(_varCode);
        }
        else {
                    var _resetPath=this.PathToImage + this.spacerImage
                    for(var i=0; i<=this.CustomTemplateMaxShade; i++) 
                    {
                                var _objId="DRAGDROP_" + i;
                                var _obj=$get(_objId);
                                
                                if (_obj!=null) {
                                    if (_obj.src.indexOf(_varCode)!=-1) {
                                      _obj.src=_resetPath; //clear the image
                                      _obj.alt="";
                                      _obj.title="";
                                      this.DoActualRemove(_varCode);
                                      break;
                                    }
                                    
                                 }
                       
                    
                    }
        }
        //alert(this.CurrentvariantsInPalette);
        this.BuildRows();
    }
    
    
    this.DoActualRemove=function(_varCode) {
    
                 if ( this.CurrentvariantsInPalette!='') {
                           var codewithsemi=_varCode + ":";
                           //alert(this.CurrentvariantsInPalette);
                           if (this.CurrentvariantsInPalette.indexOf(codewithsemi)!=-1 ) {
                               this.CurrentvariantsInPalette=this.CurrentvariantsInPalette.replace(codewithsemi,'');
                              // alert(codewithsemi);
                           }
                           else {
                              this.CurrentvariantsInPalette=this.CurrentvariantsInPalette.replace(_varCode,'');
                           }
                           //clean the last : if any.
                           if (this.CurrentvariantsInPalette!="" ) {
                                var lastStr = this.CurrentvariantsInPalette.substring(this.CurrentvariantsInPalette.length-1, this.CurrentvariantsInPalette.length); 
                                if (lastStr==":") {
                                        this.CurrentvariantsInPalette=this.CurrentvariantsInPalette.substring(0, this.CurrentvariantsInPalette.length-1)
                                }
                           }
                    }
    
    }
   
   
   this.ResetAll=function() 
   {
       // alert('this feature is under construction, checkout at the end of this week');
       // return;
        var _resetPath=this.PathToImage + this.spacerImage
        for(var i=0; i<=this.CustomTemplateMaxShade; i++) 
        {
                    var _objId="DRAGDROP_" + i;
                     var _obj=$get(_objId);
                    if (_obj!=null) {
                     _obj.src=_resetPath;
                     }
           
        
        }
        this.CurrentvariantsInPalette='';
        this.CurrentImageIdsInPalette='';
        this.IsDefaultPaletteRemoved=false;
        this.DeafultPaletteUPC="";
        this.BuildRows();
        /*
        var _obj=$get( this.PaletteRowsLayerID);
        if (_obj!=null) {
           
            _obj.innerHTML="";
       }
       */
       
   
   }
   
   
   this.MeetBasicRule=function(_obj) {
      var _continue=false;
      if (CustomPaletteObject.CustomTemplateRule.indexOf('#')!=-1) {
          var _ruleString=CustomPaletteObject.CustomTemplateRule;
          var rule_array=_ruleString.split("#");
          for (var i = 0; i < rule_array.length ; i++) {
                 //alert(rule_array[i]);
                   if (rule_array[i].indexOf(this.ParentCode) !=-1) {
                       if (rule_array[i].indexOf(_obj.id) !=-1) {
                          _continue=true;
                           break;
                       }
                   }
         }
          
      
      }
      else {_continue=true;}
     return _continue;
   
   }
   this.DoFinalDrop=function (_obj) {
       var _obj1 =$get( this.PlaceHolderID);
       if ( this.CurrentvariantsInPalette.indexOf(this.VariantCode)!=-1) {//it means same shade can not be added twice.
           _obj1.style.left='0px';
           return;
       }
      
      var imgLeft=findPosX(_obj);
      var imgW=_obj.width;
      var imgTop=findPosY(_obj);
      var imgH=_obj.height;
      var LW=parseInt(imgLeft) + parseInt(imgW);
      var TH=parseInt(imgTop) + parseInt(imgH);
      
     
      var placeholderLeft=findPosX(_obj1);
      var placeholderTop=findPosY(_obj1);
      if (placeholderLeft>=imgLeft && placeholderLeft<=LW) {
         if (placeholderTop>=imgTop && placeholderTop<=TH) {
              //alert(this.ParentCode);
               if (this.MeetBasicRule(_obj)) {
                        if (_obj.src.indexOf(this.spacerImage)!=-1) {//replace only if image is a spacer image
                                 this.ResolveDefaultPalette();//resolve default one.
                                _obj.src=this.PathToImage + this.VariantCode + "_dd.gif";
                                if ( this.CurrentvariantsInPalette!='') {
                                     this.CurrentvariantsInPalette= this.CurrentvariantsInPalette + ":";
                                }
                                this.CurrentvariantsInPalette= this.CurrentvariantsInPalette + this.VariantCode;
                               //build rows
                                this.BuildRows();
                              _obj.alt=this.GetVariantName(this.VariantCode);
                              _obj.title= _obj.alt;
                           
                        }
                }
          _obj1.style.left='0px';
         }
        
      
      }
      
   }
   
    this.DoDrag=function(_event,_id){
          //alert(_id);
           dragStart(_event,_id);
    }
      
   
  
    
    this.AddPaletteToBag=function(){
          //alert('this feature is under construction, checkout at the end of this week');
         // return;
                 var message1="Please create your palette and then click on add to shopping bag";
                 if (this.CurrentvariantsInPalette!="") { 
                    var selectedAddToBagItems= new Array();//???
                    //
                    var selectedVarSKU= new Array();
                    var variantCodes= this.CurrentvariantsInPalette;
                    var selectedVarSKU=variantCodes.split(":");
                    //quantity will need to be all 1
                    var selectedVarQty=new Array();           
                    
                       if(selectedVarSKU.length>0)
                       {
                          for(var i=0; i<selectedVarSKU.length; i++)
                                {
                                    selectedVarQty[i]=1;
                                }        
                          _WebServiceAPI.AddMultipleProductsToCart(GetCurrentCustomerID(),selectedVarSKU,selectedVarQty,AddPaletteProductToBagOnComplete);
                             
                              
                       }
                       else {   alert(_message1); }
           }
           else {
           
             
              alert(message1);
           }
     
     }
     
     this.AddPaletteProductOnComplete=function(result) {
     
       DoWait();
       document.location.href=this.BasketPageURL;
       DoDefault();
       // alert(result);
       // alert(result.ActivityStatus);
        //alert(result.ErrorString);
        //    alert("Status:"+result.ActivityStatus+"\nError:"+result.ErrorString);
       
       //TO DO here do processing of error messages:
       //if (result != null) {
          
          
          //display the shopping cart totatls
          // _WebServiceAPI.RetrieveShoppingCart(GetCurrentCustomerID(),_ShoppingCartBubble_Class.RetrieveShoppingCartResultHandler);
         //_WebServiceAPI.RetrieveShoppingCart(GetCurrentCustomerID(),test123);
       
       // }
     }
     
    this.BuildRows=function() {
       var sb = new StringBuilder();
       var totalPrice=parseFloat('00.00');;
       if (this.CurrentvariantsInPalette.length>0) {  
                     var rowString="";
                     
                     var variantCodes= this.CurrentvariantsInPalette;
                     var variantCodes_array=variantCodes.split(":");
                     for (var i = 0; i < variantCodes_array.length ; i++) {
                         var code=variantCodes_array[i];
                         //row counter
                         var rowno=i+1;
                         //price
                         var _varprice="$0.00";
                         var _pricewithnoDollarSign=parseFloat('00.00');
                         
                         var objPriceID= variantCodes_array[i] + '_PRICE';
                         var objPrice=$get(objPriceID);
                         if (objPrice!=null) {
                             _varprice=objPrice.innerHTML;
                             _pricewithnoDollarSign=parseFloat(_varprice.replace('$',''));
                             totalPrice=totalPrice + _pricewithnoDollarSign;
                         }
                         //name
                         var _varName="";
                         var objNameID= variantCodes_array[i] + '_SHADE_NAME';
                         var objName=$get(objNameID);
                         if (objName!=null) {
                             _varName=objName.innerHTML;
                         }
                         sb.append("<div>");
                          sb.append("<table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
                            sb.append("<tr>");
                                sb.append("<td>");
                                          sb.append("<div style=\"width:150px\" class=\"float_L BRDR_1px40grey_R ABLACK12_R padding05_B\">" + rowno + ". " + _varName + "</div>");
                                              sb.append("<div style=\"width:70px\" align=\"center\" class=\"float_L BRDR_1px40grey_R padding05_B ABLACK12_R\">" + _varprice + "</div>");
                                          sb.append("<div style=\"width:55px\" align=\"center\" class=\"float_L\"><a href=\"javascript:RemoveShadeFromPalette('" + variantCodes_array[i] +"');\" class=\"ABLACK12_R\"><u>remove</u></a></div>");
                                      sb.append("</td>");
                                sb.append("</tr>");
                            sb.append("</table>");
                        sb.append("</div>")
                    
                     
                    }
                   
     }
      var _obj=$get( this.PaletteRowsLayerID);
           if (_obj!=null) {
                        //alert(sb.toString());
               _obj.innerHTML=sb.toString();
           }
       var _objTotal=$get(this.TotalPriceLayerID);
       if (_objTotal!=null) {
           var _formatPrice = totalPrice.toFixed(2);
           _objTotal.innerHTML="$" +  _formatPrice;
          // alert(_objTotal.innerHTML.length);
       }
       
       
    }    
    
     this.GetVariantName=function(_vcode) {
        var _varName="";
         var objNameID= _vcode + '_SHADE_NAME';
         var objName=$get(objNameID);
         if (objName!=null) {
             _varName=objName.innerHTML;
         }
       return _varName;
     }
    
    this.GetSelectedPaletteCode=function(){
             var code='';
             var _obj=document.getElementsByName(this.RadioButtonID);
                 if (_obj.length) { //if array
                     for (i=0; i < _obj.length; i++) {
                       
                                if (_obj[i].checked == true) {
                                    code=_obj[i].value;
                                     break;
                                }
                        }
                  }
                  else {if (_obj.checked == true) {
                           code=_obj.value; 
                        }
            } 
            if (code!='') {
               this.CurrentPaletteCode=code; 
            }    
            return code;
        }


    


}

//
var CustomPaletteObject=new CustomPalette_Class();

//
function RemoveShadeFromPalette(_varCode) {

  CustomPaletteObject.RemoveShadeFromPalette(_varCode);
}

function AddPaletteProductToBagOnComplete(result) {
    DoDefault();
   _loadPowerSystem=false;
   _loadLastItem=false;
   CustomPaletteObject.AddPaletteProductOnComplete(result); 
  

}

function test123(result) {
   DoDefault();
   alert(result);

}
//
function Browser() {

  var ua, s, i;

  this.isIE    = false;
  this.isNS    = false;
  this.version = null;

  ua = navigator.userAgent;

  s = "MSIE";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isIE = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  s = "Netscape6/";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = parseFloat(ua.substr(i + s.length));
    return;
  }

  // Treat any other "Gecko" browser as NS 6.1.

  s = "Gecko";
  if ((i = ua.indexOf(s)) >= 0) {
    this.isNS = true;
    this.version = 6.1;
    return;
  }
}

var browser = new Browser();

// Global object to hold drag information.

var dragObj = new Object();
dragObj.zIndex = 100;
//
function dragStart(event, id) {
  var el;
  var x, y;

  // If an element id was given, find it. Otherwise use the element being
  // clicked on.

  if (id)
    dragObj.elNode = document.getElementById(id);
  else {
    if (browser.isIE)
      dragObj.elNode = window.event.srcElement;
    if (browser.isNS)
      dragObj.elNode = event.target;

    // If this is a text node, use its parent element.

    if (dragObj.elNode.nodeType == 3)
      dragObj.elNode = dragObj.elNode.parentNode;
  }

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Save starting positions of cursor and element.

  dragObj.cursorStartX = x;
  dragObj.cursorStartY = y;
  dragObj.elStartLeft  = parseInt(dragObj.elNode.style.left, 10);
  dragObj.elStartTop   = parseInt(dragObj.elNode.style.top,  10);

  if (isNaN(dragObj.elStartLeft)) dragObj.elStartLeft = 0;
  if (isNaN(dragObj.elStartTop))  dragObj.elStartTop  = 0;

  // Update element's z-index.

  dragObj.elNode.style.zIndex = ++dragObj.zIndex;

  // Capture mousemove and mouseup events on the page.

  if (browser.isIE) {
    document.attachEvent("onmousemove", dragGo);
    document.attachEvent("onmouseup",   dragStop);
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS) {
    document.addEventListener("mousemove", dragGo,   true);
    document.addEventListener("mouseup",   dragStop, true);
    event.preventDefault();
  }
}

function dragGo(event) {

  var x, y;

  // Get cursor position with respect to the page.

  if (browser.isIE) {
    x = window.event.clientX + document.documentElement.scrollLeft
      + document.body.scrollLeft;
    y = window.event.clientY + document.documentElement.scrollTop
      + document.body.scrollTop;
  }
  if (browser.isNS) {
    x = event.clientX + window.scrollX;
    y = event.clientY + window.scrollY;
  }

  // Move drag element by the same amount the cursor has moved.

  dragObj.elNode.style.left = (dragObj.elStartLeft + x - dragObj.cursorStartX) + "px";
  dragObj.elNode.style.top  = (dragObj.elStartTop  + y - dragObj.cursorStartY) + "px";

  if (browser.isIE) {
    window.event.cancelBubble = true;
    window.event.returnValue = false;
  }
  if (browser.isNS)
    event.preventDefault();
}

function dragStop(event) {
  // Stop capturing mousemove and mouseup events.
  CustomPaletteObject.DoHidePlaceHolder();
  if (browser.isIE) {
        document.detachEvent("onmousemove", dragGo);
        document.detachEvent("onmouseup",   dragStop);
  }
  if (browser.isNS) {
        document.removeEventListener("mousemove", dragGo,   true);
        document.removeEventListener("mouseup",   dragStop, true);
  }
}



function CreateControl(DivID, CLSID, ObjectID, WIDTH, HEIGHT, URL, FLASHVARS, AUTOSTART)
{
  var d = document.getElementById(DivID);
  var objectTag = '<object classid=' + CLSID + ' id="' + ObjectID + '" width=' + WIDTH + ' height=' + HEIGHT +' codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0">';
  objectTag = objectTag + '<param name="allowScriptAccess" value="sameDomain">';
  objectTag = objectTag + '<param name="movie" value="' + URL + '">'
  objectTag = objectTag + '<param name="FlashVars" value=' + FLASHVARS + '/>';
  objectTag = objectTag + '<param name="quality" value="high">'  
  objectTag = objectTag + '<param name="bgcolor" value="#ffffff">'  
  objectTag = objectTag + '<param name="wmode" value="transparent">'
  //objectTag = objectTag + '<param name="autoStart" value=' + AUTOSTART + '/>';
 objectTag = objectTag + '<embed src="' + URL + '" wmode="transparent" flashVars="' + FLASHVARS + '" quality="high" bgcolor="#ffffff"  width="' + WIDTH + '" height="' + HEIGHT +'" name="main" align="middle" allowscriptaccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"/>';
// objectTag = objectTag + '<embed src="' + URL + '" quality="high" bgcolor="#ffffff" width="' + WIDTH + '" height="' + HEIGHT +'" name="main" align="middle" allowscriptaccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"/>';
 
 objectTag = objectTag + "</object>";
// alert(objectTag);
  d.innerHTML = objectTag;
 // alert (d.innerHTML);
}


 function SetPaletteBenefitText(objid){   
       // alert(objid);
        var obj=document.getElementById(objid);
        
        if (obj!=null) {   
                var benefitStr=obj.innerHTML;
                //alert(benefitStr);
                var sb = new StringBuilder();
                 var strArray = benefitStr.split('|');
                for ( var i=0; i<strArray.length; i++){
                    if ( strArray[i] != '' )
                            sb.append("<li>" + strArray[i] + "</li>");
                }
                obj.innerHTML = sb;
        }         
    }
    
     function SetPaletteIngriedientText(prdCode){  
              var objAll=document.getElementById("ALL_Ingredients_" + prdCode);
              var ingredientsStr="";
              if (objAll!=null) {
                 ingredientsStr=objAll.innerHTML;
              }
              var objMayContain=document.getElementById('MayContain_Text_' + prdCode);
              var objIngred=document.getElementById('Ingriedient_Text_' + prdCode);
             
            if ( ingredientsStr!='' ){
                        var ingredientText = ingredientsStr;
                        if (ingredientsStr.indexOf('may contain') != -1 ){
                                var mayContain = ingredientsStr.substring( (ingredientsStr.indexOf('may contain')+14) ).replace("]","");
                                if ( objMayContain!=null) {
                                     objMayContain.innerHTML = mayContain;
                                }
                         }
                
                        if (ingredientsStr.indexOf('may contain') != -1 ){
                            ingredientText = ingredientsStr.substring(0,ingredientsStr.indexOf('may contain')).replace("[+/-","");
                            ingredientText = ingredientText.replace(", ,","");
                        }  
                        if (objIngred != null ) {objIngred.innerHTML = ingredientText;}
            }            
    }












