/**
 * Freeow plugin
 * Copyright (c) 2011 PJ Dietz
 * Version: 1.0.0
 * Licensed under the MIT license:
 * http://www.opensource.org/licenses/mit-license.php
 * http://pjdietz.com/jquery-plugins/freeow/
 */
(function($){"use strict";var g;g=function(a,b,c){var d,i,u;this.options=$.extend({},$.fn.freeow.defaults,c);this.element=$(this.options.template(a,b));if(this.options.startStyle){d=this.options.startStyle}else{d=this.options.hideStyle}this.element.css(d);this.element.data("freeow",this);for(i=0,u=this.options.classes.length;i<u;i+=1){this.element.addClass(this.options.classes[i])}this.element.click(this.options.onClick);this.element.hover(this.options.onHover,this.options.onHover);this.autoHide=false};g.prototype={attach:function(a){$(a).prepend(this.element);this.show()},show:function(){var a,self,fn,delay;a={duration:this.showDuration};if(this.options.autoHide&&this.options.autoHideDelay>0){this.autoHide=true;self=this;delay=this.options.autoHideDelay;fn=function(){if(self.autoHide){self.hide()}};a.complete=function(){setTimeout(fn,delay)}}this.element.animate(this.options.showStyle,a)},hide:function(){var a=this;this.element.animate(this.options.hideStyle,{duration:this.options.hideDuration,complete:function(){a.destroy()}})},destroy:function(){this.element.data("freeow",undefined);this.element.remove()}};if(typeof $.fn.freeow==="undefined"){$.fn.extend({freeow:function(a,b,c){return this.each(function(){var f;f=new g(a,b,c);f.attach(this)})}});$.fn.freeow.defaults={autoHide:true,autoHideDelay:3000,classes:[],startStyle:null,showStyle:{opacity:1.0},showDuration:250,hideStyle:{opacity:0.0},hideDuration:500,onClick:function(a){$(this).data("freeow").hide()},onHover:function(a){$(this).data("freeow").autoHide=false},template:function(a,b){var e;e=['<div>','<div class="background">','<div class="content">','<h2>'+a+'</h2>','<p>'+b+'</p>','</div>','</div>','<span class="icon"></span>','<span class="close"></span>','</div>'].join("");return e}}}}(jQuery));

/**
 * Cookie plugin
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js
 */
jQuery.cookie=function(a,b,c){if(typeof b!='undefined'){c=c||{};if(b===null){b='';c.expires=-1}var d='';if(c.expires&&(typeof c.expires=='number'||c.expires.toUTCString)){var e;if(typeof c.expires=='number'){e=new Date();e.setTime(e.getTime()+(c.expires*24*60*60*1000))}else{e=c.expires}d='; expires='+e.toUTCString()}var f=c.path?'; path='+(c.path):'';var g=c.domain?'; domain='+(c.domain):'';var h=c.secure?'; secure':'';document.cookie=[a,'=',encodeURIComponent(b),d,f,g,h].join('')}else{var j=null;if(document.cookie&&document.cookie!=''){var k=document.cookie.split(';');for(var i=0;i<k.length;i++){var l=jQuery.trim(k[i]);if(l.substring(0,a.length+1)==(a+'=')){j=decodeURIComponent(l.substring(a.length+1));break}}}return j}};

// for some reason, Fry's broken, disjointed, LAME js code is breaking Array.prototype when
// creating jquery.validator methods; uncommenting this causes a $.validator[method] error when 'remove' is the
// key, which makes no sense whatsoever, but still sucks rotten eggs
//// Array Remove - By John Resig (MIT Licensed)
//Array.prototype.remove = function(from, to) {
//   var rest = this.slice((to || from) + 1 || this.length);
//   this.length = from < 0 ? this.length + from : from;
//   return this.push.apply(this, rest);
//};

