/* 
 * 
 */

var passin = "Q104626=";
var order_total = 0;
var order_zip = "";
var br_cartzip = "";
var order_string = "";
var br_cartdata = "";

(function($) {
   $.amo.pagefixes = window.amojavalib = {
      init: function() {
         var pageName = $.amo.util.url.getPage();
         switch(pageName) {
            case 'checkout_login':
               $.amo.pagefixes.fixPasswordLink();
               break;
            case 'checkout':
               $.amo.pagefixes.fixCheckoutDefaultPayment();
               $.amo.pagefixes.fixHelpOverlay();
               $.amo.pagefixes.fixPasswordLink();
               break;
            case 'login':
               $.amo.pagefixes.fixLoginForm();
               break;
            case 'search_command':
            case 'search':
               $.amo.pagefixes.fixEmptyPaginationBars();
               break;
            default:
            //$.amo.debug.say("page type "+pageName+" 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');
         }
      },


      /**
       * 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);
         };
      },

      fixCheckoutDefaultPayment: function() {
         $('#differentCreditCard').attr('checked', true).click();
      },

      /**
       * 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" />');
      },

      // setup the scripts for the bizrate survey
      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;

            /*

             // old version using CI info
             passin = passin + CI_OrderID;
             for (i = 0; i < CI_ItemPrices.length; i++) {
             order_total += (parseFloat(CI_ItemPrices[i]) * parseInt(CI_ItemQtys[i]));
             }
             order_total += parseFloat(CI_Tax);
             order_total += parseFloat(CI_Shipping);
             order_zip = CI_ShipZIP;
             br_cartzip = 'Q113198=' + order_total + '&Q113199='
             + order_zip;
             order_string = s.products.split(";");
             for (i = 0; i < 5; i++) {
             if (i >= CI_ItemIDs.length)
             break;
             if (i > 0)
             br_cartdata += '|';
             br_cartdata += 'SKU=' + CI_ItemIDs[i] + '&MPID='
             + order_string[i * 5 + 1] + '&ITEMAMOUNT='
             + CI_ItemPrices[i];
             }
             */

            document.write(unescape("%3Cdiv id='bizrate-banner'%3E%3Cscript type='text/javascript' src='https://eval.bizrate.com/js/pos_210990.js'%3E%3C/script%3E%3C/div%3E"));
         }
      },

      /* 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-5");
       pageTracker._trackPageview();
       } catch (err) {
       }
       },
       */
      // fix the cc fields in the order payment page
      checkoutFix : function() {
         $(".required-message").html("* Required items are <b>bold</b>");
         $("#che-edi-required-text").html("* Required items are <b>bold</b>");
         if ($.amo.util.url.isPage("checkout")) {
            $("#che-bil-bill-info h4").html("Checkout as a Guest");
         }
         if ($.amo.util.url.isPage("payment")) {
            $("#che-pay-pi-one").css("height", "575px");
         }
         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", "505px");
         }
         if ($.amo.util.url.isPage("credit_card_payment")) {
            $("#che-pay-pi-one").css("height", "575px");
            var i = 0;
            $("#che-pay-pi-one .FormEntry").each(function() {
               if(i == 0) {
                  if($(this).height() > 100) {
                     var j = 0;
                     $("#che-pay-pi-one .save-cc").each(function() {
//									if(j == 0)
//										$(this).css("margin", "170px 0 0 50px");
                        j++;
                     });
                     $("#che-pay-pi-two").css("margin-top", "-192px");
                  }
               }
               i++;
            });
         }
         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" : "10px",
                     "top" : "63px",
                     "padding" : "0 0 0 62px",
                     "margin" : "15px 0 0"
                  })
                  var j = 0;
                  var formHeight = 0;
                  $(this).children().each(function() {
                     formHeight += $(this).height();
                     if($(this).hasClass("ErrorText") && $(this).height() > 16) {
                        formHeight += 15;
                        $(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 = 75;
            $("#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");
            i = 0;
            $("#cc-Month option").each(function() {
               if(i == 0) {
                  var option_string = $(this).html();
                  option_string = option_string.substring(option_string.indexOf(" ") + 1);
                  $(this).html(option_string);
               }
               i++;
            });
            i = 0;
            $("#cc-Year option").each(function() {
               if(i == 0) {
                  var option_string = $(this).html();
                  option_string = option_string.substring(option_string.indexOf(" ") + 1);
                  $(this).html(option_string);
               }
               i++;
            });
         }
         if ($.amo.util.url.isPage("receipt")) {
            // we only tweak the checkout page for the pre-kino versions
            var sgCookie = $.cookie('SG');
            if( !sgCookie || sgCookie == 'B' ) {
               var i = 0;
               $("#che-rec-billing-info p").each(function() {
                  if (i == 0)
                     $(this).css({
                        "height" : "75px",
                        "width" : "274px",
                        "clear" : "both",
                        "float" : "left"
                     });
                  if (i == 1)
                     $(this).css({
                        "height" : "75px",
                        "width" : "174px",
                        "clear" : "both",
                        "float" : "right",
                        "margin" : "-97px 0 0"
                     });
                  i++;
               });
               i = 0;
               $("#che-rec-billing-info h4").each(function() {
                  if (i == 0)
                     $(this).css({
                        "width" : "278px",
                        "float" : "left"
                     });
                  if (i == 1)
                     $(this).css({
                        "width" : "178px",
                        "float" : "right",
                        "margin" : "-27px 0 0"
                     });
                  i++;
               });
               i = 0;
               $("#che-rec-content .shipto-box .order-info-detail div")
                     .each(function() {
                        if (i == 1 || i == 2)
                           $(this).css("display", "none");
                        i++;
                     });
            }
         }
      },

      //category and section page fix: change pricing format and make 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);

            });
         }
      },

      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/cs/assets/images/bkg/product_pagination_arrow_left_off.gif");
            $(".product-pagination a:last-child img").attr("src", "http://media.orchardbrands.com/cs/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 hasMultiColor = false;
//            $(".qty-container").children().each(function() {
//               if($(this).hasClass("add-regular"))
//                  hasMultiColor = true;
//            });
//            if(hasMultiColor) {
//               $("#addToCartButton").css("margin-top", "-90px");
//               $("#updateToCartButton").css("margin-top", "-90px");
//            }
//            else {
//               $("#addToCartButton").css("margin-top", "-65px");
//               $("#updateToCartButton").css("margin-top", "-65px");
//            }

         }

      }

   }
})($);

amojavalib.bizrateSetup();
//amojavalib.googleAnalyticSetup();
//amojavalib.pageTracker();
amojavalib.checkoutFix();
amojavalib.productPageFix();
amojavalib.largerImageFix();
$.amo.pagefixes.init();
