/**
 * Copyright 2008 WeatherBill Inc.
 */
jQuery.wb = {
  WB_CONTACT_SUBMITTED_COOKIE: "WBLongTerm",
  dialogShowFunctions: {
    modal: function(dialog){
      return dialog.modal();
    }
  },

  dialogHideFunctions: {
    modal: function(dialog){
      dialog.close();
    }
  },
  getValueFromCookie: function(name, key){
    var cookie = jQuery.cookie(name) || "";
    return cookie? this._wbCookieGetVal(cookie, key) : null;
  },

  _wbCookieGetVal: function(/*String*/ cookieValue, key){
    var pairList = cookieValue.split(",");
    for (var i=0; i < pairList.length; i++){
        var pair = pairList[i].split(":");
        if (pair[0] == key) return pair[1];
    }
  },

  addToCookie: function(name, key, value, options){
    var oldCookie = jQuery.cookie(name);
    var newCookie = (oldCookie? oldCookie + "," : "") + key + ":" + value;
    jQuery.cookie(name, newCookie, options);
  },

  getValueFromLongTermCookie: function(key){
    return this.addToCookie(this.WB_CONTACT_SUBMITTED_COOKIE, key);
  },

  addToLongTermCookie: function(key, value){
    return this.addToCookie(this.WB_CONTACT_SUBMITTED_COOKIE,
                            key, value, {expires: 365});
  },

  createDefaultContactDialog: function(){
    return jQuery('<div id="CTALeadcapDialog">'
                  + '</div>').
      append(this.createDefaultContactForm());
  },

  createDefaultContactForm: function(){
    return jQuery('<form id="CTALeadcapDialogForm" action="/forms/contact" method="POST">'
                  + '<fieldset>'
                  + '<p><label for="CTALeadcapFormFirst">First Name<span>*</span></label><input class="required" type="text" id="CTALeadcapFormFirst" name="entry.0.single" value="" /></p>'
                  + '<p><label for="CTALeadcapFormLast">Last Name<span>*</span></label><input class="required" type="text" id="CTALeadcapFormLast" name="entry.1.single" value="" /></p>'
                  + '<p><label for="CTALeadcapFormEmail">Email Address<span>*</span></label><input class="required email" id="CTALeadcapFormEmail" btype="text" name="entry.2.single" value="" /></p>'
                  + '<p><label for="CTALeadcapFormCompany">Company Name</label><input id="CTALeadcapFormCompany" type="text" name="entry.3.single" value="" /></p>'
                  + '<p><label for="CTALeadcapFormTelephone">Telephone</label><input id="CTALeadcapFormTelephone" type="text" name="entry.4.single" value="" /></p>'
                  + '<p><label for="CTALeadcapFormContactMe">&nbsp;</label><input id="CTALeadcapFormContactMe" type="checkbox" name="entry.5.single" value="yes"/><strong>Contact Me</strong></p>'
                  + '<p class="CTALeadcapFormButtons"><input id="CTALeadcapFormSubmit" type="submit" value="Submit" /></p>'
                  + '<p>If you require immediate assistance, please call us at <strong>888-924-7475</strong>.</p>'
                  + '<p id="PrivacyBlurb"><strong>Concerned about privacy?</strong> '
                  + 'So are we! View our <a onClick=\'window.open("/privacy",'
                  + '"privacy", "width=800,height=600,resizable=yes,scrollbars=yes")\' href="#">privacy policy</a>.</p>'
                  + '</form>');
  },

  getContactInfo: function(options){
    options = jQuery.extend({
                              // options to customize the contact dialog
                              dialogSelector: "#CTALeadcapDialog",
                              dialogFormSelector: "#CTALeadcapDialogForm",
                              dialogStyle: "modal", // modal currently only default
                              dialogSetup: function(){}, // A hook function called at form setup time

                              // form submission
                              onSubmitSuccess: function(response){},

                              // "remember me" controls
                              // these options provide ways to make sure visitors don't get
                              // pestered for their contact information
                              noRemember: false, // don't "remember" the form submission this time
                              noRecall: false // don't try to recall form submission this time
                            }, options);

    var dialog = jQuery(options.dialogSelector);

    // If contact dialog/form don't exist, create them.
    if (dialog.length == 0){
      dialog = jQuery.wb.createDefaultContactDialog();
      jQuery("body").append(dialog);
    }
    options.dialogSetup.call(this, dialog);

    // Perform some action that shows the dialog and returns a useful wrapper object
    var dialogWrapper = jQuery.wb.dialogShowFunctions[options.dialogStyle](dialog);

    // Turn the form identified by dialogFormSelector into an Ajax form
    jQuery(options.dialogFormSelector).ajaxForm(
      {
        success: function(response){
          jQuery.wb.dialogHideFunctions[options.dialogStyle](dialogWrapper);

          if (!options.noRemember) jQuery.wb.addToLongTermCookie("contact", "submitted");

          // The form response always comes here, even if validation fails.
          // At some point we might want to do some guessing to show an
          // error message if the info is not submitted.
          options.onSubmitSuccess(response);
        },

        beforeSubmit: function(data, form, submitOptions){
          return jQuery(options.dialogFormSelector).valid();
        }
      });
  }
};


/*
 * Simple use: $('contactButtonId').wbContact();
 *   This will create the necessary dom and display a modal dialog with
 *   First Name, Last Name, Email Address, Company Name, Telephone and submit
 *   to /forms/contact
 *
 * More complex:
 *   Users can specify dialog/form selectors using options.dialogSelect,
 *   options.dialogStyle
 *
 * Depends:
 *   jquery.simplemodal.js
 *   jquery.metadata.js
 *   jquery.validate.js
 *   jquery.cookie.js
 */
jQuery.fn.wbContact = function(options){
  options = options || {};
  if (this.length == 0) return this;

  return this.click(function(){
                      // If we're not in "no recall" mode and we can find the right cookie, skip
                      // the contact submission form and go straight to the follow up.
                      if (!options.noRecall && jQuery.cookie(jQuery.wb.WB_CONTACT_SUBMITTED_COOKIE)){
                        alert("Thank you. Your information has already been submitted.");
                        if (options.onSubmitSuccess) options.onSubmitSuccess({});
                      } else {
                        jQuery.wb.getContactInfo(options);
                      }
                    });
};

// Default behavior for all weatherbill apps
jQuery(function(){

         // If there is an element with id CTALeadcapDefault, use it to kick off the contact submit fu.
         jQuery('#CTALeadcapAction').wbContact();

       });
