/* 
 * 
 */

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');
         }
      },


      /**
       * 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() {
         $('#login-page .member-login .sign-in')
               .clone().appendTo('#login-page .member-login div.FormArea').show()
               .end().remove(); //remove the original

         //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

         // 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_211242.js'%3E%3C/script%3E%3C/div%3E"));
         }
      },


      //category and section page fix: 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";
               //image_string = image_string.replace("http://media.orchardbrands.com", "http://staging.fashionspecialists.com");
               $(this).attr("src", image_string);

            });
         }
      },

      // Cart-Helper
      addToCart: function() {

         // Parameters we need
         var ts = timestamp();
         var action = "addProducts";
         var productName = $.amo.util.url.gup("productName");
         var productId = $.amo.util.url.gup("productId");
         var categoryId = $.amo.util.url.gup("categoryId");
         var parentCategoryId = $.amo.util.url.gup("parentCategoryId");
         var subCategoryId = $.amo.util.url.gup("subCategoryId");
         var redirectPath = $.amo.util.url.gup("redirectPath");
         var source = "web";
         var productVariantId = $.amo.util.url.gup("productVariantId");
         var quantity = 1;
         var productCount = 1;
         var personalizeThisItem = false;

         // Set URL
         var requestURL = "/checkout/add_item_pc.cmd";

         // Create Parm String
         var params = "ts=" + ts +
               "&action=" + action +
               "&productName=" + productName +
               "&productId=" + productId +
               "&categoryId=" + categoryId +
               "&parentCategoryId=" + parentCategoryId +
               "&subCategoryId=" + subCategoryId +
               "&redirectPath=" + redirectPath +
               "&source=" + source +
               "&productVariantId=" + productVariantId +
               "&quantity=" + quantity +
               "&productCount=" + productCount +
               "&personalizeThisItem=" + personalizeThisItem;

         // Add the Item to the Cart via AJAX
         $.ajax({
            type: "POST",
            url: requestURL,
            data: params,
            dataType: "html",
            timeout: 15000,
            success: function(data) {
               document.location = unescape(redirectPath);
               return true;
            },
            error: function() {
               return false;
            }
         });
      }

   }
})(jQuery);

amojavalib.bizrateSetup();
amojavalib.largerImageFix();
$.amo.pagefixes.init();

(function($) {
   //todo: this is only needed until KINO is completed and we are no longer using A/B branching
   //fix the location of the totals on FS site (currently show above the returning customers box)
   var tbl = $('#che-bil-totals-login #order-totals');
   if( tbl.length == 1 ) {
      tbl.remove().css({'margin-top': '75px'}).appendTo('#che-bil-totals-login');
   }
})(jQuery);

// Cart Helper 
if ( $.amo.util.url.gup("pageName") == "cartadd" ) {
   amojavalib.addToCart();
}




