//CVS:       $Id: main.js,v 1.15 2012/01/26 18:42:58 cvsdevel Exp $
//Title:     main.js
//Version:   1.00
//Copyright: Copyright (c) 2011
//Author:    Donovan Mueller (donovan@rhinointernet.com)
//Company:   Rhino Internet

/**
 * Javascript library for the Botanicare website.
 *
 * <p>
 * <b>Changelog:</b><pre>
 *  1.00   DDM 2011/06/30   created.
 * </pre>
 *
 * @author  DDM
 * @version 1.00
 */

 /**
  * Fixing Internet Explorer:
  */
 if (typeof window.console == 'undefined') {
    window.console = { 'log': function() { } };
 }
 
// Allow other JavaScript libraries to use $.
jQuery.noConflict();

// Declaring the global Nutrient Calculator
var Calculator = {};

//Microsoft Translate
function translatePage(){Microsoft.Translator.translate(document.body,"en", "es");}

/* jQuery dependent code encapsulation
   ------------------------------------------------------------------------- */
(function($){
   $(document).ready(function(){
      // Set all <a>s with the attribute `rel="external"` to open in new 
      // windows.   
      $('a[rel=external]').attr('target', '_blank');

      homepage.init();
      products.init();
      login.init();
      Calculator.choices.init();
      eventSearch.init();
   });

   var login = {
      init: function()
      {
         // Check the registration checkbox and hide it
         $('.retailer_partner input').filter(":last").prop("checked", true);
         $('.retailer_partner').hide();
         $('.login-form').show();
         $('.register-form').hide();
                  
         $('.signup_type').find('a').each(function() {
            $(this).click(function(e) {
               if (e) {
                  e.preventDefault();
                  e.stopPropagation();
               }
               $('.register-form').toggle();
               $('.login-form').toggle();
            });
         });
         
      }
   };
   
   var homepage = {
      /**
       * Initializes the dynamic elements on the homepage.
       */
      init: function()
      {
         var _this = this;

         $('.hero ul li').hide();
         $('.hero ul li:first').show();

         var imageCount = $('.hero ul li').length;
         var index = 1;

         setInterval(function() {
            var current = $('.hero ul li').get(index);

            $('.hero ul li').fadeOut(2000);
            $(current).fadeIn(2000);

            if (index == imageCount - 1) {
               index = 0;
            } else {
               index++;
            }
         }, 5000);
      }
   };

   var products = {
      /**
       * Initializes the dynamic elements for a product.
       */
      init: function ()
      {
         this.initImages();
         this.initReviewForm();
         this.initTabs();
         this.initWishlistDialog();
      },//init

      /**
       * Initializes the product image gallery.
       */
      initImages: function ()
      {
         var _this = this;

         $('.image-thumb').fancybox();
      	$("a.botanicare-products").fancybox();
      },//initImages


      /**
       * Initializes the product review form.
       */
      initReviewForm: function ()
      {
         var _this = this;

         $('.review-form-button').click(function ()
         {
            $(this).toggle();
            $('.review-form').toggle();
            $('.review-form .button').addClass('grey');

            return false;
         });
      },//initReviewForm

      /**
       * Initializes the product details tabs.
       */
      initTabs: function ()
      {
         var _this = this;

         $('.tabs a').click(function ()
         {
            var id = $(this).attr('id');
            id = id.substring(0, 3) + "content" + id.substring(3);

            $('.tabs a').removeClass('current');
            $(this).addClass('current');

            $('.tabcontent').removeClass('current');
            $('#' + id).addClass('current');

            return false;
         });
      },//initTabs

      /**
       * Initializes the wishlist dialog.
       */
      initWishlistDialog: function ()
      {
         var _this = this;
         $('a.submit-to-wishlist').click(function() {
            var valid = true;
            $('#optionsdialog .product-option').each(function() {
               if ($(this).val() == '') {
                  valid = false;
                  $(this).css('border', '1px solid #c00');
               }
            });
            if (valid) {
               $.fancybox.close();
            }
            return false;
         });
         $('.add-to-wishlist').fancybox({
            'onClosed' : function() {
               var complete = true;
               $('#optionsdialog select').each(function() {
                  if ($(this).val() == '') {
                     complete = false;
                  }
               });
               if (complete) {
                  $('input.submit-to-wishlist').trigger('click');
               }
            }
         });
      }//initWishlistDialog

   };//var product
   
   /* Nutrient Calculator Choices
    * 
    * Handles adding/removing nutrients when not on the Nutrient Calculator
    * page.
   ------------------------------------------------------------------------- */
   Calculator.choices = {
      ADDED_BTN_TEXT: 'Is in Calculator',
      ADDTO_BTN_TEXT: 'Add to Calculator',
   
      /**
       * Initializes calculator functions.
       */
      init: function() {
         var _this = this;
         
         if ($('#content.calculator').length) {
            // No point running on the actual Nutrient Calculator page.
            return null;
         }
         
         // Setup choices object
         _this.choices =
            { base_nutrients: {grow: '', bloom: ''},
              supplements: [] };
         
         // Are there any existing saved choices?
         var saved = _this.getSaved();
         if (saved) {
            $.extend(_this.choices, saved);
         }
         
         // Find all the "Add to" buttons.
         _this.buttons = $('a.calculator-add');
         
         /** Setup buttons */
         _this.buttons.each(function eachButton(){
            var button = $(this);
            // We're looking for the value of the 'product' paramter in the 
            // query string portion of the HREF.
            // Extract the query string.
            var parts = button.attr('href').split('?', 2);
            if (parts.length < 2) {
               // Invalid markup, no query string.
               _this.markInvalidButton(button);
               return;
            }
            // Pull out the nutrient from the key/value pairs.
            var parts = parts[1].split('&');
            for (var p = 0; p < parts.length; p++) {
               var pair = parts[p].split('=', 2);
               if (pair.length === 2 && pair[0] === 'product') {
                  var nutrient = decodeURIComponent(pair[1]);
                  break;
               }
            } // for
            if (!nutrient) {
               // No valid product name could be found.
               _this.markInvalidButton(button);
               return;
            }
            
            // Is this a known nutrient?
            if (nutrient in Calculator.nutrients.grow.base) {
               button.data(
                  'nutrient', {phase: 'grow', type: 'base', name: nutrient}
               );
               if (nutrient === _this.choices.base_nutrients.grow) {
                  _this.markAsAdded(button);
               }
            } else if (nutrient in Calculator.nutrients.bloom.base) {
               button.data(
                  'nutrient', {phase: 'bloom', type: 'base', name: nutrient}
               );
               if (nutrient === _this.choices.base_nutrients.bloom) {
                  _this.markAsAdded(button);
               }
            } else if (nutrient in Calculator.nutrients.grow.supplements ||
                       nutrient in Calculator.nutrients.bloom.supplements
            ) {
               button.data(
                  'nutrient', {type: 'supplement', name: nutrient}
               );
               if ($.inArray(nutrient, _this.choices.supplements) !== -1) {
                  _this.markAsAdded(button);
               }
            } else { // Unknown nutrient.
               _this.markInvalidButton(button);
               return;
            }
         });
         // We don't care about invalid buttons now.
         _this.buttons = _this.buttons.not('.invalid');
         
         /** Event Handling */
         // on hover
         _this.buttons.hover(
            function onMouseOverButton() {
               var button = $(this);
               if (button.hasClass('added')) {
                  button.html('Remove');
               }
            },
            function onMouseOutButton() {
               var button = $(this);
               if (button.hasClass('added')) {
                  button.html(_this.ADDED_BTN_TEXT);
               }
            }
         ); // on button hover
         
         // on click
         _this.buttons.click(function onButtonClick(event){
            var button = $(this);
            event.preventDefault();
            
            var nutrient = button.data('nutrient');
            switch (nutrient.type) {
               case 'base':
                  var current = _this.choices.base_nutrients[nutrient.phase];
                  if (!button.hasClass('added')) {
                     if (nutrient.name !== current) {
                        _this.choices.base_nutrients[nutrient.phase] = 
                           nutrient.name;
                        _this.notifyOfRemoval(current);
                     }
                     _this.notifyOfAddition(nutrient.name);
                  } else { // remove
                     _this.choices.base_nutrients[nutrient.phase] = '';
                     _this.notifyOfRemoval(nutrient.name);
                  }
                  break;
                  
               case 'supplement':
                  if (!button.hasClass('added')) {
                     if ($.inArray(nutrient.name, _this.choices.supplements) 
                           === -1
                     ) {
                        _this.choices.supplements.push(nutrient.name);
                     }  
                     _this.notifyOfAddition(nutrient.name);
                  } else { // remove
                     var pos = $.inArray(
                        nutrient.name, _this.choices.supplements
                     );
                     if (pos !== -1) {
                        _this.choices.supplements.splice(pos);
                     }
                     _this.notifyOfRemoval(nutrient.name);
                  }
                  break;
            } // switch
            
            _this.save();
         }); // on button click
      }, // init()
      
      /**
       * Loads saved choices from a cookie.
       * 
       * @param {string} name The key for the name of the cookie as stored in
       *                      `Calculator.settings.cookies`.
       */
      getSaved: function(name) {
         name = name || 'choices';
         try {
            var jsonvalues = CookieMonster.get(
               Calculator.settings.cookies[name]
            );
            var values = (values !== '') ? JSON.parse(jsonvalues) : null;
         } catch (e) {
            console.log('Malformed JSON in saved choices.');
            console.log(e);
            console.log(jsonvalues);
         }
         
         return values;
      }, // getSaved()
      
      /**
       * Saves current choices if none are passed in.
       *
       * @param {string} name The key for the name of the cookie as stored in
       *                      `Calculator.settings.cookies`.
       * @param object choices Choices to save (optional).
       */
      save: function() {
         var _this = this,
             name, choices;

         switch (arguments.length) {
         case 0:
         case 1:
            name    = 'choices';
            choices = arguments[0] || _this.choices;
            break;
         case 2:
         default:
            name    = arguments[0] || 'choices';
            choices = arguments[1] || _this.choices;
            break;
         } // switch
         
         CookieMonster.set(
            Calculator.settings.cookies[name], JSON.stringify(choices)
         );
      }, // save()
      
      /**
       * Changes the state of all relevant buttons according to the passed
       * nutrient having been added.
       * 
       * @param string name Name of the nutrient.
       */
      notifyOfAddition: function(name) {
         var _this = this;
         _this.buttons.each(function eachButton(){
            var button = $(this);
            if (name === button.data('nutrient').name) {
               _this.markAsAdded(button);
            }
         }); // each button
      }, // notifyOfAddition()
      
      /**
       * Changes the state of all relevant buttons according to the passed
       * nutrient having been removed.
       * 
       * @param string name Name of the nutrient.
       */
      notifyOfRemoval: function(name) {
         var _this = this;
         _this.buttons.each(function eachButton(){
            var button = $(this);
            if (name === button.data('nutrient').name) {
               button.
                  removeClass('added').
                  html(_this.ADDTO_BTN_TEXT);
            }
         }); // each button
      }, // notifyOfRemoval()
      
      /**
       * Marks and hides a button that is invalid.
       * 
       * @param jQuery button
       */
      markInvalidButton: function(button) {
         button.addClass('invalid').hide();
      }, // markInvalidButton()
      
      /**
       * Mark an "Add to" button as having been added.
       * 
       * @param jQuery button
       */
      markAsAdded: function(button) {
         var _this = this;
         button.
            addClass('added').
            html(_this.ADDED_BTN_TEXT);
      } // markAsAdded()
   }; // Calculator.choices{}

   var eventSearch = {
      init: function() {
         if (typeof jQuery.fn.labelify != 'undefined') {
            $('input').each(function() {
               if ($(this).hasClass('picker')) {
                  // using AbleCommerce control, and can't set title directly
                  if (!($(this).parent('div').children('span.picker-enabled').
                        children('input:checked').length)) {
                     var iid = $(this).attr('id');
                     if (iid.match(/_FromDate_/)) {
                        $(this).attr('title', 'From (oldest date)');
                     } else if (iid.match(/_ToDate_/)) {
                        $(this).attr('title', 'To (newest date)');
                     }

                     if ($(this).attr('title')) {
                        $(this).labelify();
                     }
                  }
               } else if (!$(this).val() && $(this).attr('title')) {
                  $(this).labelify();
               }
            });
         }
      } // init
   }; // eventSearch
})(jQuery);

