/* Victor LaLoggia @ C2 Jan. 20, 2010
*  This file contains common functionality for all Selector pages.
*  Currently, these are: Product Selector, Shop All KCups, and Quick Pick
*/

/* Victor LaLoggia @ C2, June 12, 2009
*   Sitecore's page editor is implemented with Prototype.js.
*   It is well known that Prototype and jQuery do not play well together.
*   As per Sitecore (http://sitecoresupport.blogspot.com/2009/01/jquery-conflicts-with-pageeditor.html), 
*   vic added this modification (http://docs.jquery.com/Using_jQuery_with_Other_Libraries).
*
*   Every reference to the jQuery '$' nomenclature has been replaced with '$j'
*/
var $j = jQuery.noConflict();

if (typeof GMCRSelectorLibrary == 'undefined') var GMCRSelectorLibrary = {};

//jquery helper method to switch to switch src values
$j.fn.changeSrc = function() {
  var args = arguments[0] || {};

  var currentSrc = $j(this).attr('src').toLowerCase();
  var regexTo = new RegExp(args.newValue);

  //let's only change it if it has to be changed
  if (!currentSrc.match(regexTo)) {
    if (!(currentSrc.match(/\.png$/) && $j.browser.msie && $j.browser.version.substr(0, 1) < 7)) {
      // this dos not work for PNG in IE6
      $j(this).attr('src', $j(this).attr('src').replace(args.oldValue, args.newValue));
    } else {
      // this will work on IE6 if the png is wrapped in something, probably anything, as the only element
      try {
        var imageParent = $j(this).parent();
        var imageParentHtml = imageParent.html();
        var regexFrom = new RegExp(args.oldValue, "g");
        imageParentHtml = imageParentHtml.replace(regexFrom, args.newValue);
        imageParent.html(imageParentHtml);
      } catch (err) {
        alert(err.description);
      }
    }
  }
};

///These need to be rebound when the item is loaded into the DOM as 'change'
//events are not support by 'live()'
GMCRSelectorLibrary.BindItemUpdateEvents = function() {
  $j("select[id^='selGrindCodes']").unbind('change');
  $j("select[id^='selGrindCodes']").change(function() {
    GMCRSelectorLibrary.HandleLineItemUpdate(this);
  });
  $j("select[id^='selQuantity']").unbind('change');
  $j("select[id^='selQuantity']").change(function() {
    GMCRSelectorLibrary.HandleLineItemUpdate(this);
  });
  $j("[id^='chkRecurring']").unbind('click');
  $j("[id^='chkRecurring']").click(function() {
    GMCRSelectorLibrary.HandleLineItemUpdate(this);
  });
};

//Constructs the Pricing Club URL
GMCRSelectorLibrary.BuildClubBasketURL = function(commandName) {
  var url = "/ajaxHandlers/productselectorhandler.aspx?commandName=";
  url += commandName;
  return url;
};

//Constructs the Pricing Club URL
GMCRSelectorLibrary.BuildUpdateFrequencyURL = function(commandName) {
  var url = "/ajaxHandlers/productselectorhandler.aspx?commandName=";
  url += commandName;
  return url;
};

//Constructs the Pricing Club URL
GMCRSelectorLibrary.BuildUpdateItemURL = function(commandName) {
  var url = "/ajaxHandlers/productselectorhandler.aspx?commandName=";
  url += commandName;
  return url;
};

GMCRSelectorLibrary.CreateUpdatePostData = function(lineItemID, productID) {
  var updatePost = '';
  var recurringValue = true;
  if ($j('#chkRecurring_' + lineItemID + '_' + productID).length > 0) { //use the choice if available
    recurringValue = $j('#chkRecurring_' + lineItemID + '_' + productID).is(':checked') ? true : false;
  }
  updatePost += 'lineItemID=' + lineItemID;
  updatePost += '&psProductId=' + productID.replace('Products', '(Products)');
  updatePost += '&clubMode=' + GMCR.ClubMode;
  updatePost += '&cluborderid=' + GMCR.ClubOrderID
  updatePost += '&isRecurring=' + recurringValue;
  updatePost += '&frequency=' + $j('#ProductSelectorFrequency').val()
  updatePost += '&quantity=' + $j('#selQuantity_' + lineItemID + '_' + productID).val();
  updatePost += '&grindCode=' + $j('#selGrindCodes_' + lineItemID + '_' + productID).val();
  return updatePost;
};

