//=====================================================================||
//      NOP Design JavaScript Shopping Cart  PAYPAL CHECKOUT           ||
//                                                                     ||
// For more information on SmartSystems, or how NOPDesign can help you ||
// Please visit us on the WWW at http://www.nopdesign.com              ||
//                                                                     ||
// Javascript portions of this shopping cart software are available as ||
// freeware from NOP Design.  You must keep this comment unchanged in  ||
// your code.  For more information contact FreeCart@NopDesign.com.    ||
//                                                                     ||
// JavaScript Shop Module, V.4.4.0                                     ||
//=====================================================================||

//---------------------------------------------------------------------||
//                       Global Options                                ||
//                      ----------------                               ||
// Shopping Cart Options, you can modify these options to change the   ||
// the way the cart functions.                                         ||
//                                                                     ||
// Language Packs                                                      ||
// ==============                                                      ||
// You may include any language pack before nopcart.js in your HTML    ||
// pages to change the language.  Simply include a language pack with  ||
// a script src BEFORE the <SCRIPT SRC="nopcart.js">... line.          ||
//  For example: <SCRIPT SRC="language-en.js"></SCRIPT>                ||
//                                                                     ||
// Options For Everyone:                                               ||
// =====================                                               ||
// * MonetarySymbol: string, the symbol which represents dollars/euro, ||
//   in your locale.                                                   ||
// * DisplayNotice: true/false, controls whether the user is provided  ||
//   with a popup letting them know their product is added to the cart ||
// * DisplayShippingColumn: true/false, controls whether the managecart||
//   and checkout pages display shipping cost column.                  ||
// * DisplayShippingRow: true/false, controls whether the managecart   ||
//   and checkout pages display shipping cost total row.               ||
// * DisplayTaxRow: true/false, controls whether the managecart        ||
//   and checkout pages display tax cost total row.                    ||
// * TaxRate: number, your area's current tax rate, ie: if your tax    ||
//   rate was 7.5%, you would set TaxRate = 0.075                      ||
// * TaxByRegion: true/false, when set to true, the user is prompted   ||
//   with TaxablePrompt to determine if they should be charged tax.    ||
//   In the USA, this is useful to charge tax to those people who live ||
//   in a particular state, but no one else.                           ||
// * TaxPrompt: string, popup message if user has not selected either  ||
//   taxable or nontaxable when TaxByRegion is set to true.            ||
// * TaxablePrompt: string, the message the user is prompted with to   ||
//   select if they are taxable.  If TaxByRegion is set to false, this ||
//   has no effect. Example: 'Arizona Residents'                       ||
// * NonTaxablePrompt: string, same as above, but the choice for non-  ||
//   taxable people.  Example: 'Other States'                          ||
// * MinimumOrder: number, the minium dollar amount that must be       ||
//   purchased before a user is allowed to checkout.  Set to 0.00      ||
//   to disable.                                                       ||
// * MinimumOrderPrompt: string, Message to prompt users with when     ||
//   they have not met the minimum order amount.                       ||
//                                                                     ||
// Payment Processor Options:                                          ||
// ==========================                                          ||
// * PaymentProcessor: string, the two digit payment processor code    ||
//   for support payment processor gateways.  Setting this field to    ||
//   anything other than an empty string will override your OutputItem ||
//   settings -- so please be careful when receiving any form data.    ||
//   Support payment processor gateways are:                           ||
//    * Authorize.net (an)                                             ||
//    * Worldpay      (wp)                                             ||
//    * LinkPoint     (lp)
//                                                                     ||
// Options For Programmers:                                            ||
// ========================                                            ||
// * OutputItem<..>: string, the name of the pair value passed at      ||
//   checkouttime.  Change these only if you are connecting to a CGI   ||
//   script and need other field names, or are using a secure service  ||
//   that requires specific field names.                               ||
// * AppendItemNumToOutput: true/false, if set to true, the number of  ||
//   each ordered item will be appended to the output string.  For     ||
//   example if OutputItemId is 'ID_' and this is set to true, the     ||
//   output field name will be 'ID_1', 'ID_2' ... for each item.       ||
// * HiddenFieldsToCheckout: true/false, if set to true, hidden fields ||
//   for the cart items will be passed TO the checkout page, from the  ||
//   ManageCart page.  This is set to true for CGI/PHP/Script based    ||
//   checkout pages, but should be left false if you are using an      ||
//   HTML/Javascript Checkout Page. Hidden fields will ALWAYS be       ||
//   passed FROM the checkout page to the Checkout CGI/PHP/ASP/Script  ||
//---------------------------------------------------------------------||

//Options for Everyone:
MonetarySymbol        = 'R$';
DisplayNotice         = false;
DisplayShippingColumn = true;
DisplayShippingRow    = false; /* change to true at checkout time */
DisplayTaxRow         = false;
TaxRate               = 0.00;
TaxByRegion           = false;
TaxPrompt             = ' ';
TaxablePrompt         = ' ';
NonTaxablePrompt      = ' ';
MinimumOrder          = 0.00;
MinimumOrderPrompt    = ' ';

//Payment Processor Options:
PaymentProcessor      = 'paypal';

//Options for Programmers:
OutputItemId          = 'item_number_';
OutputItemQuantity    = 'quantity_';
OutputItemPrice       = 'amount_';
OutputItemName        = 'item_name_';
OutputItemShipping    = 'shipping_';
OutputItemAddtlInfo   = 'ADDTLINFO_';
OutputItemBusiness    = 'ian@wiccaworkshop.com.br'; /* Business name for PayPal */
OutputItemCurrency    = 'BRL'; /* Currency for PayPal */
OutputItemReturn      = 'http://www.wiccaworkshop.com.br'; /* Return URL for PayPal */
OutputOrderSubtotal   = 'SUBTOTAL';
OutputOrderShipping   = 'SHIPPING';
OutputOrderTax        = 'TAX';
OutputOrderTotal      = 'TOTAL';
AppendItemNumToOutput = true;
HiddenFieldsToCheckout = false;


//=====================================================================||
//---------------------------------------------------------------------||
//    YOU DO NOT NEED TO MAKE ANY MODIFICATIONS BELOW THIS LINE        ||
//---------------------------------------------------------------------||
//=====================================================================||