/* Nutrient Calculator global settings.
 * 
 * These settings are the only ones needed globally. The rest of the
 * settings are defined in the main Nutrient Calculator JS file.
   ------------------------------------------------------------------------- */
Calculator.settings = {
   cookies: {
      choices:   'calculator-choices',
      overrides: 'calculator-overrides'
   }
};

/* Nutrient Calculator nutrient list.
   ------------------------------------------------------------------------- */
Calculator.nutrients = {
   grow: {
      base: {
         'Pure Blend Pro Grow': {
            weeks: { '1': 10, '2': 12, '3,8': 15 },
               // ml/gallon
            ppm: 60 // for 1ml/gallon
         },
         'Power Plant': {
            weeks: { '1': 8, '2': 10, '3,8': 12 },
            ppm: 75
         },
         'CNS 17 Grow': {
            weeks: { '1': 9, '2': 11, '3,8': 13 },
            ppm: 67
         },
         'CNS 17 Coco & Soil': {
            weeks: { '1': 8, '2': 10, '3,8': 12 },
            ppm: 75
         }
      }, // base
      supplements: {
         'Aqua Shield': {
            weeks: { '1': 5, '2,8': 10 },
            ppm: 0
         },
         'Blast Off': {
            weeks: { '1,8': 5 },
            ppm: 0
         },
         'Cal-Mag Plus': {
            weeks: { '1': 0, '2,3': 5, '4,8': 7 },
            ppm: 62
         },
         'Calplex': {
            weeks: { '1': 0, '2,8': 2 },
            ppm: 51
         },
         'Humega': {
            weeks: { '1': 2, '2': 3, '3,8': 5 },
            ppm: 10
         },
         'Huvega': {
            weeks: { '1': 2, '2': 3, '3,8': 5 },
            ppm: 20
         },
         'Liquid Karma': {
            weeks: { '1': 2, '2': 3, '3,8': 5 },
            ppm: 24
         },
         'Nitrex': {
            weeks: { '1': 1, '2,8': 2 },
            ppm: 150
         },
         'Pure Blend Original Grow': {
            weeks: { '1,2': 5, '3,8': 10 },
            ppm: 21
         },
         'Seaplex': {
            weeks: { '1': 0, '2': 2, '3': 3, '4,8': 5 },
            ppm: 11
         },
         'Silica Blast': {
            weeks: { '1': 2, '2': 3, '3,8': 5 },
            ppm: 6
         },
         'ZHO': {
            units: 'tsp',
            weeks: { '1': .25, '3': .25 },
            ppm: 0
         }
      } // supplements
   }, // grow
   
   bloom: {
      base: {
         'Pure Blend Pro Bloom': {
            weeks: { '1': 17, '2,10': 20, '-1': 15 },
               // Negative numbers mean to count back from the total number
               // of weeks. So, if there are 7 weeks then -1 is week 7.
               // Later week numbers overrider weeks listed earlier.
            ppm: 53
         },
         'Pure Blend Pro Bloom Soil': {
            weeks: { '1': 15, '2,10': 17, '-1': 13 },
            ppm: 66
         },
         'Power Flower': {
            weeks: { '1': 10, '2,10': 15, '-1': 10 },
            ppm: 85
         },
         'CNS 17 Bloom': {
            weeks: { '1': 13, '2,10': 17, '-1': 13 },
            ppm: 70
         },
         'CNS 17 Bloom Coco & Soil': {
            weeks: { '1': 13, '2,5': 15, '-3,-1': 0 },
            ppm: 74
         },
         'CNS 17 Ripe': {
            weeks: { '1': 20, '2': 22, '3': 24, '4,10': 25, '-1': 20 },
            ppm: 45
         }
      }, // base
      supplements: {
         'Aqua Shield': {
            weeks: { '1': 10, '2,10': 15 },
            ppm: 0
         },
         'Blast Off': {
            weeks: { '1,2': 5, '3,10': 10, '-1': 5 },
            ppm: 0
         },
         'Calplex': {
            weeks: { '1,2': 2 },
            ppm: 51
         },
         'Clearex': {
            weeks: { 'flush': 15 },
            ppm: 0
         },
         'Humega': {
            weeks: { '1,10': 5 },
            ppm: 10
         }, 
         'Huvega': {
            weeks: { '1,10': 5 },
            ppm: 20
         },
         'Hydroplex': {
            weeks: { '1,2': 2, '3': 3, '4,10': 5, '-1': 3 },
            ppm: 58
         },
         'Liquid Karma': {
            weeks: { '1,2': 5, '3,10': 3 },
            ppm: 24
         },
         'Pure Blend Original Bloom': {
            weeks: { '1,10': 5 },
            ppm: 19
         },
         'Seaplex': {
            weeks: { '1,10': 5 },
            ppm: 11
         },
         'Silica Blast': {
            weeks: { '1,10': 5 },
            ppm: 6
         },
         'Sweet': {
            weeks: { '1,3': 0, '4,10': 5 },
            ppm: 30
         },
         'ZHO': {
            units: 'tsp',
            weeks: { '1': .25, '3': .25  },
            ppm: 0
         }
      } // supplements
   } // bloom
}; // Calculator.nutrients


