
// -----------------------------------------------------------------------------------------------------------
// This script contains the function to automatically calculate the price per shirt based on user selections
// The  auto loader function executs the AJAX functions and the AJAX functions executes the wrapper function.
// The functions contained in this scripts are
// Definition variables for important amounts
// Auto loader function                                                       ---  startPriceCalculator()
// AJAX functions                                                             ---  process()
// Wrapper function                                                           ---  cpc_wrapper() 
// Letter conter function                                                     ---  cpc_countLetters()
// Font Style amount calculator.                                              ---  cpc_getAmount()
// Function to figure out the amount based on the selected T-shirt or Symbol  ---  cpc_getAmount()
// Function for blinking letters                                              ---  cpc_blink()
// Function for changing colors                                               ---  cpc_color()
// Utility functions such as money formatter, numeric value validator, a trim function for strings
// Date Created: September 16,  2009
// Date Updated: September 18,  2009
// -----------------------------------------------------------------------------------------------------------

//Define variables 

                  //Font Style    //Amount per character
FONT_STYLE =  [   
                 ['Block',        0.00],
				 ['Jester',       0.00],
				 ['Nuptial',      0.20],
                 ['Curly',        0.30],
                 ['Block-1.5',    0.30],
				 ['Cursive',      0.40],
				 ['Royal',        0.40],
                 ['Edwardian',    0.80],
                 ['Block-16ss',   0.80],
                 ['Double',       0.80],
                 ['Lucky',        2.00]
              ];


LETTERS_NOCHARGE_NUM  = 5;     //  The number of letters without charge
LETTERS_MAX           = 55;    // Maximum number of letters if this number is exceeded the count will default to this number.
BASE_PRICE            = 29.90  // The base price of a shirt
PRICE_PER_LETTER      = 0.60;  // The price of each additional letter
PRICE_PER_SHIRT_MSG   = 'Price Per Shirt $';   // Price per shirt text before dollar value concatenation



//Sets a new BASE_PRICE if BASE_PRICE_PAGE variable is defined
if (typeof BASE_PRICE_PAGE != 'undefined') {
   BASE_PRICE = BASE_PRICE_PAGE;
}


//Initializer Function 
function startPriceCalculator() {

   //Runs the  AJAX Script  to start the price calculator
   process();
}