//---------------------------------------------------------------------||
//                      Language Strings                               ||
//                     ------------------                              ||
// These strings will not be used unless you have not included a       ||
// language pack already.  You should NOT modify these, but instead    ||
// modify the strings in language-**.js where ** is the language pack  ||
// you are using.                                                      ||
//---------------------------------------------------------------------||

   strSorry  = "Desculpe, seu carrinho está cheio, por favor vá até o caixa. Nosso sistema de compras suporta apenas 18 itens. Acima de 18 produtos, por favor  efetue dois ou mais pedidos.";
   strAdded  = " adicionado(a) ao sua Cesta de Compras. Click no 'ver compras' para VERIFICAR e MODIFICAR os itens na sua cesta. Aqui voce pode ADCIONAR mas unidades dos itens pedidos, ou removar itens do seu cesta.";
   strRemove = "Clique 'Ok' para remover este produto de seu carrinho.";
   strILabel = "&nbsp;Codigo:";
   strDLabel = "&nbsp;&nbsp;Descrição&nbsp;&nbsp;";
   strQLabel = "&nbsp;&nbsp;Qtde&nbsp;&nbsp;";
   strPLabel = "&nbsp;&nbsp;Preço&nbsp;&nbsp;";
   strSLabel = "&nbsp;Ex. Preço&nbsp;";
   strThumbLabel = "Imagem";
   strRLabel = "";
   strRButton= "Remover";
   strSUB    = "SUBTOTAL";
   strSHIP   = "SHIPPING";
   strTAX    = "TAX";
   strTOT    = "TOTAL";
   strErrQty = "Quantidade inválida.";
   strNewQty = 'Por favor digite uma nova Quantidade:';


//---------------------------------------------------------------------||
// FUNCTION:    CKquantity                                             ||
// PARAMETERS:  Quantity to                                            ||
// RETURNS:     Quantity as a number, and possible alert               ||
// PURPOSE:     Make sure quantity is represented as a number          ||
//---------------------------------------------------------------------||
function CKquantity(checkString) {
   var strNewQuantity = "";

   for ( i = 0; i < checkString.length; i++ ) {
      ch = checkString.substring(i, i+1);
      if ( (ch >= "0" && ch <= "9") || (ch == '.') )
         strNewQuantity += ch;
   }

   if ( strNewQuantity.length < 1 )
      strNewQuantity = "1";

   return(strNewQuantity);
}


//---------------------------------------------------------------------||
// FUNCTION:    AddToCart                                              ||
// PARAMETERS:  Form Object                                            ||
// RETURNS:     Cookie to user's browser, with prompt                  ||
// PURPOSE:     Adds a product to the user's shopping cart             ||
//---------------------------------------------------------------------||
function AddToCart(thisForm) {
   var iNumberOrdered = 0;
   var bAlreadyInCart = false;
   var notice = "";
   iNumberOrdered = GetCookie("NumberOrdered");

   if ( iNumberOrdered == null )
      iNumberOrdered = 0;

   if ( thisForm.ID_NUM == null )
      strID_NUM    = "";
   else
      strID_NUM    = thisForm.ID_NUM.value;

   if ( thisForm.QUANTITY == null )
      strQUANTITY  = "1";
   else
      strQUANTITY  = thisForm.QUANTITY.value;
      if ( strQUANTITY <0 ) strQUANTITY = 1; 

   if ( thisForm.PRICE == null )
      strPRICE     = "0.00";
   else
      strPRICE     = thisForm.PRICE.value;

   if ( thisForm.NAME == null )
      strNAME      = "";
   else
      strNAME      = thisForm.NAME.value;

   if ( thisForm.SHIPPING == null )
      strSHIPPING  = "0.00";
   else
      strSHIPPING  = thisForm.SHIPPING.value;

	if ( thisForm.WEIGHT == null )
      strWEIGHT  = "0.00";
   else
      strWEIGHT  = thisForm.WEIGHT.value;
      
     if ( thisForm.Thumb == null )
      strThumb      = "";
   else
      strThumb      = thisForm.Thumb.value;

   if ( thisForm.ADDITIONALINFO == null ) {
      strADDTLINFO = "";
   } else {
      strADDTLINFO = thisForm.ADDITIONALINFO[thisForm.ADDITIONALINFO.selectedIndex].value;
   }
   if ( thisForm.ADDITIONALINFO2 != null ) {
      strADDTLINFO += "; " + thisForm.ADDITIONALINFO2[thisForm.ADDITIONALINFO2.selectedIndex].value;
   }
   if ( thisForm.ADDITIONALINFO3 != null ) {
      strADDTLINFO += "; " + thisForm.ADDITIONALINFO3[thisForm.ADDITIONALINFO3.selectedIndex].value;
   }
   if ( thisForm.ADDITIONALINFO4 != null ) {
      strADDTLINFO += "; " + thisForm.ADDITIONALINFO4[thisForm.ADDITIONALINFO4.selectedIndex].value;
   }

   //Is this product already in the cart?  If so, increment quantity instead of adding another.
   for ( i = 1; i <= iNumberOrdered; i++ ) {
      NewOrder = "Order." + i;
      database = "";
      database = GetCookie(NewOrder);

      Token0 = database.indexOf("|", 0);
      Token1 = database.indexOf("|", Token0+1);
      Token2 = database.indexOf("|", Token1+1);
      Token3 = database.indexOf("|", Token2+1);
      Token4 = database.indexOf("|", Token3+1);
	  Token5 = database.indexOf("|", Token4+1);

      fields = new Array;
      fields[0] = database.substring( 0, Token0 );
      fields[1] = database.substring( Token0+1, Token1 );
      fields[2] = database.substring( Token1+1, Token2 );
      fields[3] = database.substring( Token2+1, Token3 );
      fields[4] = database.substring( Token3+1, Token4 );
	  fields[5] = database.substring( Token4+1, Token5 );
      fields[6] = database.substring( Token5+1, database.length );

      if ( fields[0] == strThumb &&
		   fields[1] == strID_NUM &&
           fields[3] == strPRICE  &&
           fields[4] == strNAME   &&    
           fields[6] == strADDTLINFO
         ) {
         bAlreadyInCart = true;
         dbUpdatedOrder = strThumb    + "|" +
		                  strID_NUM    + "|" +
                          (parseInt(strQUANTITY)+parseInt(fields[2]))  + "|" +
                          strPRICE     + "|" +
                          strNAME      + "|" +
                          strSHIPPING  + "|" +
                          strADDTLINFO;

         strNewOrder = "Order." + i;
         DeleteCookie(strNewOrder, "/");
         SetCookie(strNewOrder, dbUpdatedOrder, null, "/");
         notice = strQUANTITY + " " + strNAME + strAdded;
         break;
      }
   }


   if ( !bAlreadyInCart ) {
      iNumberOrdered++;

      if ( iNumberOrdered > 18 )
         alert( strSorry );
      else {
         dbUpdatedOrder = 
		                  strThumb     + "|" +    
		                  strID_NUM    + "|" + 
                          strQUANTITY  + "|" +
                          strPRICE     + "|" +
                          strNAME      + "|" +
                          strSHIPPING  + "|" +
                          strADDTLINFO;

         strNewOrder = "Order." + iNumberOrdered;
         SetCookie(strNewOrder, dbUpdatedOrder, null, "/");
         SetCookie("NumberOrdered", iNumberOrdered, null, "/");
         notice = strQUANTITY + " " + strNAME + strAdded;
      }
   }

   if ( DisplayNotice )
      alert(notice);
}


