//-----------------------------------------------------------------------
// Module name   : Payment
// Author        : Paul Battersby
// Creation Date : Jan 14/09
//
//
//  $Log:$
//------------------------------------------------------------------------

//---------------------------- INCLUDE FILES -----------------------------

var Payment = new Class({

//----------------------------- CONSTANTS --------------------------------
  GSTMULT : 1.05, // multiplication factor for calculating GST
  MONTH_INDEX : 0, // used to index in to the cuttoff date array
  DAY_INDEX   : 1,
  YEAR_INDEX  : 2,

//----------------------------- VARIABLES --------------------------------

  options : {
    earlyBirdCutoff : null, // any purchase on or before this date will not include
                            // GST. (format: January 17 1010)
    ignoreYear : true,     // true = early bird works every year

    // function to be called when something is complete
    onComplete : Class.empty
  },

  monthString : [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
  ],

  gstFree : false, // indicates if the GST is free or not.

//----------------------------- FUNCTIONS --------------------------------

  //************************************************************************
  // Name   : moneyFormat
  //  Converts a float or int into a money string with 2 decimals
  // Returns :
  //************************************************************************
  moneyFormat : function(value) {
    var numDecimals = ("" + value).split(".");

    // if there are no decimals
    if (numDecimals.length == 1) {
      value = "" + value + ".00";

    // there is one decimal
    } else if (numDecimals[1].length == 1) {
      value = "" + value + "0";

    // there are already 2 decimals
    } else {
      value = "" + value;
    } // endif
    return value;
  },

  //************************************************************************
  // Name   : revealSp
  //
  // Returns : (nothing)
  //************************************************************************
  revealSp : function() {
    var selectedIzc = $("IZC").getProperty("value");

    if (selectedIzc == "") {
      $("SP").setStyle("display","none");
      $("SPO").setStyle("display","none");
      $("amount").setProperty("value","");
      return ;
    } // endif

    // if a platinum (and gold) price exists for this IZC
    if (this.priceList["service"]["Platinum"][selectedIzc] != null) {
      $("SP").setStyle("display","block");
      $("SPO").setStyle("display","none");
    } else {
      $("SP").setStyle("display","none");
      $("SPO").setStyle("display","block");
    } // endif

    $("SP").setProperty("value","");
    $("SPO").setProperty("value","");
  },

  //************************************************************************
  // Name   : showPrice
  //
  // Returns : (nothing)
  //************************************************************************
  showPrice : function() {
    var selectedIzc = $("IZC").getProperty("value");
    var selectedSp;
    var price;

    // if a platinum (and gold) price exists for this IZC
    if (this.priceList["service"]["Platinum"][selectedIzc] != null) {
      selectedSp  = $("SP").value;
    } else {
      selectedSp  = $("SPO").value;
    } // endif

    if (selectedSp == "") {
      $("amount").setProperty("value","");
    } else {
      price = this.priceList["service"][selectedSp][selectedIzc];

      // if GST is not to be included
      if (this.gstFree) {
        price /= this.GSTMULT;
        price = price.round(2);
      } // endif

      $("price").setProperty("value",this.moneyFormat(price));
    } // endif
  },

  //************************************************************************
  // Name   : preVal
  //
  // Returns : (nothing)
  //************************************************************************
  preVal : function(formObj) {
    var validated;
    var amount;
    var izc;
    var sp;
    var paymentType;
    var phone;
    var invoiceDate;
    var invoiceAmount;

    paymentType = $(formObj.paymentType).getProperty("value");

    validated = LFORMVAL_validate(Payment.validateStruct[paymentType],formObj);
    if (!validated) {
      return false;
    } // endif

    // if this is a service package form
    if (paymentType == "servicePackage") {
      izc = $("IZC").getProperty("value");
      if ($("SP").getStyle("display") == "block")
      {
        sp = $("SP").getProperty("value");
      } else {
        sp = $("SPO").getProperty("value");
      } // endif

      // set the izc, sp
      $(formObj.os0).setProperty("value","(" + izc + ", " + sp + ")");

      amount = parseFloat($("price").getProperty("value"));

      // if wireless upgrade is included
      if ($("wirelessSensor").checked) {
        // wireless sprinkler upgrade is included
        $(formObj.item_name).setProperty("value","Sprinkler Service Package + Wireless Upgrade");

        // add the wireless upgrade
        amount += this.priceList["wirelessUpgrade"];

      // no wireless upgrade
      } else {
        $(formObj.item_name).setProperty("value","Sprinkler Service Package");
      } // endif

    // invoice
    } else {
      // read the service package price
      amount = parseFloat($("invoiceAmount").getProperty("value"));

      // store the invoice date and value
      $(formObj.os0).setProperty("value",$(formObj.invoiceDate).getProperty("value") + ", " + $(formObj.invoiceAmount).getProperty("value"));
    } // endif

    phone = $(formObj.night_phone_b).getProperty("value");

    phone = phone.replace(/-/g," ");
    $(formObj.night_phone_b).setProperty("value",phone);

    phone = $(formObj.day_phone_b).getProperty("value");
    phone = phone.replace(/-/g," ");
    $(formObj.day_phone_b).setProperty("value",phone);

    // set the paypal amount field
    $(formObj.amount).setProperty("value",amount);

    return validated;
  },

  //************************************************************************
  // Name   : initialize (constructor)
  //
  //  (object) options - (optional) configuration options. See options declaration
  //                     above for the available options
  //
  // Returns : (nothing)
  //*************************************************************************
  initialize : function(priceList,options) {
    var today = new Date();
    var cutoffDate;
    var i;

    this.setOptions(options);

    // if there is an earlybird cutoff date
    if (this.options.earlyBirdCutoff) {

      // break the cutoff date in to 3 pieces, month, date, year
      cutoffDate = this.options.earlyBirdCutoff.split(" ");

      // turn the cutoff month into a month number from 0 .. 11
      for (i = 0; i < this.monthString.length; i++) {
        if (cutoffDate[0] == this.monthString[i]) {
          cutoffDate[0] = i;
          break;
        } // endif
      } // end for

      // if this is on or before the cutoff date, don't charge GST
      if ((this.options.ignoreYear || (today.getFullYear() == cutoffDate[this.YEAR_INDEX])) &&
          (
            today.getMonth() < cutoffDate[this.MONTH_INDEX] ||
            ((today.getMonth() == cutoffDate[this.MONTH_INDEX]) && (today.getDate() <= cutoffDate[this.DAY_INDEX]))
          )
        ){
        this.gstFree = true;
      } // endif
    } // endif

    this.priceList = priceList;

    // display today's date
    var today = this.monthString[today.getMonth()] + " " + today.getDate() + " " + today.getFullYear();
    $("todaysDateInvoice").innerHTML = today;
    $("todaysDateServicePackage").innerHTML = today;

    $("IZC").addEvent("change",function() {this.revealSp()}.bind(this));
    $("SP").addEvent("change",function() {this.showPrice()}.bind(this));
    $("SPO").addEvent("change",function() {this.showPrice()}.bind(this));

    LFORMVAL_setErrorText("en","customBlank","You must select both IZC and SP");
    LFORMVAL_initForm("invoice",Payment.validateStruct.invoice,"Payment.validateStruct.invoice");
    LFORMVAL_initForm("servicePackage",Payment.validateStruct.servicePackage,"Payment.validateStruct.servicePackage");

    // display the price for the wireless upgrade
    $("wirelessPrice").innerHTML = this.moneyFormat(this.priceList["wirelessUpgrade"]);
  }

});