// Wrapper Function 
// The wrapper function which kicks off all sub processes to calculate total price
function  cpc_wrapper() {
   var cntLetter         = 0;     //Number of letters per line
   var cntLetter_orig    = 0;     //The count of letters without any Maximum number or included letter logic
   var cntLetter_total   = 0;     //Total Number of Letters with maximum logic minus No letters with included letters
   var fontstyle_amount  = 0;      //font style amount 
   var style_amount      = 0.00;     //shirt or symbol style amount
   var extra_charges     = 0.00;     //Total extra charges
   var extra_ltr_charge  = 0.00;  //Extra Letter Charge Value




   // Count Letters from Line 1. Then  Get the style from Line 1. Then calculate extra charges
   cntLetter = cpc_countLetters('Product_Attributes[4]:value');
   fontstyle_amount =  cpc_getAmount('Product_Attributes[5]:value', FONT_STYLE);
   extra_ltr_charge  =  (cntLetter * fontstyle_amount);
   cntLetter_orig = cntLetter + cntLetter_orig;


   // Count Letters from Line 2. Then  Get the style from Line 2. Then calculate extra charges
   cntLetter = cpc_countLetters('Product_Attributes[7]:value');
   fontstyle_amount =  cpc_getAmount('Product_Attributes[8]:value', FONT_STYLE);
   extra_ltr_charge =   (cntLetter * fontstyle_amount) + extra_ltr_charge;
   cntLetter_orig = cntLetter + cntLetter_orig;

   // Count Letters from Line 3. Then  Get the style from Line 3. Then calculate extra charges
   cntLetter = cpc_countLetters('Product_Attributes[10]:value');
   fontstyle_amount =  cpc_getAmount('Product_Attributes[11]:value', FONT_STYLE);
   extra_ltr_charge =   (cntLetter * fontstyle_amount) + extra_ltr_charge;
   cntLetter_orig = cntLetter + cntLetter_orig;

   // Count Letters from Back 1. Then  Get the style from Back 1. Then calculate extra charges
   cntLetter = cpc_countLetters('Product_Attributes[18]:value');
   fontstyle_amount =  cpc_getAmount('Product_Attributes[19]:value', FONT_STYLE);
   extra_ltr_charge  =  (cntLetter * fontstyle_amount) + extra_ltr_charge;
   cntLetter_orig = cntLetter + cntLetter_orig;

   // Count Letters from Back 2. Then  Get the style from Back 2. Then calculate extra charges
   cntLetter = cpc_countLetters('Product_Attributes[21]:value');
   fontstyle_amount =  cpc_getAmount('Product_Attributes[22]:value', FONT_STYLE);
   extra_ltr_charge  =  (cntLetter * fontstyle_amount) + extra_ltr_charge;
   cntLetter_orig = cntLetter + cntLetter_orig;

   // Count Letters from Back 3. Then  Get the style from Back 3. Then calculate extra charges
   cntLetter = cpc_countLetters('Product_Attributes[24]:value');
   fontstyle_amount =  cpc_getAmount('Product_Attributes[25]:value', FONT_STYLE);
   extra_ltr_charge  =  (cntLetter * fontstyle_amount) + extra_ltr_charge;
   cntLetter_orig = cntLetter + cntLetter_orig;

   extra_charges = extra_ltr_charge  + extra_charges;

   //This logic will only give you the number of letters above the number of free letters with a cap on LETTERS_MAX
   if (cntLetter_orig <= 0) {
         cntLetter_total = 0;
   } else if (cntLetter_orig <= LETTERS_NOCHARGE_NUM)  {
         cntLetter_total  = 0;
   } else if ( (cntLetter_orig > LETTERS_NOCHARGE_NUM) && (cntLetter_orig < LETTERS_MAX) ){
         cntLetter_total = cntLetter_orig - LETTERS_NOCHARGE_NUM;
   } else if (cntLetter_orig >= LETTERS_MAX) {
         cntLetter_total = LETTERS_MAX - LETTERS_NOCHARGE_NUM;
   }

   // Adds the extra letter charge
   extra_charges = (cntLetter_total * PRICE_PER_LETTER) + extra_charges;


   //Get the amount for the shirt style selected and add this to extra charges.
   style_amount = cpc_getStyleAmount('Product_Attributes[1]:value');
   extra_charges  = style_amount + extra_charges;



   //Get the amount for Symbol 1 and add to extra charges
   style_amount = cpc_getStyleAmount('Product_Attributes[13]:value');
   extra_charges  = style_amount + extra_charges;

   //Get the amount for Symbol 2 and add to extra charges
   style_amount = cpc_getStyleAmount('Product_Attributes[15]:value');
   extra_charges  = style_amount + extra_charges;

   //Get the amount for Back Symbol 1 and add to extra charges
   style_amount = cpc_getStyleAmount('Product_Attributes[27]:value');
   extra_charges  = style_amount + extra_charges;

   //Get the amount for Back Symbol 2 and add to extra charges
   style_amount = cpc_getStyleAmount('Product_Attributes[29]:value');
   extra_charges  = style_amount + extra_charges;

   //Add the extra charges to Extra Type charges hidden variable
   aFields = document.getElementsByName('Product_Attributes[33]:value');
   if (typeof(aFields[0]) !== 'undefined')  {
      cpc_removeAllOptions(aFields[0]);
      if  (extra_ltr_charge < 1) {
         cpc_createOption(aFields[0], outputMoney(extra_ltr_charge), outputMoney(extra_ltr_charge) + " Cents");
      } else {
         cpc_createOption(aFields[0], outputMoney(extra_ltr_charge), "$" + outputMoney(extra_ltr_charge) + " Dollars");
      }
   }

   //Add the extra letter count to Extra Letters hidden variable
   aFields = document.getElementsByName('Product_Attributes[32]:value');
   if (typeof(aFields[0]) !== 'undefined')  {
      cpc_removeAllOptions(aFields[0]);
      cpc_createOption(aFields[0],cntLetter_total,cntLetter_total + " Letters");
   }




   //Update the first Price per shirt value
   aFields = document.getElementById('shirtprice1'); 
   if (typeof(aFields) !== 'undefined')  {
      //parse the text to extract the dollar value
      old_msg = aFields.innerHTML.substring(aFields.innerHTML.indexOf('$') + 1).trim();
 
      aFields.innerHTML = PRICE_PER_SHIRT_MSG + outputMoney((BASE_PRICE + extra_charges));
      if (old_msg !=  outputMoney((BASE_PRICE + extra_charges)) ) {
         cpc_blink(0,'shirtprice1');
         //cpc_color(0,'shirtprice1');
      }
   } 

   //Update the second Price per shirt value
   aFields = document.getElementById('shirtprice2'); 
   if (typeof(aFields) !== 'undefined')  {
      //parse the text to extract the dollar value
      old_msg = aFields.innerHTML.substring(aFields.innerHTML.indexOf('$') + 1).trim();

      aFields.innerHTML = PRICE_PER_SHIRT_MSG + outputMoney((BASE_PRICE + extra_charges));
      if (old_msg !=  outputMoney((BASE_PRICE + extra_charges)) ) {
         //cpc_blink(0,'shirtprice2');
         cpc_color(0,'shirtprice2');
      }

   } 
 
/*
   // ---------      Turn On for DEBUG ----------------
   // Puts in a common on the page to see what is going on
   aFields = document.getElementById('replace');
   aFields.innerHTML=  ' shirt selected: ' + style_amount +
                       ' number of letters ' + cntLetter + " Amount of style: " + fontstyle_amount + " Total extra charge " + outputMoney(extra_charges); 
  // --------------------------------------------------
*/


}