//---------------------------------------------------------------------||
// FUNCTION:    getCookieVal                                           ||
// PARAMETERS:  offset                                                 ||
// RETURNS:     URL unescaped Cookie Value                             ||
// PURPOSE:     Get a specific value from a cookie                     ||
//---------------------------------------------------------------------||
function getCookieVal (offset) {
   var endstr = document.cookie.indexOf (";", offset);

   if ( endstr == -1 )
      endstr = document.cookie.length;
   return(unescape(document.cookie.substring(offset, endstr)));
}


//---------------------------------------------------------------------||
// FUNCTION:    FixCookieDate                                          ||
// PARAMETERS:  date                                                   ||
// RETURNS:     date                                                   ||
// PURPOSE:     Fixes cookie date, stores back in date                 ||
//---------------------------------------------------------------------||
function FixCookieDate (date) {
   var base = new Date(0);
   var skew = base.getTime();

   date.setTime (date.getTime() - skew);
}


//---------------------------------------------------------------------||
// FUNCTION:    GetCookie                                              ||
// PARAMETERS:  Name                                                   ||
// RETURNS:     Value in Cookie                                        ||
// PURPOSE:     Retrieves cookie from users browser                    ||
//---------------------------------------------------------------------||
function GetCookie (name) {
   var arg = name + "=";
   var alen = arg.length;
   var clen = document.cookie.length;
   var i = 0;

   while ( i < clen ) {
      var j = i + alen;
      if ( document.cookie.substring(i, j) == arg ) return(getCookieVal (j));
      i = document.cookie.indexOf(" ", i) + 1;
      if ( i == 0 ) break;
   }

   return(null);
}


//---------------------------------------------------------------------||
// FUNCTION:    SetCookie                                              ||
// PARAMETERS:  name, value, expiration date, path, domain, security   ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Stores a cookie in the users browser                   ||
//---------------------------------------------------------------------||
function SetCookie (name,value,expires,path,domain,secure) {
   document.cookie = name + "=" + escape (value) +
                     ((expires) ? "; expires=" + expires.toGMTString() : "") +
                     ((path) ? "; path=" + path : "") +
                     ((domain) ? "; domain=" + domain : "") +
                     ((secure) ? "; secure" : "");
}


//---------------------------------------------------------------------||
// FUNCTION:    DeleteCookie                                           ||
// PARAMETERS:  Cookie name, path, domain                              ||
// RETURNS:     null                                                   ||
// PURPOSE:     Removes a cookie from users browser.                   ||
//---------------------------------------------------------------------||
function DeleteCookie (name,path,domain) {
   if ( GetCookie(name) ) {
      document.cookie = name + "=" +
                        ((path) ? "; path=" + path : "") +
                        ((domain) ? "; domain=" + domain : "") +
                        "; expires=Thu, 01-Jan-70 00:00:01 GMT";
   }
}

//---------------------------------------------------------------------||
// FUNCTION:    MoneyFormat                                            ||
// PARAMETERS:  Number to be formatted                                 ||
// RETURNS:     Formatted Number                                       ||
// PURPOSE:     Reformats Dollar Amount to #.## format                 ||
//---------------------------------------------------------------------||
function moneyFormat(input) {
   var dollars = Math.floor(input);
   var tmp = new String(input);

   for ( var decimalAt = 0; decimalAt < tmp.length; decimalAt++ ) {
      if ( tmp.charAt(decimalAt)=="." )
         break;
   }

   var cents  = "" + Math.round(input * 100);
   cents = cents.substring(cents.length-2, cents.length)
           dollars += ((tmp.charAt(decimalAt+2)=="9")&&(cents=="00"))? 1 : 0;

   if ( cents == "0" )
      cents = "00";

   return(dollars + "." + cents);
}


//---------------------------------------------------------------------||
// FUNCTION:    RemoveFromCart                                         ||
// PARAMETERS:  Order Number to Remove                                 ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Removes an item from a users shopping cart             ||
//---------------------------------------------------------------------||
function RemoveFromCart(RemOrder) {
   if ( confirm( strRemove ) ) {
      NumberOrdered = GetCookie("NumberOrdered");
      for ( i=RemOrder; i < NumberOrdered; i++ ) {
         NewOrder1 = "Order." + (i+1);
         NewOrder2 = "Order." + (i);
         database = GetCookie(NewOrder1);
         SetCookie (NewOrder2, database, null, "/");
      }
      NewOrder = "Order." + NumberOrdered;
      SetCookie ("NumberOrdered", NumberOrdered-1, null, "/");
      DeleteCookie(NewOrder, "/");
      location.href=location.href;
   }
}


//---------------------------------------------------------------------||
// FUNCTION:    ChangeQuantity                                         ||
// PARAMETERS:  Order Number to Change Quantity                        ||
// RETURNS:     Null                                                   ||
// PURPOSE:     Changes quantity of an item in the shopping cart       ||
//---------------------------------------------------------------------||
function ChangeQuantity(OrderItem,NewQuantity) {
   if ( isNaN(NewQuantity) ) {
      alert( strErrQty );
   } else {
      NewOrder = "Order." + OrderItem;
      database = "";
      database = GetCookie(NewOrder);

      Token0 = database.indexOf("|", 0);
      Token1 = database.indexOf("|", Token0+1);
      Token2 = database.indexOf("|", Token1+1);
      Token3 = database.indexOf("|", Token2+1);
      Token4 = database.indexOf("|", Token3+1);
	  Token5 = database.indexOf("|", Token4+1);

      fields = new Array;
      fields[0] = database.substring( 0, Token0 );
      fields[1] = database.substring( Token0+1, Token1 );
      fields[2] = database.substring( Token1+1, Token2 );
      fields[3] = database.substring( Token2+1, Token3 );
      fields[4] = database.substring( Token3+1, Token4 );
	  fields[5] = database.substring( Token4+1, Token5 );
      fields[6] = database.substring( Token5+1, database.length );

      dbUpdatedOrder = fields[0] + "|" +
	                   fields[1] + "|" +                 
                       NewQuantity + "|" +
                       fields[3] + "|" +
                       fields[4] + "|" +
                       fields[5] + "|" +
                       fields[6];
      strNewOrder = "Order." + OrderItem;
      DeleteCookie(strNewOrder, "/");
      SetCookie(strNewOrder, dbUpdatedOrder, null, "/");
      location.href=location.href;      
   }
}


//---------------------------------------------------------------------||
// FUNCTION:    GetFromCart                                            ||
// PARAMETERS:  Null                                                   ||
// RETURNS:     Product Table Written to Document                      ||
// PURPOSE:     Draws current cart product table on HTML page          ||
//              **DEPRECATED FUNCTION, USE ManageCart or Checkout**    ||
//---------------------------------------------------------------------||
function GetFromCart( fShipping ) {
   ManageCart( );
}


