//Add to Cart for product chart, product engine, search page and product detail.

/*
function enumerateProperties()
    {
      var pString = this + '\n\nProperties:\n---------------\n';
      for (property in this)
        {
          if (typeof this[property] == 'function') 
            {
              {pString += property + ': (function)\n';}
            }
          else
          
            {pString += property + ': ' + this[property] + '\t\t\tType: ' + typeof this[property] + '\n';}
        }
      return pString
    }
 Object.prototype.toFullString = enumerateProperties
  */

function cartAction()
   {
      var numofproducts = (this.act == 'multi') ? 'multiple' :'single' //single product add, or multi add
      var targetproductidlist = this.pid;
      if (this.act == 'a2wl'){var mode = 'addtoWL'}
      else {var mode = (this.act == 'md') ? 'choose' : 'addtocart';}
      
      //determine what kind of form we are coming from
      var formInfo = returnFormInfo(this.form) //returns an object with the properties we need
      //set up the names of the fields we need.
      var maxcol      = formInfo.maxcol;      
      
      var targetmaxrows    = formInfo.maxrows;
      var targetpagenumber = formInfo.pagenumber;
      
      if (mode == 'addtoWL')
        {          
          var thisqty = (this.quantObj) ? this.quantObj.value : 1 //if qty field exists, use its value; otherwise set qty to 1
          
          if ( (thisqty < 1) || (isNaN(parseInt(thisqty))) ) 
            {thisqty = 1;}
          else
            { thisqty = parseInt(thisqty); }
          
          var posX = this.coords.split(/_|,/)[0];
          var posY = this.coords.split(/_|,/)[1]; 
          
          
          var targetURL = '/wishlist_edit.cfm?pid=' + this.pid + '&quantity='+thisqty + '&variationidlist=' + formInfo.variationidlist + '&targetposx=' + posX + '&targetposy=' + posY + '&targetformtype=' + formInfo.formtype + '&targetformarea=' + formInfo.area + "&maxrecord=" + formInfo.maxrows + "&pagenumber=" + formInfo.pagenumber + "&maxcol=" + formInfo.maxcol + "&areatype="+ formInfo.areatype + "&frompagetype=" + js_frompagetype;
          newwindow(targetURL,'standard','wishlistwindow',560,420);
          return false;
        }
      
      if (numofproducts=="single") //single product case
      {                      
         var haserror = false ;
         //get the address id.
         if (mode == 'addtocart')
          {
           if (this.addrObj.type=="hidden") {var thisaddressid = this.addrObj.value.toString() ;}
           else {var thisaddressid = this.addrObj.options[this.addrObj.selectedIndex].value.toString() ;}
           
           if (thisaddressid == "")
           {
              alert("You must select a valid address.") ;
              this.addrObj.focus();
              haserror = true ;
           }
           else
           {targetaddressidlist = thisaddressid ;}         
         
           //get quantity && usepointpay value(s)
           if (!haserror)
           {
              //QTY
              if (this.quantObj.value=="") {targetquantitylist = 1;}
              else if (isNaN(parseInt(this.quantObj.value)))
                {
                   alert("The \'"+ js_nameforquantity + "\' field must be a number.") ;
                   this.quantObj.focus() ;
                   return;
                }
              else { targetquantitylist = parseInt(this.quantObj.value); }
              
              //USEPOINTPAY (initially assume a checkbox)
              if (this.pointObj.type.match(/hidden|text/)) {targetusepointpaylist = this.pointObj.value.toString(); }
              else if (this.pointObj.type=="checkbox")
              {
                targetusepointpaylist = (this.pointObj.checked) ? 1 : 0;
              }              
           }//end, if no error
          }//end, if adding to cart
         else
          {
            targetaddressidlist = 0;
            targetquantitylist = 0;
            targetusepointpaylist = 0;
          }//end, not adding to cart. Target address and quantity form elements may not exist in this case; bypass code and dummy up values.
        if (!haserror)
          {
            //tracking data -- what position on page.  
            
            targetposXlist = this.coords.split(/_|,/)[0]
            targetposYlist = this.coords.split(/_|,/)[1]         
          }//end, no error      
      }
      
      if (numofproducts=="multiple")// a bunch of products
      {
         var targetproductidarray = this.totalpidlist.split(","); 
                 
         //establish new arrays.
         validtargetproductidArray = new Array();
         targetquantityArray = new Array();
         targetusepointpayArray = new Array();
         targetaddressidArray = new Array();
         targetposXArray = new Array();
         targetposYArray = new Array();
         targetpagenumberArray = new Array();
         targetmaxrowsArray = new Array();
         
         //loop thru list of products         
         for (i=0;i < targetproductidarray.length;i++)
         {            
            thisQuantObj = this.form.elements[this.quantityfieldbasename + targetproductidarray[i]];
            thisPointObj = this.form.elements[this.usepointpaybasename + targetproductidarray[i]];
            haserror = false ; 
            if (thisQuantObj != undefined && thisQuantObj != null)
              {
                if ((thisQuantObj.value != '') && (isNaN(parseInt(thisQuantObj.value))))
                {
                   alert('The '+ js_nameforquantity + ' must be numeric.') ;
                   thisQuantObj.focus() ;
                   validtargetproductidlist = 0 ;
                   targetquantitylist       = 0 ;
                   targetusepointpaylist    = 0 ;
                   break ;
                }
                else if (thisQuantObj.value != '')
                {
                   if (this.allowAddSel) {thisAddressObj = this.form.elements[this.addressfieldbasename + '_' + targetproductidarray[i]];}
                   else {thisAddressObj = this.form.elements[this.addressfieldbasename]}
                   
                   thisCoordObj = this.form.elements[this.coordbasefieldname + targetproductidarray[i]];                 
                   
                   if (thisAddressObj.type == 'hidden')
                   {thisaddressid = thisAddressObj.value.toString() ;}
                   else
                   {thisaddressid = thisAddressObj.options[thisAddressObj.selectedIndex].value.toString() ;}
                   
                   if (thisaddressid == '')
                   {
                      alert('You must select a valid address.') ;
                      targetaddressidlist = "" ;
                      thisQuantObj.focus() ;
                      haserror = true ;
                   }
                   
                   if (thisaddressid == '-10')
                   {
                      alert('To add new addresses, you must add items individually.') ;
                      targetaddressidlist = "" ;
                      thisQuantObj.focus() ;
                      haserror = true ;
                   }                   
                   
                   validtargetproductidArray.push(targetproductidarray[i]);
                   targetquantityArray.push(parseInt(thisQuantObj.value));
                   
                  //get the value of this-point-pay
                   if (thisPointObj.type=="hidden") {thisusepointpayvalue = "" + thisPointObj.value; }
                   else if (thisPointObj.type=="checkbox")
                   {
                     thisusepointpayvalue = (thisPointObj.checked) ? 1 : 0;                 
                   }
                   targetusepointpayArray.push(parseInt(thisusepointpayvalue));
                   if (!haserror)
                   {
                    targetaddressidArray.push(thisaddressid)
                    targetposXArray.push(thisCoordObj.value.split("_")[0]);
                    targetposYArray.push(thisCoordObj.value.split("_")[1])
                    
                    //breed a set of maxrows/pagenumbers for each item
                    targetpagenumberArray.push(targetpagenumber)
                    targetmaxrowsArray.push(targetmaxrows)
                   }//end if !haserror
                }//end, non-empty value
             }//end, element exists
         }//end, for
         
         targetproductidlist = validtargetproductidArray.join();
         targetquantitylist = targetquantityArray.join();
         targetusepointpaylist = targetusepointpayArray.join();
         targetaddressidlist = targetaddressidArray.join();
         targetposXlist = targetposXArray.join();
         targetposYlist = targetposYArray.join();
         targetpagenumber = targetpagenumberArray.join();
         targetmaxrows = targetmaxrowsArray.join();
         
      }//end, if multiple
      
      
      if (targetproductidlist=="")
        {
        alert('Please enter a ' + js_nameforquantity + ' for at least one ' + js_nameforproduct.toLowerCase() + '.')
        }
      if ((!haserror)&&(targetproductidlist!=""))
      {
         targetform = document.defaultaddtocartform ;
         if(window.location.pathname != '/')
          {
            if (window.location.pathname != '/index.cfm') 
              {
                targetform.action = window.location.href;
              }
            var pagename = window.location.pathname;
           } 
         else
           {
            var pagename = 'index.cfm';
           }
         //set all the hidden fields and submit.
         if (js_gotocartafteradd) targetform.action = pc_siteLocation.cart;
         
         if (mode == 'choose' || formInfo.areatype == 'Variation' || formInfo.areatype == 'Detail'  || pagename == 'index.cfm') 
          {
           //var destination = "/product_detail.cfm?pid=" + targetproductidlist;
           if (!this.href) {this.href = this.getAttribute('href')}
           
           if (this.href  && (targetproductidlist.split(',').length <= 1)){var destination = decodeURI(this.href)}
           else {var destination = "/product_detail.cfm?pid=" + targetproductidlist;}
           targetform.action = destination;
           
          }
                  
         targetform.mode.value = mode;
         
         if (targetaddressidlist == -10) 
          {
            targetform.action = '/newaddress_edit.cfm';
            targetform.mode.value = "redirect";
          }
         
         if (typeof extendedFunction =='function') {extendedFunction()}
         
         targetform.targetproductidlist.value = targetproductidlist  ;
         targetform.targetquantitylist.value  = targetquantitylist   ;
         targetform.targetusepointpaylist.value  = targetusepointpaylist   ;
         targetform.targetaddressidlist.value = targetaddressidlist  ;
         targetform.targetformtype.value = formInfo.formtype;
         targetform.targetformareatype.value = formInfo.areatype;
         targetform.targetformarea.value = formInfo.area;
         targetform.variationidlist.value = formInfo.variationidlist;
         targetform.mpid.value = this.mpid;
         targetform.targetformpage.value = pagename;
         targetform.targetposx.value = targetposXlist;
         targetform.targetposy.value = targetposYlist; 
         targetform.pagenumber.value = targetpagenumber; 
         targetform.maxrecord.value = targetmaxrows
         targetform.maxcol.value = maxcol;
         
         targetform.submit() ;
         return false;
      }
   }
   

   
   
   