// Letter Counter Function. Counts everything except for space, dash, comma and period. 
function cpc_countLetters(element_name) {
   var cntLetter = 0;

   //Get the letters from document
   aFields = document.getElementsByName(element_name);
   //Spaces, comma, period and dashes are not counted
   cntLetter += aFields[0].value.replace(/[\s,\.,\,,\-]+/g,'').length;


   return cntLetter;

}



// Returns the amount for a given style
function cpc_getAmount(selected_field , array_list) {

   var style_temp    = new String();
   var selected_temp = new String();

   style_selected = document.getElementsByName(selected_field);
   selected_temp  = style_selected[0].value;
    

   //Figure out which shirt style was selected
   for (i = 0; i < array_list.length; i ++ ) {
       style_temp     = array_list[i][0];

       if ( ( style_temp.trim().toUpperCase() == selected_temp.trim().toUpperCase())  ) {
          return array_list[i][1];
       }
   }
      return 0;
}


// Function to ge the amount from a selected style. 
// This automatically parses the option value to obtain the amount.
function cpc_getStyleAmount(selected_value) {

    var style_amount = 0.00; 

    //Figure out what the shirt style is
    //shirt_style = document.getElementsByName('Product_Attributes[13]:value');
    shirt_style = document.getElementsByName(selected_value);
    shirt =  shirt_style[0].options[shirt_style[0].selectedIndex].text;
   

    //parse the text to extract the value
    shirt = shirt.substring(shirt.indexOf('$') + 1).trim();

    //If the value is numeric assign to style_amount
    if (checkNumeric(shirt))  {
       style_amount = shirt;
    } 
   
    return  parseFloat(style_amount);
}



// --------------------------------------- AJAX Functions  -------------------------------

// stores the reference to the XMLHttpRequest object
var xmlHttp = createXmlHttpRequestObject(); 

// when set to true, display detailed error messages
var showErrors = false;

// creates an XMLHttpRequest instance
function createXmlHttpRequestObject() 
{
  // will store the reference to the XMLHttpRequest object
  var xmlHttp;
  // this should work for all browsers except IE6 and older
  try
  {
    // try to create XMLHttpRequest object
    xmlHttp = new XMLHttpRequest();
  }
  catch(e)
  {
    // assume IE6 or older
    var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
                                    "MSXML2.XMLHTTP.5.0",
                                    "MSXML2.XMLHTTP.4.0",
                                    "MSXML2.XMLHTTP.3.0",
                                    "MSXML2.XMLHTTP",
                                    "Microsoft.XMLHTTP");
    // try every prog id until one works
    for (var i=0; i<XmlHttpVersions.length && !xmlHttp; i++) 
    {
      try 
      { 
        // try to create XMLHttpRequest object
        xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
      } 
      catch (e) {} // ignore potential error
    }
  }
  // return the created object or display an error message
  if (!xmlHttp) {
     // alert("Error creating the XMLHttpRequest object."); 
  } else { 
    return xmlHttp;
  }
}