//---------------------------------------------------------------------||
// FUNCTION:    RadioChecked                                           ||
// PARAMETERS:  Radio button to check                                  ||
// RETURNS:     True if a radio has been checked                       ||
// PURPOSE:     Form fillin validation                                 ||
//---------------------------------------------------------------------||
function RadioChecked( radiobutton ) {
   var bChecked = false;
   var rlen = radiobutton.length;
   for ( i=0; i < rlen; i++ ) {
      if ( radiobutton[i].checked )
         bChecked = true;
   }    
   return bChecked;
} 


//---------------------------------------------------------------------||
// FUNCTION:    QueryString                                            ||
// PARAMETERS:  Key to read                                            ||
// RETURNS:     value of key                                           ||
// PURPOSE:     Read data passed in via GET mode                       ||
//---------------------------------------------------------------------||
QueryString.keys = new Array();
QueryString.values = new Array();
function QueryString(key) {
   var value = null;
   for (var i=0;i<QueryString.keys.length;i++) {
      if (QueryString.keys[i]==key) {
         value = QueryString.values[i];
         break;
      }
   }
   return value;
} 

//---------------------------------------------------------------------||
// FUNCTION:    QueryString_Parse                                      ||
// PARAMETERS:  (URL string)                                           ||
// RETURNS:     null                                                   ||
// PURPOSE:     Parses query string data, must be called before Q.S.   ||
//---------------------------------------------------------------------||
function QueryString_Parse() {
   var query = window.location.search.substring(1);
   var pairs = query.split("&"); for (var i=0;i<pairs.length;i++) {
      var pos = pairs[i].indexOf('=');
      if (pos >= 0) {
         var argname = pairs[i].substring(0,pos);
         var value = pairs[i].substring(pos+1);
         QueryString.keys[QueryString.keys.length] = argname;
         QueryString.values[QueryString.values.length] = value;
      }
   }
}


//---------------------------------------------------------------------||
// FUNCTION:    ManageCart                                             ||
// PARAMETERS:  Null                                                   ||
// RETURNS:     Product Table Written to Document                      ||
// PURPOSE:     Draws current cart product table on HTML page          ||
//---------------------------------------------------------------------||
function ManageCart( ) {
   var iNumberOrdered = 0;    //Number of products ordered
   var fTotal         = 0;    //Total cost of order
   var fTax           = 0;    //Tax amount
   var fShipping      = 0.00;    //Shipping amount
   var strTotal       = "";   //Total cost formatted as money
   var strTax         = "";   //Total tax formatted as money
   var strShipping    = "";   //Total shipping formatted as money
   var strOutput      = "";   //String to be written to page
   var bDisplay       = true; //Whether to write string to the page (here for programmers)

   iNumberOrdered = GetCookie("NumberOrdered");
   if ( iNumberOrdered == null )
      iNumberOrdered = 0;

  if ( bDisplay ) 
strOutput = "<TABLE CELLSPACING=1 CELLPADDING=0 BORDER=0 CLASS=\"nopcart\"><TR>" + 
                  "<TD CLASS=\"nopheader\"ALIGN=CENTER><B>"+strThumbLabel+"</B></TD>" +
				  "<TD CLASS=\"nopheader\"ALIGN=CENTER><B>"+strILabel+"</B></TD>" +
                  "<TD CLASS=\"nopheader\"ALIGN=CENTER><B>"+strDLabel+"</B></TD>" +
                  "<TD CLASS=\"nopheader\"ALIGN=CENTER><B>"+strQLabel+"</B></TD>" +
                  "<TD CLASS=\"nopheader\"ALIGN=CENTER><B>"+strPLabel+"</B></TD>" +
                  "<TD CLASS=\"nopheader\"ALIGN=CENTER><B>"+strSLabel+"</B></TD>" +
                  "<TD CLASS=\"nopheader\"ALIGN=CENTER><B>"+strRLabel+"</B></TD></TR>";

   if ( iNumberOrdered == 0 ) {
      strOutput += "<TR><TD COLSPAN=6 CLASS=\"nopentry\"><CENTER><BR><B>Seu carrinho está vazio</B><BR><BR></CENTER></TD></TR>";
   }

   for ( i = 1; i <= iNumberOrdered; i++ ) {
      NewOrder = "Order." + i;
      database = "";
      database = GetCookie(NewOrder);

      Token0 = database.indexOf("|", 0);
      Token1 = database.indexOf("|", Token0+1);
      Token2 = database.indexOf("|", Token1+1);
      Token3 = database.indexOf("|", Token2+1);
      Token4 = database.indexOf("|", Token3+1);
	Token5 = database.indexOf("|", Token4+1);

      fields = new Array;
      fields[0] = database.substring( 0, Token0 );
	fields[1] = database.substring( Token0+1, Token1 );                 // Product ID
      fields[2] = database.substring( Token1+1, Token2 );          // Quantity
      fields[3] = database.substring( Token2+1, Token3 );          // Price
      fields[4] = database.substring( Token3+1, Token4 );          // Product Name/Description
      fields[5] = database.substring( Token4+1, Token5 );          // Shipping Cost
      fields[6] = database.substring( Token5+1, database.length ); //Additional Information

      
      fprodpris  = (parseInt(fields[2]) * parseFloat(fields[3]) );
      fTotal     += (parseInt(fields[2]) * parseFloat(fields[3]) );
      fTax        = (fTotal * TaxRate);
      strTotal    = moneyFormat(fTotal);
      strTax      = moneyFormat(fTax);
      strShipping = moneyFormat(fShipping);

      if ( bDisplay ) {
         strOutput += "<TR><TD CLASS=\"nopentry\" ALIGN=CENTER>"  + fields[0] + "</TD> <TD CLASS=\"nopentry\" ALIGN=CENTER>"  + fields[1] + "</TD>";
		 

         if ( fields[6] == "" )
            strOutput += "<TD CLASS=\"nopentry\" ALIGN=CENTER>"  + fields[4] + "</TD>";
         else
            strOutput += "<TD CLASS=\"nopentry\" ALIGN=CENTER>"  + fields[4] + " - <I>"+ fields[6] + "</I></TD>";

         strOutput += "<TD CLASS=\"nopentry\" ALIGN=CENTER><INPUT TYPE=TEXT class=checkoutinput NAME=Q SIZE=2 VALUE=\"" + fields[2] + "\" onChange=\"ChangeQuantity("+i+", this.value);\"></TD>";
         strOutput += "<TD CLASS=\"nopentry\" ALIGN=CENTER>"+ moneyFormat(fields[3]) + " </TD>";


	strOutput += "<TD CLASS=\"nopentry\" ALIGN=RIGHT >"+ moneyFormat(fprodpris) + "</TD>"; //OL

      strOutput += "<TD CLASS=\"nopentry\" ALIGN=CENTER><input type=button value=\" "+strRButton+" \" onClick=\"RemoveFromCart("+i+")\" class=\"nopbutton\"></TD></TR>";
	

         
         if ( !DisplayShippingColumn ) {
         strOutput += "<TD CLASS=\"nopentry\" COLSPAN=2 ALIGN=CENTER><input type=button value=\" "+strRButton+" \" onClick=\"RemoveFromCart("+i+")\" class=\"nopbutton\"></TD></TR>";
      }}

      if ( AppendItemNumToOutput ) {
         strFooter = i;
      } else {
         strFooter = "";
      }
      if ( HiddenFieldsToCheckout ) {
  
		 strOutput += "<input type=hidden name=\"" + OutputItemId        + strFooter + "\" value=\"" + fields[1] + "\">";
         strOutput += "<input type=hidden name=\"" + OutputItemQuantity  + strFooter + "\" value=\"" + fields[2] + "\">";
         strOutput += "<input type=hidden name=\"" + OutputItemPrice     + strFooter + "\" value=\"" + fields[3] + "\">";
         strOutput += "<input type=hidden name=\"" + OutputItemName      + strFooter + "\" value=\"" + fields[4] + "\">";
         strOutput += "<input type=hidden name=\"" + OutputItemShipping  + strFooter + "\" value=\"" + fields[5] + "\">";
         strOutput += "<input type=hidden name=\"" + OutputItemAddtlInfo + strFooter + "\" value=\"" + fields[6] + "\">";
      }

   }

   if ( bDisplay ) {
      strOutput += "<TR><TD CLASS=\"noptotal\" COLSPAN=5><B>"+strSUB+"</B></TD>";
      strOutput += "<TD CLASS=\"noptotal\" COLSPAN=2 ALIGN=CENTER><B>" + MonetarySymbol + strTotal + "</B></TD>";
      strOutput += "</TR>";
   
if ( DisplayTaxRow || TaxByRegion ) {
         if ( TaxByRegion ) {
            strOutput += "<TR><TD CLASS=\"noptotal\" COLSPAN=4><B>"+strTAX+"</B></TD>";
            strOutput += "<TD CLASS=\"noptotal\" COLSPAN=2><B>";
            strOutput += "<input type=radio name=\""+OutputOrderTax+"\" value=\"" + strTax + "\">";
            strOutput += TaxablePrompt + ": " + MonetarySymbol + strTax;
            strOutput += "<BR><input type=radio name=\""+OutputOrderTax+"\" value=\"0.00\">";
            strOutput += NonTaxablePrompt + ": " + MonetarySymbol + "0.00";
            strOutput += "</B></TD>";
            strOutput += "</TR>";
         }
   
 else {
      
            strOutput += "<TR><TD CLASS=\"noptotal\" COLSPAN=4><B>"+strTAX+"</B></TD>";
            strOutput += "<TD CLASS=\"noptotal\" COLSPAN=2><B>" + MonetarySymbol + strTax + "</B></TD>";
            strOutput += "</TR>";
         }
      }

     
      strOutput += "</TABLE>";

      if ( HiddenFieldsToCheckout ) {
         strOutput += "<input type=hidden name=\""+OutputOrderSubtotal+"\" value=\""+ MonetarySymbol + strTotal + "\">";
         strOutput += "<input type=hidden name=\""+OutputOrderShipping+"\" value=\""+ MonetarySymbol + strShipping + "\">";
         strOutput += "<input type=hidden name=\""+OutputOrderTax+"\"      value=\""+ MonetarySymbol + strTax + "\">";
         strOutput += "<input type=hidden name=\""+OutputOrderTotal+"\"    value=\""+ MonetarySymbol + moneyFormat((fTotal + fShipping + fTax)) + "\">";
      }
   }
   g_TotalCost = (fTotal + fShipping + fTax);

   document.write(strOutput);
   document.close();
}

