/**
 * Calculate Order Shipping Widget
 * This widget provides the main Rich Cart-like sliding drop down shipping calculation functionality.
 */
dojo.provide("atg.b2cblueprint.widget.CalculateOrderShipping");
dojo.require("dojo.lfx.*");
dojo.require("dojo.html.*");
dojo.require("dojo.html.iframe");
dojo.require("dojo.event.*");
dojo.require("dojo.widget.*");
dojo.require("dojo.io.*");

dojo.widget.defineWidget(
  "atg.b2cblueprint.widget.CalculateOrderShipping", 
  dojo.widget.HtmlWidget,
  {
    // Define all global variables for the widget.
    // templatePath: dojo.uri.dojoUri(contextPath+"/javascript/widget/template/calculateOrderShipping.html"),
    templateString: '<div id="mff_calculateShippingPopup"><div class="close"><a href="javascript:void(0);" dojoAttachEvent="onClick:toggleCalculateShipping" title="${this.i18n.closeText}">${this.i18n.closeText}</a></div><h3>${this.i18n.titleForOrder}</h3><dl><dt><span dojoAttachPoint="exceptionItemMessage" style="display:none;">${this.i18n.hasExceptionItemMessage}</span></dt><div dojoAttachPoint="groups"></div><dt class="submit"><input type="button" value="${this.i18n.calculateButtonText}" class="mff_inputButton" dojoAttachPoint="calculate" onclick="atg.b2cblueprint.shipping.getShippingCostForOrder()"></dt><dt class="note"><p>${this.i18n.calculateShippingNoteForOrder}<a href="javascript:atg.b2cblueprint.util.notifyMePopup(\'${this.contextroot}/company/shippingRatesPopup.jsp\')" title="${this.i18n.calculateShippingLarnLink}">${this.i18n.calculateShippingLarnLink}</a></p></dt></dl><dl class="total"><dt>${this.i18n.calculateShippingTotal}</dt><dd><span dojoAttachPoint="selectedMethod"></span><span dojoAttachPoint="saturdayDeliveryShow"></span><span dojoAttachPoint="calculateShippingTotal"></span></dd></dl></div>',

    // Widget properties
    triggerWidget: null,  // Reference to trigger widget
    data: null,           // Cart data - should be set with initial widget initialisation properties

    isContainer: true,    // core var, shows Dojo that this widget will contain other widgets
    firstPlacementDone: false,
    cartAnimationInProgress: false,

    duration:{
      // Durations in ms of animation elements
      highlight: 3000,
      scroll:500,
      wipe: 280,
      autoHide:5000
    },

    /**
     * Initialize the widget
     */
    initialize: function(){
      dojo.debug("Initializing CalculateOrderShipping widget...");

      // Load any initial data into the widget
      //if (this.data!==null){
        //this.setAllCartData(this.data);
      //}
      
      //atg.b2cblueprint.shipping.initSaturdayDelivery(this);
      
      //
      //  Hook up event handling
      var _this=this;
      dojo.event.connect(window, "onresize", this, "placeCart");
      dojo.event.connect(window, "onscroll", this, "placeCart");
      dojo.event.connect(document.body, "onclick", function(evt){
      // If body is clicked and cart is showing, hide it. Ignore clicks on links or submit buttons
      // as they'll be perfoming an action themselves.
        var type=evt.target.nodeName;
        if (_this.isShowing && type!="A" && type!="INPUT" && type!="BUTTON"){
          _this.hide();
        }
      });
      dojo.event.connect(this.domNode, "onclick", function(evt){
      // Prevent body from handling click within the cart
        evt.stopPropagation();
      });

      this.triggerWidget=dojo.widget.byId("richCalculateOrderShippingTrigger");
    },
    
    postCreate: function(){
      var _this=this;
      dojo.addOnLoad(function(){
        // Prepare for first show animation - hide the element's domNode and call the
        // hide animation. Set a callback to change the visibility when hide is complete.
        _this.domNode.style.visibility="hidden";
        _this.attachToContainer();
        _this.hide(function(){
          _this.domNode.style.visibility="visible";
        });
      });
    },
    
    /**
     * Set the 'Calculate shipping' popup to display all of the passed in data. This function will be
     * called when the  widget is initialised (i.e. on page load)
     */
    setAllCartData: function(pData){
      dojo.debug("Setting all Calculate Shipping data");
      dojo.debug(pData);
      this.data = pData;

//      if (pData.validForSaturdayDelivery == 'true') {
//        dojo.html.show(this.saturdayDelivery);
//      } else {
//        dojo.html.hide(this.saturdayDelivery);
//      } 
      
      
      if (pData.hasExceptionItem == 'true') {
        dojo.html.show(this.exceptionItemMessage);
      } else {
        dojo.html.hide(this.exceptionItemMessage);
      }
      
      
      this.groups.innerHTML = "";
      
      if (pData.shippingGroups){
        // Create ShippingGrpoupItem for each group and add to this parent widget       
        for (var i=0; i<pData.shippingGroups.length; i++){
          this.addShippingGroup(pData.shippingGroups[i]);
        }
      }
    },
    
    /**
     * //TODO: Add a line item to the rich cart
     */
    addShippingGroup: function(pShippingGroup){
      dojo.debug("Adding a Shipping Group");
      dojo.debug(pShippingGroup);
      
      
      var shippingGroupItem = dojo.widget.createWidget("atg.b2cblueprint:ShippingGroupItem", {
        data: pShippingGroup,
        i18n: this.i18n,
        highlightColor: this.highlightColor,
        highlightDuration: this.duration.highlight,
        scrollDuration: this.duration.scroll,
        showDelivery: (this.data.validForSaturdayDelivery == 'true')
      });
      
      //this.addChild(shippingGroupItem);
      this.groups.appendChild(shippingGroupItem.domNode);
    },   
    
        
    /**
     * Toggle display of the calculate shipping drill-down
     */
    toggleCalculateShipping: function(pEventCodeTracking){
      
      if (this.isShowing===true){
        this.hide();
      }
      else {
      
        //Added for google analytics  
        if(typeof(pageTracker) != 'undefined'){
          pageTracker._trackEvent('shipping', pEventCodeTracking);
        }

        
        dojo.io.bind({
        load: function(type, data, evt){
            var calculateShippingWidjet = dojo.widget.byId("calculateOrderShipping");
            calculateShippingWidjet.setAllCartData(data);
          },
          formNode: dojo.byId("calculateOrderShippingInitForm"),
          mimetype:'text/json'
        });
        
        dojo.io.bind({
          load: function(type, data, evt){
    
          var hiddenFields = dojo.byId("atg_mff_calculateOrderShippingHiddenFields");
          hiddenFields.innerHTML = data;
          
          },
          formNode: dojo.byId("calculateOrderShippingHiddenFieldsForm")
        });
        
        
        //atg.b2cblueprint.shipping.initSaturdayDelivery(this);
        // Clear shipping total
        this.calculateShippingTotal.innerHTML = "";
        dojo.lang.setTimeout(this, this.show, (300));
      }
    },
    
    
    
    /**
     * Position the cart at the correct location on screen
     */
    placeCart: function(){
    
      if (!this.isShowing && this.firstPlacementDone && !this.cartAnimationInProgress){
        return;
      }
      
      this.firstPlacementDone=true;
      
      var cartLeft,cartTop,cartHeight;
      cartHeight = 0;

      var richCart = dojo.widget.byId("richCart");

      if (richCart.isShowing == true ){
          cartHeight = richCart.domNode.clientHeight;
      }
      
      cartLeft = 321;
      cartTop = 135 + cartHeight;
      
      dojo.debug("Placing cart @ "+cartLeft+", "+cartTop);
                
      this.domNode.style.left=cartLeft+"px";
      this.domNode.style.top=cartTop+"px";
    },

    /**
     * Show the Rich Cart
     */
    show: function(callback) {
      if (this.isShowing){
        // If we've been passed a callback function, then call it even if we're showing. It's
        // most likely that a new item has been added, and the callback is the highlight
        if (callback){
          callback();
        }
        return;
      }
      
      if (this.cartAnimationInProgress===true){
        return;
      }
                
      this.cartAnimationInProgress=true;
      this.placeCart();
      var _this=this;
      var wipeAnimation=dojo.lfx.html.wipeIn(this.domNode, this.duration.wipe, dojo.lfx.easeOut, function(){
        _this.isShowing = true;
        _this.cartAnimationInProgress=false;
        
        // IE6 - prevent form elements from shining through cart with hidden bg iframe
        if(dojo.render.html.ie){
          if(!_this.bgIframe){
            _this.bgIframe = new dojo.html.BackgroundIframe();
            _this.bgIframe.setZIndex(_this.domNode);
          }
          _this.bgIframe.size(_this.domNode);
          _this.bgIframe.show();
        }

        if (callback && dojo.lang.isFunction(callback)){
          callback();
        }
        
      });
      var fadeAnimation=dojo.lfx.html.fade(this.domNode, { start:0.3, end: 1 }, this.duration.wipe, dojo.lfx.easeOut);    
      dojo.lfx.combine([wipeAnimation,fadeAnimation]).play();
    },

    /**
     * Hide the Rich Cart
     */
    hide: function(callback){
      if (this.cartAnimationInProgress===true){
        return;
      }
      
      this.cartAnimationInProgress=true;
      var _this=this;
      var wipeAnimation=dojo.lfx.html.wipeOut(this.domNode, this.duration.wipe, dojo.lfx.easeIn, function(){
        _this.isShowing = false;
        _this.cartAnimationInProgress=false;
        
        // IE6 - Prevent form element shine through - hide hidden iframe
        if(_this.bgIframe){
          _this.bgIframe.hide();
          _this.bgIframe.size({left:0, top:0, width:0, height:0});
        }
		
        if (callback && dojo.lang.isFunction(callback)){
          callback();
        }
      });
      var fadeAnimation=dojo.lfx.html.fade(this.domNode, { start:1, end: 0.8 }, this.duration.wipe); 
      dojo.lfx.combine([wipeAnimation,fadeAnimation]).play();      
      this.triggerWidget.updateTriggerDisplay();
      this.clearAutoHide();
    },
    
    /*
     * Get an array of all items that have been flagged as 'modified. This will
     * usually be just a single item - the item that has just been added to the cart.
     */
    getChangedItemWidgets: function(){
      var changedItems=[];
      var item;
      for (var i=0; i<this.data.items.length; i++){
        item=this.data.items[i];
        if (item.modified===true){
          // Get referene to child widget
          changedItems[changedItems.length] = this.children[i];     
        }
      }
      return changedItems;
    },

    /**
     * Start the auto-hide timer. This will close the rich cart after a short period of
     * time, unless the use mouses over the cart display, in which case the timer
     * will be cancelled so the user can continue to view the contents
     */
    startAutoHide: function(){      
      // Clear any existing auto-hide timer
      if (this.autoHideTimer!==null){
        this.clearAutoHide();
      }
      
      dojo.debug("Starting auto-hide (in "+this.duration.autoHide+" ms)");
      
      // Auto-hide the rich cart after n ms...
      this.autoHideTimer = dojo.lang.setTimeout(this, this.hide, (this.duration.autoHide));
      
      // ... unless the user mouses over the cart
      dojo.event.connect(this.domNode, "onmouseover", this, "clearAutoHide");
    },
      
    /**
     * Clear the auto-hide timer. This will stop the widget from auto-hiding. The user
     * must now click the 'hide rich cart' link/icon to hide the widget 
     */
    clearAutoHide: function(){
      dojo.debug("Clearing auto-hide");
      clearTimeout(this.autoHideTimer);
      dojo.event.disconnect(this.domNode, "onmouseover", this, "clearAutoHide");
      this.autoHideTimer=null;        
    },
    

    
    /**
     * Attach this widget's domNode to its containing node
     */
    attachToContainer: function(){
      dojo.debug("Appending cart domNode to body");
      document.body.appendChild(this.domNode);
    }
  }
);