/* function that figures out what kind of form we're dealing with, and sets
        up the "name for" shims correctly, so the main add to cart and add to wishlist
        functions don't have to. Returns an object with the correct properties. */
            
 function returnFormInfo(formref)
  {
    var formname = formref.name;
    var formtype = formname.split("_")[0]     
    
    //determine whether this form has maxrows and variationidlist fields or not
    var hasmaxrows = false;
    var hasvariationidlist = false 
    var maxcol = formref.elements["maxcol"].value 
     
    for(var i=0; i < formref.elements.length;i++)
      {        
        if (formref.elements[i].name)
        {            
          if (formref.elements[i].name.indexOf("pickvariation") != -1 )
           {
            hasvariationidlist = true;   
           }  
         } //end, if I have a name.               
      }     
     
     if (hasvariationidlist)
       {
        var selectorfields = fieldlist.split(",");
        for (var i= 0; i < selectorfields.length; i++)
          {
            getVariation(selectorfields[i],formref)//get the value of each variation and put it into pagevariationidlist (which is actually an array)
          }
        var thisvariationidlist = pagevariationidlist.toString(); 
       }
     else //no variationidlist, set it to empty
       {
        var thisvariationidlist = '';
       }
    
    switch(formtype)
    {
    case "assocProdform": //associated product form
      {
        var blankpos = formname.indexOf("_");
        blankpos++;
        var area = formname.substr(blankpos)
        var areatype ="Associated";
        var thismaxrows = formref.elements["maxrows_associated_" + area].value;
        var thisstartrow = formref.elements["startrow_associated_" +area].value ;
        break;
      }//end case
      
    case "featuredproductsform": //featured product form
      {        
        var blankpos = formname.indexOf("_");
        blankpos++;
        var area = formname.substr(blankpos)
        var areatype ="Feature";
        var thismaxrows = formref.elements["maxrows_featured_" + area].value;
        var thisstartrow = formref.elements["startrow_featured_" +area].value ;
        break;            
      }//end case    
      
    case "manufactureform": //product detail page or group product page
      {
        var area = "manufacturer product display"
        var areatype = "Manufacturer";
        var thismaxrows = formref.elements["maxrows_manuf"].value;
        var thisstartrow = formref.elements["startrow_manuf"].value ;
        break;
      }//end case     
      
    case "productdisplayform": //group product page
      {
        var area = "group product display"
        var areatype="MainContent";
        var thismaxrows = formref.elements["maxrows_groupproduct"].value;
        var thisstartrow = formref.elements["startrow_groupproduct"].value ;
        break;
      }//end case 
      
    case "productvariationform": //product detail page or group product page
      {
        var area = "variation display"
        var areatype = "Variation";
        var thismaxrows = formref.elements["maxrows_productvariation"].value;
        var thisstartrow = formref.elements["startrow_productvariation"].value ;
        break;
      }//end case 
      
    case "recentproductsform":
      {
        var area = "recent product display"
        var areatype = "Recent Product";
        var thismaxrows = formref.elements["maxrows_recentproduct"].value;
        var thisstartrow = formref.elements["startrow_recentproduct"].value ;
        break;
      }
      
    case "searchresults":
      {
        var viewval = formref.search_viewimages.value       
        
        if (viewval == "yes")
          {
            var area = "product search images"                    
          }
        else
          {
            var area = "product search list"
          }
        var thismaxrows = formref.elements["maxrows_search"].value;
        var thisstartrow = formref.elements["startrow_search"].value ;
        var areatype = "Search";  
        var usepointpayprefix = "usepointpay_search_";           
        
        break;
      }          
     case "special":
      { 
        var blankpos = formname.indexOf("_");
        blankpos++;
        var area = formname.substr(blankpos)
        var areatype ="Special";
        var thismaxrows = formref.elements["maxrows_special_" + area].value;
        var thisstartrow = formref.elements["startrow_special_" +area].value ;
        break;            
      }//end case 
       
     default: //product detail
      {
        var area = "product detail single";
        var areatype = "Detail";
        var thismaxrows = 1;
        var thisstartrow = 1;
        break;
      }//end case          
    }//end switch
   
   var thispagenum = (formtype != "productdetailform") ? Math.floor(thisstartrow/thismaxrows) + 1 : 1;
   
  
  
   var fieldInfo = new Object()
       fieldInfo.formtype = formtype;
       fieldInfo.area = area;
       fieldInfo.areatype = areatype;
       fieldInfo.maxrows = thismaxrows;
       fieldInfo.pagenumber = thispagenum;
       fieldInfo.variationidlist = thisvariationidlist;
       fieldInfo.maxcol = maxcol;
    return fieldInfo;
  }
      
      
  function getVariation(formfieldname,formref)
    {
      //alert(getVariation.caller)
      var myslot = formfieldname.split("_")[1]; //formfield name will indicate which variation type and what kind of form control
      var formobj  = formref.elements[formfieldname];
      var myvalue
      switch(formfieldname.split("_")[0]) //branch on what type of control
        {
          case "pickvariationselect": //select box
            {
              myvalue = formobj.options[formobj.selectedIndex].value;
              break;
            } //end case        
          case "pickvariationradio": //radio buttons
            {
             //alert(formobj)
             if (!formobj.length) //one radio button
              {
                 myvalue = formobj.value
              }
             else //multiple radio buttons
               {
               
                for (var i=0; i<formobj.length; i++)
                 {
                   if (formobj[i].checked) {myvalue = formobj[i].value}
                 }
               }
              break;
            } //end radio case    
            
          default: //default case
           {
              myvalue = formobj.value;
              break;
           }  //end default case   
        }
      
      pagevariationidlist[myslot-1] = myvalue;
      targetform = document.defaultaddtocartform ;      
      
    } 
    
  Array.prototype.push = function (element) 
  {
    this[this.length] = element;
    return this.length;
  }
   
   