//---------------------------------------------------------------------||
// FUNCTION:    ValidateCart                                           ||
// PARAMETERS:  Form to validate                                       ||
// RETURNS:     true/false                                             ||
// PURPOSE:     Validates the managecart form                          ||
//---------------------------------------------------------------------||
var g_TotalCost = 0;
function ValidateCart( theForm ) {
   if ( TaxByRegion ) {
      if ( !RadioChecked(eval("theForm."+OutputOrderTax)) ) {
         alert( TaxPrompt );
         return false;
      }
   }

   if ( MinimumOrder >= 0.01 ) {
      if ( g_TotalCost < MinimumOrder ) {
         alert( MinimumOrderPrompt );
         return false;
      }
   }

   return true;
}

//---------------------------------------------------------------------||
// FUNCTION:    CheckoutCart                                           ||
// PARAMETERS:  Null                                                   ||
// RETURNS:     Product Table Written to Document                      ||
// PURPOSE:     Draws current cart product table on HTML page for      ||
//              checkout.                                              ||
//---------------------------------------------------------------------||
function CheckoutCart() {
   var iNumberOrdered = 0;    //Number of products ordered
   var fTotal         = 0;    //Total cost of order
   var fTax           = 0;    //Tax amount
   var fShipping      = 0;    //Shipping amount
   var fWeight        = 0;    //Weight
   var strTotal       = "";   //Total cost formatted as money
   var strTax         = "";   //Total tax formatted as money
   var strShipping    = "";   //Total shipping formatted as money
   var strWeight      = 0;   //Total Weight
   var strOutput      = "";   //String to be written to page
   var bDisplay       = true; //Whether to write string to the page (here for programmers)
   var strPP          = "";   //Payment Processor Description Field
   var strZone        = "";
   var zone;
   
   
	var zone = decodeURIComponent(window.location.search.substring(6)) || "";
	strZone = zone;
		
	DisplayShippingRow = false;
   iNumberOrdered = GetCookie("NumberOrdered");
   if ( iNumberOrdered == null )
      iNumberOrdered = 0;

   if ( TaxByRegion ) {
      QueryString_Parse();
      fTax = parseFloat( QueryString( OutputOrderTax ) );
      strTax = moneyFormat(fTax);
   }

   if ( bDisplay )
      strOutput = "<TABLE CLASS=\"nopcart\"><TR>" +
                  "<TD CLASS=\"nopheader\"><B>"+strILabel+"</B></TD>" +
                  "<TD CLASS=\"nopheader\"><B>"+strDLabel+"</B></TD>" +
                  "<TD CLASS=\"nopheader\"><B>"+strQLabel+"</B></TD>" +
                  "<TD CLASS=\"nopheader\"><B>"+strPLabel+"</B></TD>" +
                  (DisplayShippingColumn?"<TD CLASS=\"nopheader\"><B>"+strSLabel+"</B></TD>":"") +
                  "</TR>";
	  
   for ( i = 1; i <= iNumberOrdered; i++ ) {
      NewOrder = "Order." + i;
      database = "";
      database = GetCookie(NewOrder);

      Token0 = database.indexOf("|", 0);
      Token1 = database.indexOf("|", Token0+1);
      Token2 = database.indexOf("|", Token1+1);
      Token3 = database.indexOf("|", Token2+1);
      Token4 = database.indexOf("|", Token3+1);
	  Token5 = database.indexOf("|", Token4+1);

      fields = new Array;
      fields[0] = database.substring( 0, Token0 );                //thumb
      fields[1] = database.substring( Token0+1, Token1 );          // Product ID
      fields[2] = database.substring( Token1+1, Token2 );          // Quantity
      fields[3] = database.substring( Token2+1, Token3 );          // Price
      fields[4] = database.substring( Token3+1, Token4 );          // Product Name/Description
	  fields[5] = database.substring( Token4+1, Token5 );          // Shipping Cost
      fields[6] = database.substring( Token5+1, database.length ); //Additional Information

      fprodpris  = (parseInt(fields[2]) * parseFloat(fields[3]) );
      fTotal     += (parseInt(fields[2]) * parseFloat(fields[3]) );
      fShipping  += (parseInt(fields[2]) * parseFloat(fields[5]) );
	  
      if ( !TaxByRegion ) fTax = (fTotal * TaxRate);
      strTotal    = moneyFormat(fTotal);
      if ( !TaxByRegion ) strTax = moneyFormat(fTax);
	  strShipping = moneyFormat(fShipping);
	  

      if ( bDisplay ) {
         strOutput += "<TR><TD CLASS=\"nopentry\">"  + fields[1] + "</TD>";

         if ( fields[6] == "" )
            strOutput += "<TD CLASS=\"nopentry\">"  + fields[4] + "</TD>";
         else
            strOutput += "<TD CLASS=\"nopentry\">"  + fields[4] + " - <I>"+ fields[6] + "</I></TD>";

         strOutput += "<TD CLASS=\"nopentry\">" + fields[2] + "</TD>";
         strOutput += "<TD CLASS=\"nopentry\">"+ MonetarySymbol + moneyFormat(fields[3]) + "</TD>";
         strOutput += "<TD CLASS=\"nopentry\" ALIGN=RIGHT >"+ moneyFormat(fprodpris) + "</TD>"; //OL
        

         strOutput += "</TR>";
      }


      if ( AppendItemNumToOutput ) {
         strFooter = i;
      } else {
         strFooter = "";
      }
      
         strOutput += "<input type=hidden name=\"" + OutputItemId        + strFooter + "\" value=\"" + fields[1] + "\">";
         strOutput += "<input type=hidden name=\"" + OutputItemQuantity  + strFooter + "\" value=\"" + fields[2] + "\">";
         strOutput += "<input type=hidden name=\"" + OutputItemPrice     + strFooter + "\" value=\"" + fields[3] + "\">";
         strOutput += "<input type=hidden name=\"" + OutputItemName      + strFooter + "\" value=\"" + fields[4] + "\">";
         strOutput += "<input type=hidden name=\"" + OutputItemAddtlInfo + strFooter + "\" value=\"" + fields[6] + "\">";
   }
   
   if ( bDisplay ) {
      strOutput += "<TR><TD CLASS=\"noptotal\" COLSPAN=4><B>"+strSUB+"</B></TD>";
      strOutput += "<TD CLASS=\"noptotal\"><B>" + MonetarySymbol + strTotal + "</B></TD>";
      strOutput += "</TR>";

      strOutput += "</TABLE>";
     
         strOutput += "<input type=hidden name=\""+OutputOrderSubtotal+"\" value=\""+ MonetarySymbol + strTotal + "\">";
         strOutput += "<input type=hidden name=\""+OutputOrderShipping+"\" value=\""+ MonetarySymbol + strShipping + "\">";
         strOutput += "<input type=hidden name=\""+OutputOrderTax+"\"      value=\""+ MonetarySymbol + strTax + "\">";
         strOutput += "<input type=hidden name=\""+OutputOrderTotal+"\"    value=\""+ MonetarySymbol + moneyFormat((fTotal + fShipping + fTax)) + "\">";

      
      if ( PaymentProcessor == 'an') {
         //Process this for Authorize.net WebConnect
         strOutput += "<input type=hidden name=\"x_Version\" value=\"3.0\">";
         strOutput += "<input type=hidden name=\"x_Show_Form\" value=\"PAYMENT_FORM\">";
         strOutput += "<input type=hidden name=\"x_Description\" value=\""+ strPP + "\">";
         strOutput += "<input type=hidden name=\"x_Amount\" value=\""+ moneyFormat((fTotal + fShipping + fTax)) + "\">";
      } else if ( PaymentProcessor == 'wp') {
         //Process this for WorldPay
         strOutput += "<input type=hidden name=\"desc\" value=\""+ strPP + "\">";
         strOutput += "<input type=hidden name=\"amount\" value=\""+ moneyFormat((fTotal + fShipping + fTax)) + "\">";
      } else if ( PaymentProcessor == 'lp') {
         //Process this for LinkPoint         
         strOutput += "<input type=hidden name=\"mode\" value=\"fullpay\">";
         strOutput += "<input type=hidden name=\"chargetotal\" value=\""+ moneyFormat((fTotal + fShipping + fTax)) + "\">";
         strOutput += "<input type=hidden name=\"tax\" value=\""+ MonetarySymbol + strTax + "\">";
         strOutput += "<input type=hidden name=\"subtotal\" value=\""+ MonetarySymbol + strTotal + "\">";
         strOutput += "<input type=hidden name=\"shipping\" value=\""+ MonetarySymbol + strShipping + "\">";
         strOutput += "<input type=hidden name=\"desc\" value=\""+ strPP + "\">";
		 } else if ( PaymentProcessor == 'paypal') {
         //Process this for Paypal         
         strOutput += "<input type=hidden name=\"cmd\" value=\"_cart\">";
		 strOutput += "<input type=hidden name=\"upload\" value=\"1\">";
         strOutput += "<input type=hidden name=\"business\" value=\"" + OutputItemBusiness + "\">";
		// strOutput += "<input type=hidden name=\"discount_rate_cart\" value=\"10\" />";
         strOutput += "<input type=hidden name=\"handling_cart\" value=\"" + strShipping + "\">";
		 strOutput += "<input type=hidden name=\"no_shipping\" value=\"2\" />";
         strOutput += "<input type=hidden name=\"currency_code\" value=\"" + OutputItemCurrency + "\">";
		 strOutput += "<input type=hidden name=\"return\" value=\"" + OutputItemReturn + "\">";
      } else {
         strOutput += "<input type=hidden name=\""+OutputOrderSubtotal+"\" value=\""+ MonetarySymbol + strTotal + "\">";
         strOutput += "<input type=hidden name=\""+OutputOrderShipping+"\" value=\""+ MonetarySymbol + strShipping + "\">";
         strOutput += "<input type=hidden name=\""+OutputOrderTax+"\"      value=\""+ MonetarySymbol + strTax + "\">";
         strOutput += "<input type=hidden name=\""+OutputOrderTotal+"\"    value=\""+ MonetarySymbol + moneyFormat((fTotal + fShipping + fTax)) + "\">";
      }
   }
   document.write(strOutput);
   document.close();
}