//Pull this from the hidden field updated by ajax
GMCRSelectorLibrary.CurrentProductCount = function() {
  return parseInt($j('#hdnProductCount-' + GMCR.CurrentTabType).val());
};

//Change the image to 'off' and set a flag to disable submitting
//cannot unbind event as it was not set with jquery
GMCRSelectorLibrary.DisableSubmit = function() {
  GMCR.SubmitEnabled = false;
  var imageElement = $j("[clientid = 'btnSubmitUpdate']");
  $j(imageElement).attr('src', $j(imageElement).attr('src').replace('.gif', '_off.gif'));
};

//Change the image to 'on' and set a flag to enable submitting
//cannot unbind event as it was not set with jquery
GMCRSelectorLibrary.EnableSubmit = function() {
  GMCR.SubmitEnabled = true;
  var imageElement = $j("[clientid = 'btnSubmitUpdate']");
  $j(imageElement).attr('src', $j(imageElement).attr('src').replace('_off', ''));
};

GMCRSelectorLibrary.GetFilterElementByName = function(filterName) {
  return $j(".tagList[tabType='" + GMCR.CurrentTabType + "'] li a:contains('" + filterName + "')");
};

//Handle the updating of a line item, quantity, grindcode, recurrence
GMCRSelectorLibrary.HandleLineItemUpdate = function(element) {
  var renderURL = GMCRSelectorLibrary.BuildUpdateItemURL('UpdateProduct');
  var postData = GMCRSelectorLibrary.CreateUpdatePostData($j(element).attr('id').split('_')[1], $j(element).attr('id').split('_')[2]);
  $j.ajax({ type: "POST", data: postData, url: renderURL, dataType: 'json', contentType: 'application/x-www-form-urlencoded',
    success: function(data) {
      GMCR.PriceClub();
    }
  });
};

//Highlights a filter
GMCRSelectorLibrary.HighlightFilter = function(filterElement) {
  filterElement.css("background-color", "#c86202");
  filterElement.css("color", "#ffffff");
};

//Highlights a filter by tag contents name
GMCRSelectorLibrary.HighlightFilterByName = function(filterName) {
  GMCR.HighlightFilter(GMCRSelectorLibrary.GetFilterElementByName(filterName));
};

//Reset the paging control HTML
GMCRSelectorLibrary.ResetPagingView = function() {
  $j('#pageStart-' + GMCR.CurrentTabType).text(GMCR.CurrentStartNumber[GMCR.CurrentTabType]);
  $j('#pageStop-' + GMCR.CurrentTabType).text(GMCR.CurrentEndNumber[GMCR.CurrentTabType]);
  $j('#pageCount-' + GMCR.CurrentTabType).text(GMCRSelectorLibrary.CurrentProductCount());
};

//Reset the scrolling arrow images using the current values
GMCRSelectorLibrary.ResetScrollArrows = function() {
  // I've seen this undefuined for some strange reason
  try {
    if (GMCR.ScrollingEnabled[GMCR.CurrentTabType].right) {
      $j('#scrollRight-' + GMCR.CurrentTabType + ' img').changeSrc({ oldValue: '_off', newValue: '_on' });
    } else {
      $j('#scrollRight-' + GMCR.CurrentTabType + ' img').changeSrc({ oldValue: '_on', newValue: '_off' });
    }
    if (GMCR.ScrollingEnabled[GMCR.CurrentTabType].left) {
      $j('#scrollLeft-' + GMCR.CurrentTabType + ' img').changeSrc({ oldValue: '_off', newValue: '_on' });
    } else {
      $j('#scrollLeft-' + GMCR.CurrentTabType + ' img').changeSrc({ oldValue: '_on', newValue: '_off' });
    }
  } catch (Error) {
    // leave them as is....
  }
};

