
/// <reference name="MicrosoftAjax.js"/>
/// <reference path="Lib/jquery-1.5.1-vsdoc.js" />
/// <reference path="producteditor-0.0.js" />
/// <reference path="eventmanager-core.js" />
/// <reference path="cookiemanager-core.js" />
/// <reference path="../Wcf/SDProxy.svc" />

//
// Order Slider (orderslider-0.0.js)
// Version 0.0
//
// Written by CC
// Revised RR ~ 06/29/2009
// Revised CC ~ 01/22/2010

var ordersliderMgr = {
  ordSliderCtId: '',
  eventIndex: -1,
  lcDateRequested: { DateValue: 0 },
  lcTimeRequested: { WindowStartMins: -1, Asap: false },
  lcInterstateFlag: null,
  lcIsGrouplunchcart: null,
  onAddEventIndex: -1,
  qtyChanged: false,
  clientId: null,
  setup: function(ordSliderCt) {
    this.ordSliderCtId = '#' + ordSliderCt;
    this.addHandlers();
    this.proposalFeatureEnabled();
    $(window).load(function() { ordersliderMgr.move(); });
    if (Sys.Browser.agent == Sys.Browser.InternetExplorer) if (Sys.Browser.version < 7) ordersliderMgr.move();
    $('#ordMgrSlider-locationSelected-btn').click(function() { ordersliderMgr.renderLocationSlider(); return false; });
    $('#ordMgrSlider-dateTimeSelected-btn').click(function() { ordersliderMgr.renderDateTimeSlider(); return false; });
  },
  addHandlers: function() {
    this.eventIndex = eventMgr.onscroll.add(function() {
      ordersliderMgr.move();
    });
    eventMgr.onlocationchange.add(function() {
      ordersliderMgr.renderLocationSlider();
      ordersliderMgr.renderDateTimeSlider();
      ordersliderMgr.proposalFeatureEnabled();
    });
  },
  remHandlers: function() {
    eventMgr.onscroll.remove(this.eventIndex);
  },
  move: function() {
    var oC = $(this.ordSliderCtId);
    var c = $('#ctContainer');
    if ((oC.outerHeight() + 100) > c.innerHeight()) c.height((oC.outerHeight() + 100) + 'px');
    var topMargin = 90;
    var triggerPoint = 120;
    var popupHeight = oC.outerHeight();
    var windowHeight = $(window).height();
    var scrollPosition = 0;
    if (document.documentElement.scrollTop) {
      scrollPosition = parseInt(document.documentElement.scrollTop);
    } else if (document.body.scrollTop) {
      scrollPosition = parseInt(document.body.scrollTop);
    }
    if (windowHeight < (popupHeight + 40) || (scrollPosition < triggerPoint)) {
      oC.stop();
      oC.animate({ top: String(topMargin) + 'px' }, 500);
    } else {
      oC.stop();
      oC.animate({ top: String(scrollPosition - triggerPoint + topMargin) + 'px' }, 500);
    }
  },
  updProductQty: function(clientId) {
    var o = new Specialtys.SpecialtysDirect.Client.OrderSummarySlider(this.clientId);
    var container = o.getContainer();
    var products = container.children();
    var items = new Array();

    for (var i = 0; i < products.length; i++) {
      if (products[i].id != "orderTotal") {
        var product_id = products[i].id.replace(this.clientId + '_prod_', "");
        var qty = $("#" + this.clientId + "_qty_" + product_id).val();
        var itemPrice = parseFloat($("#" + this.clientId + "_itemPrice_" + product_id).val());
        items.push({ ProductId: product_id, Quantity: qty, Price: itemPrice });
      }
    }
    lunchcartMgr.updateCart(items);
    ordersliderMgr.qtyChanged = false;
    $('#orderSlider-confirmBtn').html('confirm contents &raquo;');
  },
  clearProducts: function(clientId) {
    var o = new Specialtys.SpecialtysDirect.Client.OrderSummarySlider(this.clientId);
    var container = o.getContainer();
    var products = container.children();

    for (var i = 0; i < products.length; i++) {
      if (products[i].id != "orderTotal") {
        var product_id = products[i].id.replace(this.clientId + '_prod_', "");
        o.removeProductFast({ ProductId: product_id });
      }
    }
  },
  refresh: function(clientId) {
    this.clearProducts(this.clientId);
    var o = new Specialtys.SpecialtysDirect.Client.OrderSummarySlider(this.clientId);
    var container = o.getContainer();
    var products = container.children();
    specialtys.com.SDProxy.LoadLunchcartItems(function(data) {
      for (var i = 0; i < data.length; i++) {
        o.addProduct(data[i], data[i].Quantity);
      }
    });
  },
  applyTemplate: function(data, clientId, product, qty) {
    var item = new Specialtys.SpecialtysDirect.Client.OrderSummarySlider(this.clientId);
    var itemId = item.generateItemId(product);
    data = data.replace("!itemID", itemId);
    data = data.replace("!qtyId", item.generateQtyId(product));
    data = data.replace("!qtyValue", qty);
    data = data.replace("!itemName", product.OrderSummaryName + ((product.ProductTypeId == 100 || product.ProductTypeId == 110 || product.ProductTypeId == 115) ? ' (edited) ' : ''));
    data = data.replace("!itemLinePriceId", item.generateLinePriceId(product));
    data = data.replace("!itemLinePriceValue", (parseFloat(qty) * product.Price).toFixed(2));
    data = data.replace("!itemPriceId", item.generatePriceId(product));
    data = data.replace("!itemPriceValue", product.Price);
    data = data.replace("!edits", product.FriendlyIngredientEditsHtml);
    data = data.replace("!instructs", product.SpecialInstructions);
    var ele = $(data);
    //assign events
    ele.find("#edit").click(function() { productMgr.showEditor(product.ProductId, 'lunchcart'); return false; });
    ele.find("#remove").click(function() { lunchcartMgr.removeFromCart(product.ProductId, product.Price); return false; });
    ele.find("#addtofav").click(function() {
      userMgr.requireCustomerId(function() {
        productMgr.addFavorite(product.ProductId, function() {
          alert('Item added to my favorites.');
          productMgr.showFavorites();
        });
      });
      return false;
    });
    if (product.IsReadOnly == false) {
      ele.find("#rename").click(function() { productMgr.showRename(product.ProductId); return false; });
      ele.find("#rename").attr('title', 'click to rename item');
      ele.find('#prodHdr').addClass('renameEnabled');
    }
    ele.find("#add").click(function() {
      var o = new Specialtys.SpecialtysDirect.Client.OrderSummarySlider($("#clientId").val());
      o.increaseQty(product);
      return false;
    });
    ele.find("#sub").click(function() {
      var o = new Specialtys.SpecialtysDirect.Client.OrderSummarySlider($("#clientId").val());
      o.decreaseQty(product);
      return false;
    });

    var pT = product.ProductTypeId;
    var editableProdTypes = new Array(100, 101, 110, 111, 115, 116, 152, 153);
    var isEditableType = false;

    for (var i = 0; i < editableProdTypes.length; i++) if (editableProdTypes[i] == product.ProductTypeId) isEditableType = true;

    if (product.IsReadOnly == true || isEditableType == false) {
      ele.find('#edit').parent('.btnTextSml').addClass('hide');
      ele.find('#remove').parent('.btnTextSml').removeClass('btnRModSml');
      ele.find('#editDescription').addClass('hide');
      ele.find('#specialInstruct').addClass('hide');
    }

    if (product.FriendlyIngredientEditsHtml == '') ele.find('#editDescription').addClass('hide');
    else ele.find('#editDescription').removeClass('hide');

    if (product.SpecialInstructions == '') ele.find('#specialInstruct').addClass('hide');
    else ele.find('#specialInstruct').removeClass('hide');

    ele.find('#editDescription').id = '';
    ele.find('#specialInstruct').id = '';
    ele.find('#edit').id = '';
    ele.find('#addtofav').id = '';
    ele.find('#remove').id = '';
    ele.find('#add').id = '';
    ele.find('#sub').id = '';
    ele.find('#rename').id = '';
    ele.find('#prodHdr').id = '';

    ele.insertBefore('#orderTotal');
    $('#' + itemId).hide();
    if (Sys.Browser.agent == Sys.Browser.InternetExplorer) $('#' + itemId).show();
    else $('#' + itemId).fadeIn('fast');

    //alert('check for free delivery status now...');

    item.updateSummary();

    this.move();

  },
  renderLocationSlider: function() {
    specialtys.com.SDProxy.LoadLunchcartLocation(function(data) {
      ordersliderMgr.renderLocationSliderCallback(data);
    });
  },
  renderLocationSliderCallback: function(a) {

    var c = $('#ordMgrSlider-locationSelected-btnContainer');
    var d = $('#locationOrdMgrDescription');
    var isKe = (cookieMgr.getKioskTypeFromCookie() == 3);
    var e = $('#ordMgrSliderFreeDeliveryMsg');


    //nothing

    if (a == null || a == undefined) {
      e.hide();
      c.hide();
      d.html('<b>Pickup or Delivery location has not been selected.</b> Click the button below.' + this.getLocationBtn());
      return;
    }

    if ((a.AddressId == 0 || a.AddressId == undefined) && (a.BuildingId == 0 || a.BuildingId == undefined)) {
      e.hide();
      c.hide();
      d.html('<b>Pickup or Delivery location has not been selected.</b> Click the button below.' + this.getLocationBtn());
    }

    //pickup
    if (a.AddressId == 0 && a.BuildingId > 0) {
      e.hide();
      if (a.IsLocked)
        c.hide();
      else
        c.show();
      d.html('<img src="Images/SubHeads/h3_pickupLocation.gif" alt="Pickup From" /><br/>' + a.FriendlyAddressHtml + ((a.IsLocked || isKe) ? '' : this.getLocationChangeBtn()));
      if (isKe) c.hide();
    }

    //delivery
    if (a.AddressId > 0) {
      if (a.State == 'WA') e.fadeIn(2000); else e.hide();
      if (a.IsLocked)
        c.hide();
      else
        c.show();
      d.html('<img src="Images/SubHeads/' + ((a.Type == 7) ? 'h3_shippingLocation' : ((a.IsLunchStop) ? 'h3_lunchStopLocation' : 'h3_deliveryLocation')) + '.gif" alt="Delivery To" /><br/>' + a.FriendlyAddressHtml + ((a.IsLocked) ? '' : this.getLocationChangeBtn()));
    }

  },
  getLocationBtn: function() {
    return '<br/><span class="btnTextSml btnGreenSml"><a href="#" onclick="userMgr.requireCustomerId(function() { beetMgr.showLocationSelector(); }); return false;"><span>choose pickup/delivery location</span></a></span>'
  },
  getLocationChangeBtn: function() {
    return '<br/><span class="btnTextSml btnGreenSml"><a href="#" onclick="userMgr.requireCustomerId(function() { beetMgr.showLocationSelector(); }); return false;"><span>change pickup/delivery location</span></a></span>'
  },
  disableDateTimeSelection: function() {
    $('#ordMgrSlider-dateRequested').attr('disabled', 'disabled');
    $('#ordMgrSlider-timeRequested').attr('disabled', 'disabled');
  },
  enableDateTimeSelection: function() {
    $('#ordMgrSlider-dateRequested').attr('disabled', '');
    $('#ordMgrSlider-timeRequested').attr('disabled', '');
  },
  renderDateTimeSlider: function() {
    this.disableDateTimeSelection();
    this.saveDateTimeSelectors();
    specialtys.com.SDProxy.LoadLunchcart(function(lC) {
      if (lC.DateValue != null && lC.DateValue != undefined) ordersliderMgr.lcDateRequested.DateValue = lC.DateValue;
      if (lC.TimeValue != null && lC.TimeValue != undefined) ordersliderMgr.lcTimeRequested.WindowStartMins = lC.TimeValue;
      ordersliderMgr.lcInterstateFlag = lC.InterstateFlag;
      ordersliderMgr.lcIsGrouplunchcart = lC.IsGroupLunchcartObject;
      if (ordersliderMgr.lcInterstateFlag == true) {
        $('#ordMgrSlider-timeRequested').hide();
      } else {
        $('#ordMgrSlider-timeRequested').show();
      }
      ordersliderMgr.lcTimeRequested.Asap = false;
      if (ordersliderMgr.lcIsGrouplunchcart == true) {
        $('#ordMgrSlider-btnContainer').hide();
      } else {
        $('#ordMgrSlider-btnContainer').show();
      }

      if (lC.Asap == true) ordersliderMgr.lcTimeRequested.Asap = true;
      if (lC.ItemCount == 0 || ((lC.AddressId == 0 || lC.AddressId == undefined) && (lC.BuildingId == 0 || lC.BuildingId == undefined))) {
        $('#ordMgrSlider-dateTime-msg').addClass('errorText').html('You must have items in your cart and selected pickup or delivery location first.');
      }
      else {
        if (ordersliderMgr.lcInterstateFlag == true) {
          $('#ordMgrSlider-dateTime-msg').removeClass('errorText').html('Select a shipping date using the drop down list below...');
        } else {
          $('#ordMgrSlider-dateTime-msg').removeClass('errorText').html('Select a date &amp; time using the drop down lists below...');
        }
        var dS = $('#ordMgrSlider-dateRequested');
        dS.html('');
        specialtys.com.SDProxy.LoadCheckoutDates(function(data) { ordersliderMgr.renderDateTimeSliderDates(data); });
      }
    });
  },
  renderDateTimeSliderDates: function(d) {
    var h = '';
    var dS = $('#ordMgrSlider-dateRequested');
    dS.append('<option value="{DateValue:0}">(select a date)</option>');
    var h = '';
    for (var i = 0; i < d.length; i++) {
      h += '<option value="{DateValue:' + d[i].DateValue + '}"' + ((this.lcDateRequested.DateValue == d[i].DateValue) ? ' selected="selected"' : '') + '>';
      h += d[i].FriendlyDateDescription
      h += '</option>'
    }
    dS.append(h);

    if (this.lcInterstateFlag) {
      this.enableDateTimeSelection();
    } else {
      this.renderDateTimeSliderTimes();
    }

  },
  dateChanged: function() {
    this.saveDateTimeSelectors();
    if (!this.lcInterstateFlag) this.renderDateTimeSliderTimes();
  },
  saveDateTimeSelectors: function() {
    if ($('#ordMgrSlider-dateRequested option:selected').attr('value') != '') eval("this.lcDateRequested = " + $('#ordMgrSlider-dateRequested option:selected').attr('value'));
    if ($('#ordMgrSlider-timeRequested option:selected').attr('value') != '') eval("this.lcTimeRequested = " + $('#ordMgrSlider-timeRequested option:selected').attr('value'));
    if (this.lcDateRequested == undefined) this.lcDateRequested = { DateValue: 0 };
    if (this.lcTimeRequested == undefined) this.lcTimeRequested = { WindowStartMins: -1, Asap: false };
  },
  renderDateTimeSliderTimes: function() {
    var tS = $('#ordMgrSlider-timeRequested');
    tS.html('');
    specialtys.com.SDProxy.LoadCheckoutTimes(this.lcDateRequested.DateValue, function(data) {
      ordersliderMgr.renderDateTimeSliderTimesCallback(data);
    });
  },
  renderDateTimeSliderTimesCallback: function(t) {
    var tS = $('#ordMgrSlider-timeRequested');
    var indexSelected = -1;
    var asapAvailable = false;
    if (t.length > 0) tS.append('<option value="{ WindowStartMins: -1, Asap: false }">(select a time)</option>');
    if (t.length == 0) tS.append('<option value="{ WindowStartMins: -1, Asap: false }">(no times for selected day)</option>');
    var h = '';
    for (var i = 0; i < t.length; i++) {
      h += '<option value="{ WindowStartMins: ' + t[i].WindowStartMins + ', Asap: ' + t[i].Asap + ' }"'
      if (t[i].WindowStartMins == this.lcTimeRequested.WindowStartMins && t[i].Asap == this.lcTimeRequested.Asap) {
        h += ' selected';
        indexSelected = i;
      }
      h += '>'
      h += t[i].FriendlyTimeSlotDescription
      h += '</option>'
    }
    tS.append(h);
    this.enableDateTimeSelection();
    if (this.lcIsGrouplunchcart) this.disableDateTimeSelection();
  },
  setDateTimeRequested: function(callback) {
    this.disableDateTimeSelection();
    this.saveDateTimeSelectors();
    if (this.lcDateRequested.DateValue >= 0 && this.lcTimeRequested.WindowStartMins >= 0) {
      if (this.lcTimeRequested.Asap == true) {
        specialtys.com.SDProxy.SetDateTimeRequestedAsap(function() {
          ordersliderMgr.setDateTimeRequestedCallback(callback);
        }, function() {
          ordersliderMgr.enableDateTimeSelection();
          callback.call(this);
        });
      }
      else {
        specialtys.com.SDProxy.SetDateRequestedByOffset(this.lcDateRequested.DateValue, this.lcTimeRequested.WindowStartMins, function() {
          ordersliderMgr.setDateTimeRequestedCallback(callback);
        }, function() {
          ordersliderMgr.enableDateTimeSelection();
          callback.call(this);
        });
      }
    } else if (this.lcDateRequested.DateValue >= 0 && this.lcInterstateFlag == true) {
      specialtys.com.SDProxy.SetDateRequestedByOffset(this.lcDateRequested.DateValue, 0, function() {
        ordersliderMgr.setDateTimeRequestedCallback(callback);
      }, function() {
        ordersliderMgr.enableDateTimeSelection();
        callback.call(this);
      });
    } else {
      ordersliderMgr.enableDateTimeSelection();
    }
  },
  setDateTimeRequestedCallback: function(callback) {

    ordersliderMgr.enableDateTimeSelection();
    if (callback != undefined && callback != null) callback.call(this);
  },
  checkout: function() {
    this.saveDateTimeSelectors();
    if (this.qtyChanged == true) this.updProductQty(this.clientId);
    if (this.lcDateRequested.DateValue >= 0 && this.lcTimeRequested.WindowStartMins >= 0) {
      this.setDateTimeRequested(function() {
        userMgr.checkout();
      });
    }
    else {
      userMgr.checkout();
    }
  },
  proposalFeatureEnabled: function() {
    userMgr.initFromCookie();
    //&& ordersliderMgr.lcIsGrouplunchcart == false removed
    if (userMgr.proposalFeatureEnabled) {
      $("#ordMgrSlider-proposalBtn").removeClass('hide');
      //$('#ordMgrSlider-checkoutBtn').addClass('btnRModLg');
    } else {
      $("#ordMgrSlider-proposalBtn").addClass('hide');
      //$('#ordMgrSlider-checkoutBtn').removeClass('btnRModLg');
    }
  }
}