//=====================================================================||
//               END NOP Design SmartPost Shopping Cart                ||
//=====================================================================||

function CalcPost(strZone,strWeight)
	{
//		var message = "Please go back and select your location";
//		if (strZone == "blank")
// 		{
//			alert(message);
//			return false;
//		}
//		
		if (strWeight == 0)
		{
			if (strZone == "zonea")
			{
				strShipping = 0.00;
			}
			if (strZone == "zoneb")
			{
				strShipping = 0.00;
			}
			if (strZone == "zonec")
			{
				strShipping = 0.00;
			}
			if (strZone == "zoned")
			{
				strShipping = 0.00;
			}
			return(strShipping);
		}
		
		if (strZone == "local")
		{
			if (strWeight < 500)
			{
				strShipping = 6.00;
			}
			else if (strWeight < 3000)
			{
				strShipping = 10.00;
			}
			else if (strWeight < 6000)
			{
				strShipping = 20.00;
			}
			else 
			{
				strShipping = 40.00;
			}
			return(strShipping);
		}
		
		if (strWeight < 250)
		{
			if (strZone == "zonea")
			{
				strShipping = 7.50;
			}
			if (strZone == "zoneb")
			{
				strShipping = 8.50;
			}
			if (strZone == "zonec")
			{
				strShipping = 9.50;
			}
			if (strZone == "zoned")
			{
				strShipping = 11.50;
			}
			return(strShipping);
		}
		
		if (strWeight < 500)
		{
			if (strZone == "zonea")
			{
				strShipping = 11.00;
			}
			if (strZone == "zoneb")
			{
				strShipping = 13.50;
			}
			if (strZone == "zonec")
			{
				strShipping = 15.50;
			}
			if (strZone == "zoned")
			{
				strShipping = 19.00;
			}
			return(strShipping);
		}
		
		if (strWeight < 750)
		{
			if (strZone == "zonea")
			{
				strShipping = 15.00;
			}
			if (strZone == "zoneb")
			{
				strShipping = 18.00;
			}
			if (strZone == "zonec")
			{
				strShipping = 21.50;
			}
			if (strZone == "zoned")
			{
				strShipping = 26.75;
			}
			return(strShipping);
		}

		if (strWeight < 1000)
		{
			if (strZone == "zonea")
			{
				strShipping = 18.50;
			}
			if (strZone == "zoneb")
			{
				strShipping = 23.00;
			}
			if (strZone == "zonec")
			{
				strShipping = 27.50;
			}
			if (strZone == "zoned")
			{
				strShipping = 34.50;
			}
			return(strShipping);
		}
		
		if (strWeight < 1250)
		{
			if (strZone == "zonea")
			{
				strShipping = 22.00;
			}
			if (strZone == "zoneb")
			{
				strShipping = 28.00;
			}
			if (strZone == "zonec")
			{
				strShipping = 33.50;
			}
			if (strZone == "zoned")
			{
				strShipping = 42.00;
			}
			return(strShipping);
		}
		
		if (strWeight < 1500)
		{
			if (strZone == "zonea")
			{
				strShipping = 25.50;
			}
			if (strZone == "zoneb")
			{
				strShipping = 32.50;
			}
			if (strZone == "zonec")
			{
				strShipping = 40.00;
			}
			if (strZone == "zoned")
			{
				strShipping = 50.00;
			}
			return(strShipping);
		}
		
		if (strWeight < 1750)
		{
			if (strZone == "zonea")
			{
				strShipping = 30.00;
			}
			if (strZone == "zoneb")
			{
				strShipping = 37.50;
			}
			if (strZone == "zonec")
			{
				strShipping = 45.50;
			}
			if (strZone == "zoned")
			{
				strShipping = 57.50;
			}
			return(strShipping);
		}
		
		if (strWeight < 2000)
		{
			if (strZone == "zonea")
			{
				strShipping = 40.00;
			}
			if (strZone == "zoneb")
			{
				strShipping = 42.50;
			}
			if (strZone == "zonec")
			{
				strShipping = 51.50;
			}
			if (strZone == "zoned")
			{
				strShipping = 65.00;
			}
			return(strShipping);
		}
		
		if (strWeight >= 2000)
		{
			if (strZone == "zonea")
			{
				strShipping = 50.00;
			}
			if (strZone == "zoneb")
			{
				strShipping = 58.50;
			}
			if (strZone == "zonec")
			{
				strShipping = 60.00;
			}
			if (strZone == "zoned")
			{
				strShipping = 70.00;
			}
			return(strShipping);
		}
	}