(function($) {
   /**
    * Emulate the detach() method added in jQuery 1.4--if we ever update jQuery to
    * something from the modern era, this can be removed
    */
   $.fn.detach = function() {
      var $clones = this.clone(true);
      this.remove();
      return $clones;
   };

   /**
    * Create an AMO namespace
    */
   $.amo = {
      cookieOpts: {expires: 30, path:    "/"},
      sessionCookieOpts: {expires: -1, path: '/'}
   };

   $.amo.bar = {
      show: function() {
         if( $('#amoDebugBanner').length > 0 ) {
            $.amo.debug.say("Debug banner already visible");
            return;
         }

         var $content = $('<div class="inner"><h2>AMO Debug Bar</h2></div>')
//               .append(
//               $.amo.bar.makeBox('SG Cookie', $.amo.sg.toggle, $.amo.sg.state())
//         )
               .append(
               $.amo.bar.makeBox('Messages', $.amo.debug.toggle, $.amo.debug.state())
         )
               .append(
               $.amo.bar.makeBox('Forsee', $.amo.forsee.toggle, $.amo.forsee.state())
         )
               .append(
               $.amo.bar.makeBox('Omniture', $.amo.omni.toggle, $.amo.omni.state())
         )
               .append(
               $('<div class="closeButton"></div>').click($.amo.bar.hide)
         );
         if( document.getElementById('paymentForm') ) {
            $content.append(
                  $.amo.bar.makeBox('Auto-Fill', $.amo.bar.payForm, 'checkout')
            ).append(
                  $.amo.bar.makeBox('Auto-Fill', $.amo.prescreen.open, 'ADS')
            );
         }
         if( $.cookie('ADSDate') ) {
            $content.append(
                  $.amo.bar.makeBox('ADSDate set', $.amo.prescreen.dropCookie, 'delete')
            );
         }
         if( $.cookie('GUEST') ) {
            $content.append(
                  $.amo.bar.makeBox('GUEST set', $.amo.cookies.dropGuest, 'delete')
            );
         }


         $('<div id="amoDebugBanner"></div>')
               .append($content)
               .prependTo(document.body)
               .slideDown();
         $.cookie('amoDebugBar', 1, $.amo.cookieOpts);
      },

      toggle: function() {
         if( $('#amoDebugBanner').length > 0 ) { $.amo.bar.hide(); }
         else { $.amo.bar.show(); }
      },

      hide: function() {
         $('#amoDebugBanner').slideUp().remove();
         $.cookie('amoDebugBar', 0, $.amo.cookieOpts);
      },

      toggleBox: function(event) {
         var fxn = $(this).data('handler');
         $(this).find('.stateBox').html( fxn() );
      },

      makeBox: function(title, handler, state) {
         return $('<div>'+title+': <span class="stateBox">'+state+'</span></div>')
               .data('handler', handler)
               .click($.amo.bar.toggleBox);
      },

      init: function() {
         if( $.cookie('amoDebugBar') == 1 ) {
            $.amo.forsee.init();
            $.amo.omni.init();
            //$.amo.debug.init(); //done at bottom
            $.amo.bar.show();
         }
      },

      payForm: function(useAds) {
         // scroll down to the submit button
         //$('html, body').animate({scrollTop: $(document).height()}, 200);
         var fname = useAds? 'Always' : 'Mr. Test'; //'Mr. T\''+String.fromCharCode(233)+'st';
         var lname = useAds? 'Approve' : 'User'; //'U\'ser-'+String.fromCharCode(252)+'ser D.';

         // fill in billing info
         $('#billingFirstName').val(fname).click().focus().blur();
         $('#billingLastName').val(lname).click().focus().blur();
         $('#billingAddress1').val('123 Anystreet').click().focus().blur();
         $('#billingCity').val('Anytown').click().focus().blur();
         $('#billingState').val('AZ').click().focus().blur();
         $('#billingZipCode').val('85710').click().focus().blur();
         $('#emailAddress').val('aaa@aaa.com').click().focus().blur();
         $('#emailPreference').click().focus().blur();
         $('#billingPhone').val('9998887777').click().focus().blur();

         //$.amo.util.fryCompatibleBlur(document.getElementById('billingZipCode'));
         $('#differentCreditCard').attr('checked', true).click();

         // fill in CC values
         $('#cctype').val('VI').click().focus().blur();
         $('#cc-name').val(fname+' '+lname).click().focus().blur();
         $('#ccnumber').val('4111111111111111').click().focus().blur();
         $('#ccMonth').val(12).click().focus().blur();
         $('#ccYear').val(2020).click().focus().blur();
         $('#cc-security-code').val(411).click().focus().blur();

         // try to force the billing info to refresh
         $('#billingZipCode').focus().change();

         //$('#paymentForm .submitButton')[0].focus();
         return 'done';
      }

   };

   /**
    * Create some debugging utilities
    */
   $.amo.debug = {
      on: false,

      cookieName: 'amoDebugMsg',
      pageStateCookieName: 'amoPageStateMsg',

      /**
       * Checks the "debug" cookie; if it is set to "ON", then debugging is enabled, otherwise it is false
       */
      init: function() {
         // create the freeow div layer that is copied to create the message boxes
         $('<div id="freeow" class="freeow freeow-top-right"></div>').appendTo(document.body);
         // store the 'debug' cookie value
         $.amo.debug.on = $.cookie($.amo.debug.cookieName) == 'ON';
         // send our message to Firebug if it's up
         if( typeof(console) == "object" && console.log ) {
            console.log("debug cookie setting: "+$.amo.debug.on);
         }
      },

      /**
       * returns ON or OFF, based on whether debugging is enabled
       */
      state: function() {
         return $.amo.debug.on? 'ON' : 'OFF';
      },

      /**
       * Enables/disables debugging on the fly; this also sets the cookie accordingly
       * This can be done from the browser window by typing this into the URL and hitting enter:
       * <code>
       *    javascript:$.amo.debug.toggle();
       * </code>
       */
      toggle: function() {
         $.amo.debug.on = !$.amo.debug.on;
         var v = $.amo.debug.state();
         $.cookie($.amo.debug.cookieName, v, $.amo.cookieOpts);
         $("#freeow").freeow("Toggled Debugging", v, $.amo.debug.opts);
         return v;
         //return $.amo.debug.on? 'ON' : 'OFF';
      },

      /**
       * Defines the look/feel of the debug windows, see the Freeow comments for more options
       */
      opts: {
         classes: ['smokey'],
         showDuration: 500,
         hideStyle: {
            opacity: 0,
            left: "400px"
         },
         showStyle: {
            opacity: 1,
            left: 0
         }
      },

      /**
       * Generates a debug window that slides into the screen
       * @param title (String) optional - if omitted, then set to "Debug Message"
       * @param text the message window blurb to be displayed
       */
      say: function() {
         var title, text;
         if( arguments.length < 2 ) {
            title = 'MESSAGE';
            text = arguments[0];
         }
         else {
            title = arguments[0];
            text = arguments[1];
            $.amo.debug.log(title);
         }
         // send message to the Firebug/IE consoles
         // if performance degrades, this can be moved after the $.amo.debug.on check
         $.amo.debug.log(text);
         // check to see if debugging is on
         if( !$.amo.debug.on ) { return false; }
         // post message in a debug window
         $("#freeow").freeow(title, text, $.amo.debug.opts);
         return true;
      },

      log: function(anything) {
         if( typeof(console) == 'object' && console.log ) { console.log(anything); }
      }
   };

   // shortcuts
   $.amo.say = $.amo.debug.say;
   $.amo.log = $.amo.debug.log;

//   //keeping this commented; this could come back in future releases and be useful again
//   /**
//    * Utility for dealing with the SG cookie and RMT routing
//    */
//   $.amo.sg = {
//      // this has to match what Fry puts into the cookies
//      cookieName: 'SG',
//
//      /**
//       * returns A or B, based on the SG cookie's value
//       */
//      state: function() {
//         return $.cookie($.amo.sg.cookieName);
//      },
//
//      /**
//       * Flips the SG cookie between A/B for RMT testing
//       * This can be done from the browser window by typing this into the URL and hitting enter:
//       * <code>
//       *    javascript:$.amo.debug.sgToggle();
//       * </code>
//       */
//      toggle: function() {
//         var v = ($.cookie($.amo.sg.cookieName) == 'A')? 'B' : 'A';
//         $.cookie($.amo.sg.cookieName, v, $.amo.cookieOpts);
//         $.amo.debug.say('SG Cookie Changed', v);
//         return v;
//      }
//   };

   $.amo.prescreen = {
      open: function() {
         $.amo.prescreen.dropCookie();
         return $.amo.bar.payForm(true);
      },

      dropCookie: function() {
         $.cookie($.amo.prescreen.cookieName, null, $.amo.sessionCookieOpts);
         $.amo.say('dropped '+$.amo.prescreen.cookieName+' cookie');
         return 'done';
      },

      cookieName: 'ADSDate'
   };

   $.amo.cookies = {
      dropGuest: function() {
         $.cookie($.amo.cookies.guestCookieName, null, $.amo.sessionCookieOpts);
         $.amo.say('dropped '+$.amo.cookies.guestCookieName+' cookie');
         return 'done';
      },

      guestCookieName: 'GUEST'
   };

   /**
    * Utility for disabling the forsee survey window
    */
   $.amo.forsee = {
      cookieName: 'ForseeState',

      /**
       * Sets the forsee flag according to cookie value
       */
      init: function() {
         var v = $.amo.forsee.state();
         if( v == 'OFF' ) {
            window.FSR.enabled = false;
         }
         //else if( v == 'ON' ) {
         //   window.FSR.enabled = true;
         //}
      },

      /**
       * returns A or B, based on the SG cookie's value
       */
      state: function() {
         // handles the case where there is no cookie (defaults to off)
         return ($.cookie($.amo.forsee.cookieName) == 'ON')? 'ON' : 'OFF';
      },

      /**
       * Flips the SG cookie between A/B for RMT testing
       * This can be done from the browser window by typing this into the URL and hitting enter:
       * <code>
       *    javascript:$.amo.debug.sgToggle();
       * </code>
       */
      toggle: function() {
         if( window.FSR ) {
            window.FSR.enabled = !window.FSR.enabled;
         }
         var v = ($.amo.forsee.state() == 'ON')? 'OFF' : 'ON';
         $.cookie($.amo.forsee.cookieName, v, $.amo.cookieOpts);
         $.amo.debug.say('Forsee Survey', v);
         return v;
      }
   };

   /**
    * Auto closes omniture site catalyst popup that slides in over the checkout receipt page
    */
   $.amo.omni = {
      cookieName: 'OmniState',

      /**
       * Disables the window if set to OFF
       */
      init: function() {
         if( $.amo.omni.state() == 'OFF' && window.closeslider) {
            window.closeslider();
            $.amo.debug.say('Omniture SiteCatalyst', 'auto-closed');
         }
      },

      /**
       * returns ON or OFF, based on the omni cookie's value
       */
      state: function() {
         // handles case where cookie doesn't exist (defaults to off)
         return $.cookie($.amo.omni.cookieName) == 'ON'? 'ON' : 'OFF';
      },

      /**
       * Flips the SG cookie between A/B for RMT testing
       * This can be done from the browser window by typing this into the URL and hitting enter:
       * <code>
       *    javascript:$.amo.debug.sgToggle();
       * </code>
       */
      toggle: function() {
         var v = $.amo.omni.state() == 'ON'? 'OFF' : 'ON';
         $.cookie($.amo.omni.cookieName, v, $.amo.cookieOpts);
         $.amo.debug.say('Omni Window', v);
         return v;
      }
   };

   /**
    * AMO Standard Set of Utilities
    *
    *
    */

   $.amo.util = {

      // URL Helpers
      url : {
         // Grab unescaped parameters
         gup : function(name) {

            name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
            var regexS = "[\\?&]" + name + "=([^&#]*)";
            var regex = new RegExp(regexS);
            var results = regex.exec(window.location.href);
            if (results == null) return "";
            else return results[1];

         },

         getPage: function() {
            if( $.amo.util.url.whatPage == null ) {
               var sPath = window.location.pathname;
               $.amo.util.url.whatPage =
                     sPath.substring(sPath.lastIndexOf('/') + 1, sPath.lastIndexOf('.')).toLowerCase();
            }
            return $.amo.util.url.whatPage;
         },

         whatPage: null,

         // Get Page Name
         isPage : function(name) {

            var pageName = $.amo.util.url.getPage();

            // Check to see that they are equal
            if ( name.toLowerCase() == pageName ) {
               return true;
            }

            return false;
         }
      },

      newUrl : {
         isPage : function(name) {

            var swPath = window.location.pathname;
            var pageName = sPath.substring(sPath.indexOf(".com") + 5);
            pageName = pageName.substring(0, pageName.indexOf("/"));

            if(name.toLowerCase() == pageName)
               return true;

            return false;

         }
      },

      //todo not used
      browser : {
         isIE6 : function() {
            return !!( document.all && (/msie 6./i).test(navigator.appVersion) && window.ActiveXObject );
         }
      },

      //todo not used
      cookie : {
         getCookie : function(cookieName) {
            var value = $.cookie(cookieName);
            $.amo.debug.say("Cookie Retrieved", cookieName+"="+value);
            return value;
         },

         setCookie : function(cookieName, value, expireDays) {
            $.amo.debug.say("Cookie Set", cookieName+"="+value+" (expires in "+expireDays+" days)");
            var expireDate = new Date();
            expireDate.setDate(expireDate.getDate() + expireDays);
            document.cookie = cookieName + "=" + escape(value) +
                  ((expireDays == null) ? "" : ";expires=" + expireDate.toUTCString());
         },

         deleteCookie : function(cookieName) {
            $.amo.debug.say("Cookie Deleted", cookieName);
            if(getCookie(cookieName)) {
               document.cookie = cookieName + "=; expires=Thu, 01-Jan-70 00:00:01 GMT";
            }
         }
      },

      getDocForEvent: function(element) {
         if( element.ownerDocument ) {
            return element.ownerDocument;
         }
         else {
            return document;
         }
      },

      fryCompatibleClick: function(element) {
         var event,doc;
         try {
            doc = $.amo.util.getDocForEvent(element);
            event = doc.createEvent('MouseEvents');

            event.initMouseEvent('click', true, true,
                  doc.defaultView, 1, 0, 0, 0, 0, false,
                  false, false, false, 1, null);

            if (element.fireEvent){
               // dispatch for IE
               return element.fireEvent('onclick', event)
            }
            else{
               // dispatch for firefox + others
               return !element.dispatchEvent(event);
            }
         }
         catch(e) {
            $.amo.debug.say('ERROR', e);
         }
      },

      fryCompatibleBlur: function(element) {
         var event,doc;
         try {
            doc = $.amo.util.getDocForEvent(element);
            if (doc.createEventObject){
               // dispatch for IE
               event = doc.createEventObject();
               return element.fireEvent('onblur', event)
            }
            else{
               // dispatch for firefox + others
               event = doc.createEvent('UIEvents');
               event.initEvent('blur', true, true);
               return !element.dispatchEvent(event);
            }
         }
         catch(e) {
            $.amo.debug.say('ERROR', e);
         }
      }
   };

   // initialize elements on page ready
   $(function() {
      $.amo.debug.init();
      $.amo.bar.init();
   });

})(jQuery);