Type.registerNamespace('Specialtys.SpecialtysDirect.Client.OrderSummarySlider');

Specialtys.SpecialtysDirect.Client.OrderSummarySlider = function(clientId) {
    // constructor
    this._clientId = clientId;
}
Specialtys.SpecialtysDirect.Client.OrderSummarySlider.prototype = {
  decreaseQty: function(product) {
    var currentQty = parseInt($("#" + this.generateQtyId(product)).val());
    var basePrice = parseFloat($("#" + this.generatePriceId(product)).val());
    ordersliderMgr.qtyChanged = true;
    $('#orderSlider-confirmBtn').html('update quantities &raquo;');
    if ((currentQty - 1) > 0) {
      $("#" + this.generateQtyId(product)).val(currentQty - 1);
      $("#" + this.generateLinePriceId(product)).val((parseFloat(currentQty - 1) * basePrice).toFixed(2));
    } else {
      $("#" + this.generateQtyId(product)).val("1");
      $("#" + this.generateLinePriceId(product)).val(basePrice.toFixed(2));
    }

  },
  showTotals: function() {
    var orderTotal = $("#orderTotal");
    var updateButton = $("#updateWraper");
    orderTotal.removeClass();
    orderTotal.addClass("total");
    updateButton.removeClass();
    updateButton.addClass("btnContainer");
  },
  loadTotals: function() {
    var emptyTag = $("#ordMgrEmptyMsg");
    if (emptyTag.length == 0) {
      this.showTotals();
    }
    else {
      this.hideTotals();
    }
  },
  increaseQty: function(product) {
    var currentQty = parseInt($("#" + this.generateQtyId(product)).val());
    var basePrice = parseFloat($("#" + this.generatePriceId(product)).val());
    ordersliderMgr.qtyChanged = true;
    $('#orderSlider-confirmBtn').html('update quantities &raquo;');
    $("#" + this.generateQtyId(product)).val(currentQty + 1);
    $("#" + this.generateLinePriceId(product)).val(((parseFloat(currentQty + 1) * basePrice)).toFixed(2));
  },
  updateSummary: function() {
    var container = this.getContainer();
    var products = container.children();
    var totalPrice = $('#' + this._clientId + '_tPrice');
    totalPrice.val("0.00");
    for (var i = 0; i < products.length; i++) {
      if (products[i].id != "orderTotal") {
        var product_id = products[i].id.replace(this._clientId + '_prod_', "");
        var qty = parseInt($("#" + this.generateQtyId({ ProductId: product_id })).val());
        var itemPrice = parseFloat($("#" + this.generatePriceId({ ProductId: product_id })).val());
        var itemTotal = parseFloat(qty) * itemPrice;
        totalPrice.val((parseFloat(totalPrice.val()) + itemTotal).toFixed(2));
      }
    }
    if (parseFloat(totalPrice.val()) == 0) this.hideTotals();

  },
  removeProduct: function(product) {
    var obj = this;
    var itemId = this.generateItemId(product);
    if (Sys.Browser.agent == Sys.Browser.InternetExplorer) {
      $('#' + itemId).remove();
      obj.updateSummary();
    }
    else {
      $('#' + itemId).fadeOut('fast', function() {
        $('#' + itemId).remove();
        obj.updateSummary();
      });
    }
  },
  removeProductFast: function(product) {
    var obj = this;
    var itemId = this.generateItemId(product);
    $('#' + itemId).remove();
    obj.updateSummary();
  },
  getContainer: function() {
    return $('#' + this._clientId + '_body');
  },
  generateItemId: function(product) {
    return this._clientId + '_prod_' + product.ProductId;
  },
  generateQtyId: function(product) {
    return this._clientId + '_qty_' + product.ProductId;
  },
  generatePriceId: function(product) {
    return this._clientId + '_itemPrice_' + product.ProductId;
  },
  generateLinePriceId: function(product) {
    return this._clientId + '_linePrice_' + product.ProductId;
  },
  hideTotals: function() {
    var container = this.getContainer();
    var liEle = $("<li id='ordMgrEmptyMsg'/>");
    var pTag = $("<p class='toolTip'></p>");
    var orderTotal = $("#orderTotal");
    var updateButton = $("#updateWraper");
    var emptyTag = $("#ordMgrEmptyMsg");
    if (emptyTag.length == 0) {
      pTag.append(" <b>Your order is empty!</b> Add an item to your order by clicking one of the \"add to order\" buttons.");
      liEle.append(pTag);
      container.prepend(liEle);
    }
    orderTotal.removeClass();
    orderTotal.addClass("total hide");
    updateButton.removeClass();
    updateButton.addClass("btnContainer hide");
  },
  addProduct: function(product, qty) {
    var container = this.getContainer();
    var emptyTag = $("#ordMgrEmptyMsg");
    var clientId = this._clientId;
    var curProdQty = $('#' + this.generateQtyId(product));
    var curProdPrice = $('#' + this.generateLinePriceId(product));
    if (emptyTag.length != 0) {
      emptyTag.remove();
      this.showTotals();
    }
    if (curProdQty.length != 0) {
      // product already exists, update only
      curProdQty.val(parseInt(curProdQty.val()) + parseInt(qty));
      curProdPrice.val((curProdQty.val() * product.Price).toFixed(2));
      this.updateSummary();
      return;
    }
    $.get('Templates/ord-summary-slider-item.htm', '', function(data, status) { ordersliderMgr.applyTemplate(data, clientId, product, qty); });
  }
}