function MM_openBrWindow(theURL,winName,features) 
 	{
		window.open(theURL,winName,features);
	}

//---------------------------------------------------------------------||
// FUNCTION: Print_total                                               ||
// PARAMETERS: true/false if you want MonetarySymbol added to string   ||
// RETURNS: Total cost currently racked up by shopper                  ||
// PURPOSE: Aesthetics                                                 ||
//---------------------------------------------------------------------||
function Print_total(bSymbol) {
var strOutput = ""; //String to be written to page
var strTotal = ""; //Total cost formatted as money
var fTotal = 0;
var iNumberOrdered = 0; //Number of products ordered

iNumberOrdered = GetCookie("NumberOrdered");
if ( iNumberOrdered == null )
iNumberOrdered = 0;

for ( i = 1; i <= iNumberOrdered; i++ ) {

NewOrder = "Order." + i;
database = "";
database = GetCookie(NewOrder);

Token0 = database.indexOf("|", 0);
Token1 = database.indexOf("|", Token0+1);
Token2 = database.indexOf("|", Token1+1);
Token3 = database.indexOf("|", Token2+1);
Token4 = database.indexOf("|", Token3+1);

fields = new Array;
fields[0] = database.substring( 0, Token0 ); // Product ID
fields[1] = database.substring( Token0+1, Token1 ); // Quantity
fields[2] = database.substring( Token1+1, Token2 ); // Price
fields[3] = database.substring( Token2+1, Token3 ); // Product Name/Description
fields[4] = database.substring( Token3+1, Token4 ); // Weight
fields[5] = database.substring( Token4+1, database.length ); //Additional Information

fTotal += (parseInt(fields[2]) * parseFloat(fields[3]) );
}
strTotal = moneyFormat(fTotal);
strOutput+=strTotal;
if ( bSymbol )
   strOutput = MonetarySymbol + strOutput
document.write(strOutput);
}