// make asynchronous HTTP request using the XMLHttpRequest object 
function process()
{
  // proceed only if the xmlHttp object isn't busy
  if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
  {


    //Start the wrappper script 
    cpc_wrapper();


    //Gets javafunctions.js as a dummy page to kick start xmlHttp
    xmlHttp.open("GET", "ajaxfile.js", true);  

    // define the method to handle server responses
    xmlHttp.onreadystatechange = handleServerResponse;
    // make the server request
    xmlHttp.send(null);

  }
  else
    // if the connection is busy, try again after one second  
    setTimeout('process()', 1000);
}


// function that displays an error message
function displayError($message)
{
  // ignore errors if showErrors is false
  if (showErrors)
  {
    // turn error displaying Off
    showErrors = false;
    // display error message
    alert("Error encountered: \n" + $message);
 
  }
}



// executed automatically when a message is received from the server
function handleServerResponse() 
{
  // move forward only if the transaction has completed
  if (xmlHttp.readyState == 4) 
  {
    // status of 200 indicates the transaction completed successfully
    if (xmlHttp.status == 200) 
    {

      // restart sequence
      setTimeout('process()', 1000);
    } 
    // a HTTP status different than 200 signals an error
    else 
    {
       //displayError(e.toString());
       displayError(xmlHttp.statusText);
    }
  }
}

// --------------------------------------- End AJAX Functions ----------------------------


// --------------------------------------  Utility Functions -----------------------------

// Adds a trim function to strings
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}


// Formatter for Money
function outputMoney(number) {
    return outputDollars(Math.floor(number-0) + '') + outputCents(number - 0);
}

function outputDollars(number) {
    if (number.length <= 3)
        return (number == '' ? '0' : number);
    else {
        var mod = number.length%3;
        var output = (mod == 0 ? '' : (number.substring(0,mod)));
        for (i=0 ; i < Math.floor(number.length/3) ; i++) {
            if ((mod ==0) && (i ==0))
                output+= number.substring(mod+3*i,mod+3*i+3);
            else
                output+= ',' + number.substring(mod+3*i,mod+3*i+3);
        }
        return (output);
    }
}

function outputCents(amount) {
    amount = Math.round( ( (amount) - Math.floor(amount) ) *100);
    return (amount < 10 ? '.0' + amount : '.' + amount);
}


// Function to check if a variable is numeric
function checkNumeric(value){

   var anum=/(^\d+$)|(^\d+\.\d+$)/;

   if (anum.test(value)) {
      return true;
   }
   return false;
}

//Deletes the Option menu
function cpc_removeAllOptions(selectbox)
{
   var i;
   for(i=selectbox.options.length-1;i>=0;i--)
   {
      selectbox.remove(i);
   }
}



//Function to create the option menu
function cpc_createOption(doc, value, text) {
   optn = document.createElement("OPTION");
   optn.text = text;
   optn.value = value;

   doc.options.add(optn);      

   doc.selectedIndex= doc.options.length-1;
}



function cpc_blink(inc,idname) {
   var speed = 300; 

      s = document.getElementById(idname); 
      if (typeof(s) !== 'undefined')  {
         if (inc  < 3) {
            s.style.visibility=(s.style.visibility=='visible')?'hidden':'visible';
            setTimeout('cpc_blink('+(inc+1) + ', \''+ idname +'\')',speed);  
         } else if (s.style.visibility=='hiddden') {
            setTimeout('cpc_blink('+(inc+1) + ', \''+ idname +'\')',speed);  
         } else  {
            s.style.visibility= 'visible';
         }
      }
}

function cpc_color(inc,idname) {
   var speed = 300; 
   //var change_to_color = '#ae3d64';  //Just Jen Pink
   var change_to_color = '#000000';  //Black

      s = document.getElementById(idname); 
      if (typeof(s) !== 'undefined')  {
         if (inc  < 3) {
            s.style.color =( (s.style.color =='#8c070a')|| (s.style.color == 'rgb(140, 7, 10)')   )?change_to_color :'#8c070a';
            setTimeout('cpc_color('+(inc+1) + ', \''+ idname +'\')',speed);  
         } else {
            s.style.color ='#8c070a';
         }
      }
}