/* to'h 20071022 - moved handler attachment to function so it can be called 
    after engine is inserted into a page. */
function addAdd2CartHandlers(DOMnode)  
  {
    if (!document.getElementById) {return}
    if (DOMnode == null) {DOMnode = document}
    
    var formArray = DOMnode.getElementsByTagName('FORM')
    var toolmode,toolfield,elemArray,thisElement,coordbasefieldname,quantityfieldbasename,usepointpaybasename,addressfieldbasename,allowAddSel,multi,isProdDetail
    var mouseoversEnabled = (typeof btnOn == 'function' && typeof btnOff == 'function') //hook for adding image rollovers
    for (var f = 0; f < formArray.length; f++)
      {
        if (formArray[f].className.match(/chartform|PEform|PDForm|PSListForm/))//product chart form, engineform,productDetail form, loop thru its descendants
          {
            currForm = formArray[f]
            toolfield = currForm.toolmode;
            if (!toolfield){continue}
            toolmode = toolfield.value
            if(toolmode == '') {toolmode = 'button'}
            isProdDetail = currForm.className.match(/PDForm/)
            if (isProdDetail) //product detail form, base names are known
              {
                coordbasefieldname = 'coord_';
                addressfieldbasename = 'targetmemberaddressid';
                quantityfieldbasename = 'quantity_';
                usepointpaybasename = 'usepointpay_'
              }
              
            else 
              {
                coordbasefieldname = currForm.coordbasefieldname.value
                addressfieldbasename = currForm.addressfieldbasename.value
                quantityfieldbasename =  currForm.quantityfieldbasename.value
                usepointpaybasename  = currForm.usepointpaybasename.value 
              }
            
            allowAddSelfield = currForm.allowAddSel
            if (!allowAddSelfield) {continue} //current form (probably pd form) isn't allowing adding to cart. Move on to next form
            allowAddSel = allowAddSelfield.value
            targetTag = (toolmode == 'button')? 'INPUT' :'A'
            elemArray = currForm.getElementsByTagName(targetTag)
            for (i = 0; i < elemArray.length; i++)
              {
                thisElement = elemArray[i];
                if (thisElement.className.match(/add2cart|add2WL|moredetails|prodimagelink|ptitle|pc_prodZoom/))
                  {
                    idArray = thisElement.id.split('_')
                    thisElement.act = idArray[0]
                    thisElement.pid = idArray[1]
                    thisElement.mpid = idArray[2]
                    if (!thisElement.className.match(/pc_prodZoom/))
                      {
                          thisElement.coords = currForm.elements[coordbasefieldname + idArray[1]].value.toString()
                          thisElement.quantObj = currForm.elements[quantityfieldbasename + idArray[1]]
                          thisElement.pointObj = currForm.elements[usepointpaybasename + idArray[1]]
                          thisElement.addrObj = (allowAddSel == 1 || isProdDetail) ? currForm.elements[addressfieldbasename + '_' + idArray[1]] : currForm.elements[addressfieldbasename] //use shared form element if no selector
                          if (thisElement.tagName != 'INPUT'){thisElement.form = currForm;}  
                          if (toolmode == 'icon' && mouseoversEnabled && thisElement.firstChild.tagName =="IMG" && thisElement.className.match(/add2cart|add2WL|moredetails/))
                            {
                              thisElement.firstChild.onmouseover = btnOn
                              thisElement.firstChild.onmouseout = btnOff
                            }  
                      }
                   
                    
                    if(!thisElement.onclick) 
                      {
                        if (thisElement.className.match(/pc_prodZoom/)){thisElement.onclick = getProductBasics}
                        else {thisElement.onclick = cartAction}
                      }
                  }//end, element class matching                
                  
              }//end, looping over elements  
             multi = document.getElementById('multi_' + currForm.id)
             if (multi != null)//multiple adder exists
              {
                multi.act= 'multi';
                if (multi.tagName != 'INPUT'){multi.form = currForm;}              
                multi.pid = ''; multi.mpid = 0;
                multi.coordbasefieldname = coordbasefieldname;
                multi.allowAddSel = (allowAddSel == 1)
                multi.addressfieldbasename = addressfieldbasename;
                multi.quantityfieldbasename = quantityfieldbasename
                multi.usepointpaybasename = usepointpaybasename;
                multi.totalpidlist = currForm.fullproductidlist.value;
                multi.onclick = cartAction  
                if (toolmode == 'icon' && mouseoversEnabled && multi.firstChild.tagName =="IMG")
                  {
                    multi.firstChild.onmouseover = btnOn
                    multi.firstChild.onmouseout = btnOff
                  }              
              }
          }//end, form class matching
      }//end, looping over forms    
    
  }   
 
//call function  
addAdd2CartHandlers(document)
