/* 
 * 
 */

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 p = $.amo.util.url.getPage();
         switch(p) {
            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;
            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 don't like teh uglies provided by our insane-in-the-membrane vendor who lacks midichlorians, so we
       * have the pagination on section pages set to display none. Here, we will extract the link and create our own.
       */
      fixSectionPagination: function() {
         $('.category-page .sub-cat-header').each(function() {
            var $this = $(this),
                  count = $.amo.pagefixes.getSectionCount($this.find('.pagination')),
                  img   = "<img src='http://media.orchardbrands.com/bf/assets/images/img/webding-rightarrow.png' width='10' height='10' alt='View More' />";
            if( count[1] === 0 || count[1] > 4 ) {
               $this.find('.pagination a').eq(0)
                     .html("<span>View More "
                     +$this.find('.sub-cat-name').eq(0).html()
                     +img
                     +"</span>")
                     .addClass('revisedSectionPagination')
                     .insertBefore($this.find('.clr'));
            }
            else if( count[0] ) {
               $this.find('.clr').before('<div class="revisedSectionPagination message"><span>'+count[1]+' items</span></div>');
            }
         });
      },

      /**
       * 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();
      },

      getSectionCount: function($box) {
         $.amo.say($box.text());
         $.amo.say($box.text().replace('&nbsp;', ' '));
         var m = $box.text().replace('&nbsp;', ' ').match(/\d+-(\d+)\sof\s(\d+)/);
         $.amo.say(m);
         return m && m.length == 3? [m[1], m[2]] : [0,0];
      },

      /**
       * 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;

            /*
             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_179771.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-4");
       pageTracker._trackPageview();
       } catch (err) {
       }
       },
       */
      // create cookie for targeted content
      createTargetedContent : function() {
         $("a.parent-category-link").each(function() {
            var targetedContentName = $(this).html();
            var date = new Date();
            date.setTime(date.getTime() + (24 * 60 * 60 * 365 * 10 * 1000));
            var expires = ";expires=" + date.toGMTString();
            document.cookie = "amoContent" + "=" + targetedContentName + expires + ";path=/";
         });
      },

      // fix the cc fields in the order payment page
      checkoutFix : function() {
         if ($.amo.util.url.isPage("payment")) {
            $("#che-pay-pi-one").css("height", "375px");
         }
         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", "425px");
         }
         if ($.amo.util.url.isPage("credit_card_payment")) {
            $("#che-pay-pi-one").css("height", "460px");
         }
         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" : "70px",
                     "top" : "25px"
                  });
                  var j = 0;
                  var formHeight = 0;
                  $(this).children().each(function() {
                     formHeight += $(this).height();
                     if($(this).hasClass("ErrorText") && $(this).height() > 16)
                        $(this).html("This Bedford Fair Apparel (BFA) 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 += 25;
               position += $(this).height();
            });
            $("#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")) {
//					var i = 0;
//					$("#che-rec-billing-info p").each(function() {
//						if (i == 0)
//							$(this).css( {
//								"height" : "75px",
//								"width" : "215px"
//							});
//						if (i == 1)
//							$(this).css("height", "15px");
//						i++;
//					});
//					i = 0;
//					$("#che-rec-billing-info h4").each(function() {
//						if (i == 0)
//							$(this).css("width", "225px");
//						i++;
//					});
//					i = 0;
         }
      },

      catalogOrderFix : function() {
         var page_address = document.URL;
         if ($.amo.util.url.isPage("add_catalog_order_item.cmd")
               || $.amo.util.url
               .isPage("add_catalog_order_item.cmd#topOfPage")) {
            $(".qty-container").prepend("<span>Quantity: </span>");
         }

      },

      //category and section page fix: 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);

            });
         }
      },



      //related items on basket page fix
      shoppingCartFix : function() {
         var page_address = document.URL;
         if ($.amo.util.url.isPage("basket")){
            var i = 0;
            i = 0;
            $("#che-bas-may-like-wrap .fl .sale").each(function() {
               var span_string = $(this).html();
               span_string = span_string.substring(0, 11);
               $(this).html(span_string);
            });
            i = 0;
            $("#che-bas-may-like-wrap .fl .sale:first-child").each(function() {
               var span_string = $(this).html();
               span_string = span_string.substring(span_string.indexOf("$"));
               if(span_string.indexOf(" ") > -1)
                  span_string = span_string.substring(0, span_string.indexOf(" "));
               span_string = "Was " + span_string;
               $(this).html(span_string);
            });
            i = 0;
            $("#che-bas-may-like-wrap .fl .regular").each(function() {
               var span_string = $(this).html();
               span_string = span_string.substring(span_string.indexOf("$"));
               if(span_string.indexOf(" ") > -1)
                  span_string = span_string.substring(0, span_string.indexOf(" "));
               span_string = " " + span_string;
               $(this).html(span_string);
            });
            i = 0;
            $("#che-bas-may-like-wrap .fl 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);
            });
         }
      },

      //related items fix on product page
      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;
         i = 0;
         $("#product_rr .item-container .price .regular").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 = " " + price_string;
            $(this).html(price_string);
         });
         i = 0;
         $("#product_rr .item-container .price .sale").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 = "Now " + price_string;
            $(this).html(price_string);
         });
         i = 0;
         $("#product_rr .item-container .price  .sale:first-child").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 = "Was " + 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);
         });

         $(".more-details-link").html("Sizing Guide >");
         $(".availability-link a").html("Check Availability >");

      }
   }
})($);

amojavalib.bizrateSetup();
//amojavalib.googleAnalyticSetup();
//amojavalib.pageTracker();
amojavalib.checkoutFix();
amojavalib.catalogOrderFix();
amojavalib.productPageFix();
amojavalib.createTargetedContent();
amojavalib.shoppingCartFix();
amojavalib.largerImageFix();
$.amo.pagefixes.init();

//Cart Helper 
if ( $.amo.util.url.gup("pageName") == "cartadd" ) {
   amojavalib.addToCart();
}