(function NutrientCalculatorPredefinedRecipes($){
   var $tables, $intro, $printBtn;
   
   jQuery(function onDOMReady(){
      var main = $('#content.calculator.recipes.predefined');
      
      $tables   = main.find('.outline-content > div.phase');
      $intro    = main.find('.outline-content > div.intro');
      $printBtn = main.find('.outline-content input.print-calculator');
      
      $printBtn.hide();
      $tables.hide();
      
      main.find('#overlay.calculator .form ul a[href^=#]').click(
         function onLinkClick(event){
            var id = $(this).attr('href');
            event.preventDefault();
            
            $intro.hide();
            $printBtn.show();
            $tables.not(id).hide();
            $tables.filter(id).show();
         });
   }); // on DOM ready
})(jQuery); // setup Nutrient Calculator predefined recipes page


/* Utilities
---------------------------------------------------------------------------- */
Number.prototype.formatNumber = function(c, t, d) {
   // Thanks to Daok for this:
   // http://stackoverflow.com/questions/149055/how-can-i-format-numbers-as-money-in-javascript/149099#149099
   // int c number of decimal points
   // string t thousands separator
   // string d decimal point separator
   var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c,
   d = d == undefined ? "." : d,
   t = t == undefined ? "," : t,
   s = n < 0 ? "-" : "",
   i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
   j = (j = i.length) > 3 ? j % 3 : 0;

   return s + (j ? i.substr(0, j) + t : "") +
      i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) +
      (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

/* Taken from https://github.com/douglascrockford/JSON-js
 * Removed `parse` method as that is provided by jQuery.
 * Minified using http://www.minifyjavascript.com/
 */
var JSON;if(!JSON){JSON={}}(function(){"use strict";function f(n){return n<10?'0'+n:n}if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+f(this.getUTCMonth()+1)+'-'+f(this.getUTCDate())+'T'+f(this.getUTCHours())+':'+f(this.getUTCMinutes())+':'+f(this.getUTCSeconds())+'Z':null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf()}}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+string+'"'}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key)}if(typeof rep==='function'){value=rep.call(holder,key,value)}switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null'}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null'}v=partial.length===0?'[]':gap?'[\n'+gap+partial.join(',\n'+gap)+'\n'+mind+']':'['+partial.join(',')+']';gap=mind;return v}if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==='string'){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v)}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v)}}}}v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+mind+'}':'{'+partial.join(',')+'}';gap=mind;return v}}if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' '}}else if(typeof space==='string'){indent=space}rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify')}return str('',{'':value})}}}());