//Scrolls the current viewport for the current scroll target and tab type
GMCRSelectorLibrary.ScrollProducts = function(speed) {
  $j('#resultsList-' + GMCR.CurrentTabType).scrollTo($j('#scrollTarget-' + GMCR.CurrentTabType + '-' + GMCR.CurrentScrollSpot[GMCR.CurrentTabType]), speed, { axis: 'x' });
};

//Select a filter and get the products for it
GMCRSelectorLibrary.SelectFilter = function(element) {
  $j('#justAddedMiniCart').hide();
  GMCRSelectorLibrary.UnHighlightAllFilters();
  GMCRSelectorLibrary.HighlightFilter($j(element));
  GMCR.GetProducts(GMCR.CurrentTabType, GMCR.CurrentBrand[GMCR.CurrentTabType], $j($j(element)[0]).text());
};

//Sets the filter font size taking values from 1 - 20 and 
//setting values between 1 and 2
GMCRSelectorLibrary.SetFilterSize = function(frequency) {
  return (frequency / 10) + 1 + "em";
};

GMCRSelectorLibrary.SetTabStatusFromLink = function(div) {
  var image = $j(div).find('img:first');
  GMCR.SetTabStatus(image, image.attr('id'));
};

//Unhighlights all filters
GMCRSelectorLibrary.UnHighlightAllFilters = function() {
  $j(".tagList[tabType='" + GMCR.CurrentTabType + "'] li a").each(function() {
    GMCRSelectorLibrary.UnHighlightFilter($j(this));
  });
};

//Unhighlights a filter
GMCRSelectorLibrary.UnHighlightFilter = function(filterElement) {
  filterElement.css("background-color", '');
  filterElement.css("color", '');
};

//***************************
//  On Document Ready
//***************************
$j(document).ready(function() {

  //Current tab type defaults to 'all' or the one constained to by the custom club link
  if (GMCR.ClubType === 'all') {
    GMCR.CurrentTabType = 'kcup';
  }
  else {
    GMCR.CurrentTabType = GMCR.ClubType;
    //hide all tabs
    $j("[id^='content']").hide();
    //show this one
    $j("[id^='content-" + GMCR.CurrentTabType + "']").show();
  }

  GMCR.SubmitEnabled = true;

  //Set sizes of filters
  $j(".tagList li a").each(function() {
    $j(this).css("fontSize", GMCRSelectorLibrary.SetFilterSize($j(this).attr('freq')));
  });

  //Bind change events to any current items when the page loads
  GMCRSelectorLibrary.BindItemUpdateEvents();
  
    //Handler for the updating of the club frequency
  $j('#ProductSelectorFrequency').change(function() {
    var renderURL = GMCRSelectorLibrary.BuildUpdateFrequencyURL('UpdateFrequency');
    $j.ajax({ type: "POST", data: 'clubMode=' + GMCR.ClubMode + '&cluborderid=' + GMCR.ClubOrderID + '&frequency=' + $j('#ProductSelectorFrequency').val(), url: renderURL, dataType: 'json', contentType: 'application/x-www-form-urlencoded',
      success: function(data) {

      }
    });
  });

  //When the user submits the club
  $j("[clientid = 'btnSubmitUpdate']").click(function() {
    if (GMCR.SubmitEnabled) {
      if (GMCR.ClubMode === 'new') {
        if ($j('img[removeid]').length === 0) {
          tb_show('', 'TB_inline?height=155&width=300&inlineId=noRecurringItemsInClubDiv&modal=true');
          return false;
        }
      } 
      else {
        //must be at least one recurring item
        if (($j('img[removeid]').length === 0) || ($j("[id^='chkRecurring_']:not([disabled]):checked").length === 0)) {
          tb_show('', 'TB_inline?height=155&width=300&inlineId=noRecurringItemsInClubDiv&modal=true');
          return false;
        }
      }
    } 
    else {
      return false;
    }
  });
});
