
var passin = "Q104626=";
var order_total = 0;
var order_zip = "";
var br_cartzip = "";
var order_string = "";
var br_cartdata = "";

(function($) {
   /**
    * Right now we are in transition from the old, sloppy setup using window.amojavalib
    * and the ton of if( isPage(...) ) statements to a more elegant solution using
    * $.amo.pagefixes (a scoped namespace) and an init() method, which will centralize
    * all the logic of determining what fixes get applied into one spot.
    *
    * Until this is completed, the window.amojavalib object and big long list of
    * method calls at the bottom must remain.
    */
   $.amo.pagefixes = window.amojavalib = {
      /**
       * The init() method looks at the current page, then runs appropriate fixes
       * based on which one it is, using a switch() on the page name.
       */
      init: function() {
         var pageName = $.amo.util.url.getPage();
         switch(pageName) {
            case '1778':
            case '1779':
            case '1780':
            case '1781':
               // add a banner to the petite pages manually; due to a bug in fry code, the managed content
               // areas don't function correctly on subcategories, so we can't utilize those
               $.amo.pagefixes.petiteBannerFix();
               break;
            case 'basket':
               break;
            case 'checkout_login':
               $.amo.pagefixes.fixPasswordLink();
               break;
            case 'checkout':
               $.amo.pagefixes.fixCheckoutDefaultPayment();
               $.amo.pagefixes.fixHelpOverlay();
               $.amo.pagefixes.fixPasswordLink();
               //$.amo.pagefixes.fixBillingFields();
               break;
            case 'login':
               $.amo.pagefixes.fixLoginForm();
               break;
            case 'pl_preapplication':
               $.amo.pagefixes.fixCreditCardTitleBar();
               $.amo.pagefixes.fixFormEntryBoxes();
               break;
            case 'receipt':
               $.amo.pagefixes.bizrateSetup();
            case 'search_command':
            case 'search':
               $.amo.pagefixes.fixEmptyPaginationBars();
               break;
            default:
            //$.amo.debug.say("page type "+p+" has no methods to run"); //debug
         }

         var winName = window.location.pathname;
         if(winName.indexOf("category") >= 0 || winName.indexOf('thumbnail') >= 0) {
            $.amo.pagefixes.fixEmptyPaginationBars();
         }
         else if(winName.indexOf('section')) {
            $.amo.pagefixes.fixSectionPagination();
         }
      },

      /**
       * For pages with no pagination (less than one page of items) and no heading in the pagination-container, an
       * empty bar appears. Because simply removing this would cause page elements to disappear (unintended animation)
       * we first hide the bars and only show them if either a title is present and not hidden or the pagination
       * exists
       */
      fixEmptyPaginationBars: function() {
         var $e = $('.right-body .pagination-container');
         if( $e.find('h1:visible').length > 0 || $.trim($e.find('.pagination').text()).length > 0 ) {
            $e.css('display', 'block');
         }
         $('.right-body .product-list .pagination').each(function() {
            if( $.trim($(this).text()).length > 0 ) {
               $(this).css('display', 'block');
            }
         });
      },

      /**
       * We want our pagination to have arrows instead of >>, so this method replaces the section arrows accordingly
       * We want our link to have the section name and no title to the left, so fiddle it just so
       */
      fixSectionPagination: function() {
         // FIX ARROWS
         // the css class 'divider' is overloaded because our vendor is insane in the membrane
         // so we have to verify this is the right arrows to proceed
         $('.pagination span.divider').each(function() {
            var $this = $(this), link;
            if( $.trim($this.html()) == '&gt;&gt;' ) {
               // this doesn't work for some reason; the massive CSS we've been provided causes all kinds of quirks lik
               // this; basically, the top margin is -4px and our image is a background-image in the CSS so that it doesn't
               // push the other content all over the screen
               //link = '<a href="'+$this.prev().attr('href')+'"><img src="http://media.orchardbrands.com/opt/assets/images/btn/pretty_arrow.png" width="22" height="22" alt="View More" /></a>';
               // we find the previous anchor tag, which contains the link that should also be applied to the arrows,
               // assuming our vendor wasn't so weak in the force
               link = '<a href="'+$this.prev().attr('href')+'"></a>';
               $this.html(link);
            }
         });

         // FIX MORE LINK TEXT
         // the more link has no identifiable markings since our vendor is not so bright with the building
         // so we have to iterate and look for it
         $('.pagination a').each(function() {
            var $this = $(this), html;
            if( $this.html().match('View more') ) {
               html = $this.parent().parent().find('a.sub-cat-name').html();
               if( html ) {
                  $this.html('View More '+html);
               }
            }
         });
      },

      /**
       * The help overlay on checkout is not a MC area; we make it one with a little js magic! We override the method so
       * it calls a url we can control and put our content there.
       *
       * Adds PT Sans font using Google Web Fonts for use in please wait message
       * (http://www.google.com/webfonts?family=PT+Sans&subset=latin#QuickUsePlace:quickUse/Family:)
       */
      fixHelpOverlay: function() {
         $('head').append("<link href='https://fonts.googleapis.com/css?family=PT+Sans+Narrow' rel='stylesheet' type='text/css'>");
         // store the old function so we can call it internally
         var oldFxn = lib2.layer.create;
         // override existing function
         lib2.layer.create = function(jQuerySelector, props) {
            // replace the url
            if( props.url == '/checkout/processing_message.jsp' ) {
               $.amo.log(props);
               props.url = '/content_layer.jsp?pageName=processing_message';
               var oldCallback = props.callback;
               props.callback = function() {
                  var html = $('#helpPopup .pop-up-content .mc-area-1').html();
                  $('#helpPopup .pop-up-content').remove();
                  $.amo.log('starting old callback');
                  oldCallback();
                  $.amo.log('done with old callback');
                  $('#helpPopup').append(html);
               }
            }
            // call old fxn with new props
            return oldFxn(jQuerySelector, props);
         };
      },

      onReadyInit: function() {
//         if( typeof(window.showBasket) == 'function' ) {
//            var _showBasket = showBasket;
//            window.showBasket = function(action, parms) {
//               var res = _showBasket(action, parms);
//               $("#widget-ucart")
//                     .stop(false, true)
//                     .animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );
//               return res;
//            };
//            $(window).scroll(function(){
//               $("#widget-ucart")
//                     .stop(false, true)
//                     .animate({"marginTop": ($(window).scrollTop() + 30) + "px"}, "slow" );
//            });
//         }
      },

      /**
       * Fixes the red title bar on the credit card application windows, which
       * is necessary because we need the fields padded at a consistent width, but
       * padding the parent container also causes this title bar to get padded and
       * look retarded. This moves the title bar outside the parent container and
       * fixes the issue.
       */
      fixCreditCardTitleBar: function() {
         $('#che-plp-content .container-box h4').detach().insertBefore('#che-plp-content .container-box');
      },

      /**
       * There are some usability issues with the current structure for credit cards
       * 80% of users use visa/mastercard/etc but our default is the AMO card. Also
       * the credit card type field reacts when clicked on even when disabled, causing
       * people to miss the fact that they need to click the radio. So we click it by
       * default using this fix, which solves many of these issues.
       */
      fixCheckoutDefaultPayment: function() {
         $('#differentCreditCard').attr('checked', true).click();
      },

      /**
       * The various fields on Fry forms are [abberations, anomalies] controlled by
       * adding div layers ad nauseam around each input field and label. However, since
       * the contents are all relativistic, none of the wrapper divs actually take styles
       * as intended. The mess of styles Fry put around these to correct it is shameful.
       *
       * Here, we will insert the proper clearing tags needed by FF so that we can style things
       * in a semi-sensible manner.
       */
      fixFormEntryBoxes: function() {
         $('.FormArea .FormEntry').append('<br style="clear:both" />');
      },

      /**
       * Corrects billing fields layout - Fry/Orchard's default is a mess and ugly as hell
       * so make these something reasonable and usable
       */
      fixBillingFields: function() {
         // process each field
         $('#billingBox .FormEntry').each($.amo.pagefixes.processFormArea);
         $('#billingBox div.companyName').show();
         $('#billingBox div.address2').show();
         $('#billingBox div.addFeilds').hide();
         $.extend($('#paymentForm').data('validator').settings, {
            errorPlacement: function($error, $element) {
               $error.html('&nbsp;');
               $error.insertBefore($element.parent().find('br').eq(0));
            }
         });
      },

      /**
       * Part of the fixBillingFields() process; each call to this method finds the input field,
       * detaches it, creates a new, appropriate html layout, and reattaches it.
       */
      processFormArea: function() {
         var $this,$firstLabel,labelText,isRequired,$inputs,c;

         // determine what our inputs/labels/etc are going to be
         $this = $(this);
         $this.find('select :selected').text('-select a state-');
         $firstLabel = $this.find('label').eq(0);
         labelText = $firstLabel.html().replace(/\(optional\)/i, '');
         isRequired = $this.find('.required').length > 0;

         // remove all the screwey event handling and error validation garbage
         $inputs = $this.find('input,select').detach().each(function() {
            // remove the default text inside the fields
            lib2.input.defaultText("#"+$(this).attr('id'), { defaultText : "" });
            $(this).attr('value', '');
            // remove event handlers that put the text back in
            var handlers = $(this).data('events');
            if( handlers && handlers.blur ) {
               $.amo.log(handlers.blur);
               for(key in handlers.blur) {
                  $.amo.log('found handler: '+handlers.blur[key]);
                  if( (handlers.blur[key]+'').indexOf("settings.defaultText") > -1 ) {
                     $.amo.log('removed stupid handler');
                     $(this).unbind('blur', handlers.blur[key]);
                     break;
                  }
               }
            }
         });

         // clear out the current content
         $this.empty();

         // recreate the node with something more useful inside
         c = isRequired? 'amoFieldLabel required' : 'amoFieldLabel';
         $this.append('<label class="noshow"></label><div class="'+c+'">'+labelText+'</div>')
               .append($inputs)
               .append('<br style="clear:both" />');
      },

      /**
       * The current forgot password link is too obscure; we move it to the bottom of the form to utilize white
       * space as a means of making it more noticeable and enforcing a logical UX hierarchy (forgot password is not a
       * part of the login form; it's an alternative)
       */
      fixPasswordLink: function() {
         //todo: jQuery 1.2.6 has no detach method; must clone it; once we no longer use 1.2.6 we can change this to detach
         $('.password-tip .forgot-password-link')
               .clone().insertBefore('#che-login-page #loginForm div.FormArea > div.clr:last') //insert a clone
               .end().remove(); //remove the original
      },

      /**
       * The current forgot password link is too obscure; we move it to the bottom of the form to utilize white
       * space as a means of making it more noticeable and enforcing a logical UX hierarchy (forgot password is not a
       * part of the login form; it's an alternative)
       *
       * We don't utilize the fixPasswordLink() function here because our vendor lacks midichlorians, and managed to make
       * the forms just different enough to confuse everything.
       *
       * The login button is actually outside the container, so move it in and align it nicely
       */
      fixLoginForm: function() {
         //todo: jQuery 1.2.6 has no detach method; must clone these; once we no longer use 1.2.6 we can change this to detach
         $('#login-page .forgot-password-link').clone().appendTo('#login-page .member-login div.FormArea').css('display', 'block') //insert a clone
               .end().remove(); //remove the original

         $('#login-page .member-login .sign-in')
               .clone().appendTo('#login-page .member-login div.FormArea').show()
               .end().remove(); //remove the original

         // add a break for layout control
         $('#login-page .member-login div.FormArea').append('<br class="clr" />');
      },

      /**
       * MAKE SURE THIS IS CALLED DURING PAGE RENDER
       *
       * BizRate survey utilizes document.write() which means it must be inserted during page rendering. If document.write()
       * is called on document ready or on load, it will cause the page to be reloaded with the new content. This is problematic
       * because it forces the browsers to freeze rendering while it waits for the javascript to get downloaded.
       *
       * They should be utilizing document.appendChild() or similar methods. We should also be able to use the following hack, which
       * would force BizRate to use appendChild unwillingly and allow their ultra-annoying popup to load after the page is
       * rendered. However, our CSS is so jacked by Fry this doesn't work either:
       * <code>
       $('body').append("<div id='bizrate-banner' />");
       var oldDocWrite = document.write;
       document.write = function(what) { $('#bizrate-banner').append(what); };
       $.getScript('https://eval.bizrate.com/js/pos_70770.js', function() { document.write = oldDocWrite; });
       * </code>
       */
      bizrateSetup : function() {
         if ($.amo.util.url.isPage("receipt")) {
            // new version using omniture info
            passin = passin + s.purchaseID;
            product_string = s.products.substring(1);
            order_string = product_string.split(";");
            for(var i = 0; i < 5; i++) {
               if (i * 5 + 9 > order_string.length)
                  break;
               if (i > 0)
                  br_cartdata += "|";
               br_cartdata += 'SKU=' + order_string[i * 5 + 4].substring(6, 13) + '&MPID=' + order_string[i * 5] + '&ITEMAMOUNT=' + (order_string[i * 5 + 2] / order_string[i * 5 + 1]);
            }
            br_cartzip = 'Q113198=' + $.trim($("#che-rec-order-sum-two table tfoot td").html()).substring(1) + '&Q113199=' + s.zip;
            document.write("<div id='bizrate-banner'><script type='text/javascript' src='https://eval.bizrate.com/js/pos_70770.js'></script></div>");
         }
      },

      /*
       // setup google analytics
       googleAnalyticSetup : function() {
       var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl."
       : "http://www.");
       document
       .write(unescape("%3Cscript src='"
       + gaJsHost
       + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
       },

       // pagetracker
       pageTracker : function() {
       try {
       var pageTracker = _gat._getTracker("UA-11418627-1");
       pageTracker._trackPageview();
       } catch (err) {
       }
       },
       */
      // fix the cc fields in the order payment page
      checkoutFix : function() {
         if ($.amo.util.url.isPage("payment")) {
            $("#che-pay-pi-one").css("height", "580px");
         }
         if ($.amo.util.url.isPage("apply_gift_card")) {
            $("#che-pay-pi-one").css("height", "425px");
         }
         if ($.amo.util.url.isPage("update_award_in_order")) {
            $("#che-pay-pi-one").css("height", "495px");
         }
         if ($.amo.util.url.isPage("credit_card_payment")) {
            $("#che-pay-pi-one").css("height", "645px");
         }
         if ($.amo.util.url.isPage("payment")
               || $.amo.util.url.isPage("apply_gift_card")
               || $.amo.util.url.isPage("update_award_in_order")
               || $.amo.util.url.isPage("credit_card_payment")) {
            var i = 0;
            $("#che-pay-pi-one .FormEntry").each(function() {
               if (i == 0) {
                  $(this).css( {
                     "position" : "absolute",
                     "left" : "63px",
                     "top" : "38px"
                  })
                  var j = 0;
                  var formHeight = 0;
                  $(this).children().each(function() {
                     formHeight += $(this).height();
                     if($(this).hasClass("ErrorText") && $(this).height() > 16)
                        $(this).html("This Arizona Mail Order (AMO) Account number is not valid as you entered it. Please check your number and try again.");
                     if (j == 0)
                        $(this).css("margin", "0");
                     j++;
                  });

                  formHeight -= 39;
                  $("#che-pay-cms-brand-cc img").each(function() {
                     $(this).css("margin-bottom", formHeight + "px");
                  });
               }
               i++;
            });
            var position = 50;
            $("#che-pay-saved-cc").css("top", position + "px");
            position += $("#che-pay-saved-cc").height();
            position += 5;
            $(".cc-field").each(function() {
               $(this).css("top", position + "px");
               $(this).css("display", "block");
               position += 5;
               position += $(this).height() * 1.4;
            });
            $("#che-pay-save-cc").css("top", position + "px");
         }
         if ($.amo.util.url.isPage("order_status")) {
            $("#che-rec-header").css("margin-top", "26px");
            $("#che-rec-intro-order-info a.print-page-link").css( {
               "bottom" : "0",
               "top" : "110px",
               "background-position" : "top left"
            });
            $("#che-rec-thankyou-text").css("display", "none");
            $("#che-rec-cms-cust-serv-one").css("margin-bottom", "122px");
            $("#che-rec-content").css("margin-bottom", "20px");
            $("#che-rec-return-link").css( {
               "float" : "right",
               "margin" : "15px"
            });
         }
         if ($.amo.util.url.isPage("receipt") || $.amo.util.url.isPage("order_status")) {
            $("#che-rec-content .shipto-box .order-info-detail div").not(':first').css('display', 'none');
         }
      },

      catalogOrderFix : function() {
         var page_address = document.URL;
         if ($.amo.util.url.isPage("add_catalog_order_item")) {
            $(".qty-container").prepend("<span>Quantity: </span>");
         }

      },

      clearanceCatalogFix : function() {
         var pageName = window.location.pathname;
         if (pageName.indexOf("Clearance") != -1) {
            $("#hs-opt-clearance-fix-0105").css("display", "none");
            $("#hs-opt-clearance-clr-0105").css("display", "inline");
         }
         if (pageName.indexOf("Clearance") == -1) {
            $("#hs-opt-clearance-fix-0105").css("display", "inline");
            $("#hs-opt-clearance-clr-0105").css("display", "none");
         };
      },

      productPageFix : function() {
         var pageName = window.location.pathname;
         if (pageName.indexOf("product") != -1 || $.amo.util.url.isPage("ensemble")) {

            $("#product_rr h3").html("You may also like...");

            var i = 0;
            $("#product_rr .item-container").each(function() {
               if(i == 3)
                  $(this).css("display", "none");
               i++;
            });
            i = 0;
            $("#product_rr .item-container .price div").each(function() {
               var price_string = $(this).html();
               price_string = price_string.substring(price_string.indexOf("$"));
               if(price_string.indexOf(" ") > -1)
                  price_string = price_string.substring(0, price_string.indexOf(" "));
               price_string = "from " + price_string;
               $(this).html(price_string);
            });
            i = 0;
            $("#product_rr .item-container a img").each(function() {
               var image_string = $(this).attr("src");
               image_string = image_string.substring(0, image_string.length - 9);
               image_string = image_string + "200x200.jpg";
               $(this).attr("src", image_string);
            });

            $(".product-pagination a:first-child img").attr("src", "http://media.orchardbrands.com/opt/assets/images/bkg/product_pagination_arrow_left_off.gif");
            $(".product-pagination a:last-child img").attr("src", "http://media.orchardbrands.com/opt/assets/images/bkg/product_pagination_arrow_right_off.gif");

            var collection_name = $(".breadcrumb a:last").html();
            var product_pagination = $(".product-pagination").html();
            product_pagination = $.trim(product_pagination);
            if(product_pagination != "") {
               $(".product-pagination").before("<div style=\"float: right; width: 160px; text-align: center; font-size: 1.2em;\">Browse:<br />" + collection_name + "</div>");
            }
            $(".availability-link a").html("Check Availability >");

            $(".bug-image").appendTo(".description");
            $(".bug-image").before("<br />");
            $(".bug-image").after("<div style=\"font-weight: bold; color: #1f65c5; text-align: center; margin: -70px 0 10px 30px;\">Cool Savings!<br>20% OFF this item<br><span style=\"font-weight: normal;\">(discount appears in<br>shopping cart)</span></div>");

            var variantBlocks = 0;
            $("#variant-selector-block-regular").each(function() {
               variantBlocks++;
            });
            $("#variant-selector-block-sale").each(function() {
               variantBlocks++;
            });

            i = 0;
            if(variantBlocks > 1) {
               $(".product-page .product-info-right .qty-container .the-variant-qtys").each(function() {
                  if(i == 0)
                     $(this).css("margin-bottom", "0px");
                  i++;
               });

               $("#variant-selector-block-regular").append("<span style=\"color: #B9272B; font-size: 1.3em;\">Select colors at sale prices</span><div class=\"clr\"></div>");
            }


         }

         $("a.curr-category-link").append("<img src=\"http://media.orchardbrands.com/opt/assets/images/bkg/arrow_current_category.gif\" />");
         $("div.curr-subcat-link").append("<img src=\"http://media.orchardbrands.com/opt/assets/images/bkg/arrow_current_subcat.gif\" />");
      },

      //category and section fix: make thumbnail images larger
      largerImageFix : function() {
         var pageName = window.location.pathname;
         if (pageName.indexOf("category") != -1 || pageName.indexOf("section") != -1 || pageName.indexOf("thumbnail") != -1 || pageName.indexOf("search") != -1){
            var i = 0;
            i = 0;
            $(".prod-container .image-container a img").each(function() {
               var image_string = $(this).attr("src");
               image_string = image_string.substring(0, image_string.length - 11);
               image_string = image_string + "179x235.jpg";
               $(this).attr("src", image_string);
            });
         }
      },


      imageBugFix : function() {
         var pageName = window.location.pathname;
         if (pageName.indexOf("category") != -1 || pageName.indexOf("section") != -1 || pageName.indexOf("thumbnail") != -1) {

            $(".bug-image").each(function() {
               $(this).after("<span style=\"float: left; color: #1f65c5; font-size: 1.1em; font-weight: bold; margin: -10px 0 0;\">Cool Savings!<br />20% OFF</span>")
            });
         }
      },

      petiteBannerFix: function() {
         var txt = '<img src="http://media.orchardbrands.com/opt/assets/images/section%20banners/PetiteBanner_Sub_Subcat.gif" width="762" height="100" alt="Petites Sale Banner" />';
         $('#mainDiv .right-body .mc-area-1').html(txt).show();
      }

   };
})(jQuery);

jQuery.amo.pagefixes.init();
jQuery($.amo.pagefixes.onReadyInit);
//amojavalib.googleAnalyticSetup();
//amojavalib.pageTracker();
amojavalib.checkoutFix();
amojavalib.catalogOrderFix();
amojavalib.productPageFix();
amojavalib.imageBugFix();
//amojavalib.largerImageFix();
amojavalib.clearanceCatalogFix();