/* JSON sans eval
 * This parses JSON without using `eval()`. This is important because IE7 was
 * having difficulties parsing the JSON produced by saving the Calculator 
 * choices.
 * 
 * Taken from: http://code.google.com/p/json-sans-eval/
 */
window.jsonParse=function(){var r="(?:-?\\b(?:0|[1-9][0-9]*)(?:\\.[0-9]+)?(?:[eE][+-]?[0-9]+)?\\b)",k='(?:[^\\0-\\x08\\x0a-\\x1f"\\\\]|\\\\(?:["/\\\\bfnrt]|u[0-9A-Fa-f]{4}))';k='(?:"'+k+'*")';var s=new RegExp("(?:false|true|null|[\\{\\}\\[\\]]|"+r+"|"+k+")","g"),t=new RegExp("\\\\(?:([^u])|u(.{4}))","g"),u={'"':'"',"/":"/","\\":"\\",b:"\u0008",f:"\u000c",n:"\n",r:"\r",t:"\t"};function v(h,j,e){return j?u[j]:String.fromCharCode(parseInt(e,16))}var w=new String(""),x=Object.hasOwnProperty;return function(h,
j){h=h.match(s);var e,c=h[0],l=false;if("{"===c)e={};else if("["===c)e=[];else{e=[];l=true}for(var b,d=[e],m=1-l,y=h.length;m<y;++m){c=h[m];var a;switch(c.charCodeAt(0)){default:a=d[0];a[b||a.length]=+c;b=void 0;break;case 34:c=c.substring(1,c.length-1);if(c.indexOf("\\")!==-1)c=c.replace(t,v);a=d[0];if(!b)if(a instanceof Array)b=a.length;else{b=c||w;break}a[b]=c;b=void 0;break;case 91:a=d[0];d.unshift(a[b||a.length]=[]);b=void 0;break;case 93:d.shift();break;case 102:a=d[0];a[b||a.length]=false;
b=void 0;break;case 110:a=d[0];a[b||a.length]=null;b=void 0;break;case 116:a=d[0];a[b||a.length]=true;b=void 0;break;case 123:a=d[0];d.unshift(a[b||a.length]={});b=void 0;break;case 125:d.shift();break}}if(l){if(d.length!==1)throw new Error;e=e[0]}else if(d.length)throw new Error;if(j){var p=function(n,o){var f=n[o];if(f&&typeof f==="object"){var i=null;for(var g in f)if(x.call(f,g)&&f!==n){var q=p(f,g);if(q!==void 0)f[g]=q;else{i||(i=[]);i.push(g)}}if(i)for(g=i.length;--g>=0;)delete f[i[g]]}return j.call(n,
o,f)};e=p({"":e},"")}return e}}();