//---------------------------------------------------------------------||
// FUNCTION: Print_total_products                                      ||
// PARAMETERS: true/false if you want "item(s)" added to string        ||
// RETURNS: Total cost currently racked up by shopper                  ||
// PURPOSE: Aesthetics                                                 ||
//---------------------------------------------------------------------||
function Print_total_products(bVerbose) {
var strOutput = ""; //String to be written to page
var fTotal = 0;
var iNumberOrdered = 0; //Number of products ordered

iNumberOrdered = GetCookie("NumberOrdered");
if ( iNumberOrdered == null )
iNumberOrdered = 0;

for ( i = 1; i <= iNumberOrdered; i++ ) {

NewOrder = "Order." + i;
database = "";
database = GetCookie(NewOrder);

Token0 = database.indexOf("|", 0);
Token1 = database.indexOf("|", Token0+1);
Token2 = database.indexOf("|", Token1+1);
Token3 = database.indexOf("|", Token2+1);
Token4 = database.indexOf("|", Token3+1);

fields = new Array;
fields[0] = database.substring( 0, Token0 ); // Product ID
fields[1] = database.substring( Token0+1, Token1 ); // Quantity
fields[2] = database.substring( Token1+1, Token2 ); // Price
fields[3] = database.substring( Token2+1, Token3 ); // Product Name/Description
fields[4] = database.substring( Token3+1, Token4 ); // Weight
fields[5] = database.substring( Token4+1, database.length ); //Additional Information

fTotal += (parseInt(fields[2]));
}

strOutput+=fTotal;
if ( bVerbose ) {
   if (fTotal == 1) {
      strOutput+=" item"
   }
   else {
      strOutput+=" items"
   }
}
document.write(strOutput);
}

//---------------------------------------------------------------------||
// FUNCTION: Cart_is_empty                                             ||
// PARAMETERS: none                                                    ||
// RETURNS: Total true if cart is empty, false otherwise               ||
// PURPOSE: Aesthetics                                                 ||
//---------------------------------------------------------------------||
function Cart_is_empty( ) {
   iNumInCart = GetCookie("NumberOrdered");

   if ( iNumInCart == null ) iNumInCart = 0;

   if ( iNumInCart == 0 ) return true;

   return false;

}

//=====================================================================||
//               END NOP Design SmartPost Shopping Cart                ||
//=====================================================================||
function wopen(url, name, w, h)
{
// Fudge factors for window decoration space.
 // In my tests these work well on all platforms & browsers.
w += 32;
h += 96;
 var win = window.open(url,
  name, 
  'width=' + w + ', height=' + h + ', ' +
  'location=no, menubar=no, ' +
  'status=no, toolbar=no, scrollbars=no, resizable=no');
 win.resizeTo(w, h);
 win.focus();
}
// -->
/*

Project:	Input Placeholder Text
Title:		Automatic population of form fields with contents of title attributes
Author      Jon Gibbins (aka dotjay)
Created:	13 Aug 2005
Modified:	26 Oct 2009



Notes:

Add the following classes to text inputs or textareas to get the 
desired behaviour:

auto-select
	Will pre-populate the input with the title attribute and select the
	text when it receives focus.

auto-clear
	Will pre-populate the input with the title attribute and clear the 
	text when it receives focus. Note: if auto-select and auto-clear 
	are set, auto-select takes precedence.

populate
	Will just populate the input with the title attribute.

NB: A class name of "placeholder" is set on form inputs that have 
placeholder text in them. This allows you to style the inputs 
differently when there is user input versus placeholder text, e.g.
input.placeholder,
textarea.placeholder{
color: #777;
}



Potential additions:

Add in handling of default text if an initial value is detected (line 
60, line 93, etc) using something like:
if (!el.defaultValue) continue;
el.onfocus = function() {
	if (this.value == this.defaultValue) this.value = "";
}
el.onblur = function() {
	if (this.value == "") this.value = this.defaultValue;
}


*/

function hasClass(el,cls) {
	return el.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}
function addClass(el,cls) {
    if (!this.hasClass(el,cls)) el.className += " "+cls;
}
function removeClass(el,cls) {
    if (hasClass(el,cls)) {
        var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
        el.className = el.className.replace(reg,' ');
    }
}
function addLoadEvent(func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    } else {
        window.onload = function() {
            if (oldonload) {
                oldonload();
            }
            func();
        }
    }
}

function initFormPlaceholders() {

	if (!document.getElementsByTagName) return true;

	ourForms = document.getElementsByTagName('form');

	// go through each form
	var numForms = ourForms.length;
	for (var i=0;i<numForms;i++) {

		// go through each form element
		var numFormElements = ourForms[i].elements.length;
		for (var j=0;j<numFormElements;j++) {

			var el = ourForms[i].elements[j];

			// ignore submit buttons
			if (el.type == "submit") continue;

			// if we got a text type input or textarea
			if ((el.type == "text") || (el.type == "textarea")) {
				// only populate if we want it to
				// note: might want title attribute but no pre-population of inputs
				var ourClassName = el.className;
				if (ourClassName.match('auto-select') || ourClassName.match('auto-clear') || ourClassName.match('populate')) {
					// only populate if empty
					if (el.value == '') {
					    addClass(el, "placeholder");
					    el.value = el.title;
					}
				}

				// add auto select if class contains auto-select
				// note: else if below so auto-select takes precedence (assuming select is better than clear)
				if (el.className.match('auto-select')) {
					el.onfocus = function () {
						if (this.value == this.title) {
						    removeClass(this, "placeholder");
						    this.select();
						}
					}
					if (el.captureEvents) el.captureEvents(Event.FOCUS);

					el.onblur = function () {
						if (this.value == '') {
						    this.value = this.title;
						}
						if (this.value == this.title) {
						    addClass(this, "placeholder");
						}
					}
					if (el.captureEvents) el.captureEvents(Event.BLUR);
				}

				// add auto clear if class contains auto-clear
				else if (el.className.match('auto-clear')) {
					el.onfocus = function () {
						if (this.value == this.title) {
						    removeClass(this, "placeholder");
						    this.value = '';
						}
					}
					if (el.captureEvents) el.captureEvents(Event.FOCUS);

					el.onblur = function () {
						if (this.value == '') {
						    this.value = this.title;
						}
						if (this.value == this.title) {
						    addClass(this, "placeholder");
						}
					}
					if (el.captureEvents) el.captureEvents(Event.BLUR);
				}
			}

		}

	}

}

addLoadEvent(initFormPlaceholders);