Payment.implement(new Events,new Options);

Payment.validateStruct = {};

Payment.validateStruct.invoice = {
  normalColor : "black",
  errorColor : "red",
  fields : {
    first_name     : ["mostChars",  "required"],
    last_name      : ["mostChars",  "required"],
    address1       : ["mostChars",   "required"],
    city           : ["mostChars",   "required"],
    zip            : ["postalCode",  "required"],
    night_phone_b  : ["phoneStrictAreaCode", "required"],
    day_phone_b    : ["phoneStrictAreaCode",  "required"],
    amount         : ["customBlank",     "required"],
    email          : ["email",     "required"],
    invoiceDate    : ["mostChars",     "required"],
    invoiceAmount  : ["mostChars",     "required"]
  }
};

Payment.validateStruct.servicePackage = {
  normalColor : "black",
  errorColor : "red",
  fields : {
    first_name     : ["mostChars",  "required"],
    last_name      : ["mostChars",  "required"],
    address1       : ["mostChars",   "required"],
    city           : ["mostChars",   "required"],
    zip            : ["postalCode",  "required"],
    night_phone_b  : ["phoneStrictAreaCode", "required"],
    day_phone_b    : ["phoneStrictAreaCode",  "required"],
    amount         : ["customBlank",     "required"],
    email          : ["email",     "required"],
    price          : ["mostChars", "required"]
  }
};