// Setup which JSON parsing method to use if no native method is available.
if (!JSON.parse) {
   JSON.parse = (jQuery.browser.msie && jQuery.browser.version < 8)
      ? window.jsonParse
      : jQuery.parseJSON;
}

/**
 * Finds an embeded SWF movie by the passed name.
 *
 * @param string name
 */
function findSWF(name) {
  return (navigator.appName.indexOf("Microsoft")!= -1)
     ? window[name]
     : document[name];
}

/** Handles saving and retrieving cookies. */
var CookieMonster = {
   // Based off of http://www.quirksmode.org/js/cookies.html
   set /* bake */: function(name,value,params) {
      if (typeof params === 'object') {
         if (params.days) {
            var date = new Date();
            date.setTime(date.getTime() + (params.days * 24*60*60*1000));
            params.expires = date.toGMTString();
            delete params.days;
         }
         var settings = '';
         for (var key in params) {
            settings += '; ' + key + '=' + params[key];
         }
      } else {
         var settings = '';
      }

      var cookie = name + '=' + encodeURIComponent(value) + settings;
      document.cookie = cookie;
   }, // set()

   get /* sniff */: function(name) {
      var nameEQ = name + "=";
      var ca = document.cookie.split(';');
      for(var i=0;i < ca.length;i++) {
         var c = ca[i];
         while (c.charAt(0)==' ') c = c.substring(1,c.length);
         if (c.indexOf(nameEQ) == 0) {
            var value = c.substring(nameEQ.length,c.length);

            return decodeURIComponent(value);
         }
      }

      return null;
   }, // get()

   erase /* eat */: function(name) {
      this.set(name, '', { days: -1 });
   }, // erase()

   isWorking /* isAwake */: function() {
      if (typeof this.monsterInTheHouse !== 'undefined') {
         return this.monsterInTheHouse;
      }

      this.set('__verifyCookiesAreWorking', '1');
      this.monsterInTheHouse =
         (this.get('__verifyCookiesAreWorking') !== null);
      this.erase('__verifyCookiesAreWorking');

      return this.monsterInTheHouse;
   } // isWorking()
} // cookieMonster{}

function clearField(field, defaultValue)
{
   if (field.value == defaultValue) {
      field.value = '';
   }
}

function resetField(field, defaultValue)
{
   if (field.value == '') {
      field.value = defaultValue;
   }
}
