// Place your application-specific JavaScript functions and classes here
// This file is automatically included by javascript_include_tag :defaults

// AUTO HIDE
var AutoHide = Class.create({
  initialize: function(element) {
    this.element = element;
    this.transition = 1;
    this.element.hide()
    this.enhancedShow(this);
    this.enhancedHide.delay(3,this);
  },
  enhancedHide: function(object) {
     new Effect.BlindUp(object.element, {
        duration: object.transition
     });
  },
  enhancedShow: function(object) {
    new Effect.BlindDown(object.element, {
       duration: object.transition
    });
  }
});

// Extending all elements to support special interactive functionality.
function checkForAutoHide(e){ 
   if($('notice')) { new AutoHide($('notice')); }
   if($('warning')) { new AutoHide($('warning')); }
}

Event.observe(window, 'load', checkForAutoHide);


// DRAWER OBJECT
var Drawer = Class.create({
  initialize: function(element) {
    this.element = element;
    this.contents = $('drawer_content');
    this.handle = $('drawer_handle');
    this.duration = 1;
    this.jar = new CookieJar({
       expires:3600,// seconds
       path: '/'
    });
    if(this.jar.get('status')) {
       if(!this.jar.get('status').open) {
          this.contents.hide();
          this.handle.addClassName('open');
          this.handle.removeClassName('close');
          this.handle.observe('click', this.openDrawer.bindAsEventListener(this));
       } else {
          this.handle.observe('click', this.closeDrawer.bindAsEventListener(this));
       }
    } else {
       this.setOpenStatus(true);
       this.handle.observe('click', this.closeDrawer.bindAsEventListener(this));
    }
  },
  closeDrawer: function(e) {
     e.stop();
     new Effect.BlindUp(this.contents, {
        duration: this.duration
     });
     //this.handle.innerHTML = 'Open Drawer';
     this.handle.addClassName('open');
     this.handle.removeClassName('close');
     this.handle.stopObserving('click');
     this.handle.observe('click', this.openDrawer.bindAsEventListener(this));
     this.setOpenStatus(false);
  },
  openDrawer: function(e) {
     e.stop();
    new Effect.BlindDown(this.contents, {
       duration: this.duration
    });
    // this.handle.innerHTML = 'Close Drawer';
    this.handle.addClassName('close');
    this.handle.removeClassName('open');
    this.handle.stopObserving('click');
    this.handle.observe('click', this.closeDrawer.bindAsEventListener(this));
    this.setOpenStatus(true);
  },
  setOpenStatus: function(s) {
     var status = {open: s};
     this.jar.put('status', status);
  }
});

// Extending all elements to support special interactive functionality.
function setupDrawer(e){ 
   if($('drawer_content')) { new Drawer($('backend_drawer')); }
}

Event.observe(window, 'load', setupDrawer);

// DRAGGABLE_ITEM
var DraggableItem = Class.create({
  initialize: function(element) {
    this.element = element;
    this.element.insert('<span class="handle"></span>', 'bottom');
    this.slack = 0.5;
    this.handle = this.element.down('.handle');
    Event.observe(this.element, 'mouseover', this.showHandleListener.bindAsEventListener(this));
    Event.observe(this.element, 'mouseout', this.hideHandleListener.bindAsEventListener(this));
  },
  showHandleListener: function(e) {
     window.clearTimeout(this.activation_request);
     if(!this.element.hasClassName('showHandle')){
        this.activation_request = this.enabler.delay(this.slack,this);
     }  
  },
  enabler: function(source) {
     source.element.addClassName('showHandle');
  },
  hideHandleListener: function(e) {
     if(!this.element.hasClassName('showHandle')){
        window.clearTimeout(this.activation_request);
     } else {
        this.activation_request = this.disabler.delay(this.slack,this);
     }
  },
  disabler: function(source) {
     source.element.removeClassName('showHandle');
  }
});

// DRAGGABLE_GROUP
var DraggableGroup = Class.create({
   initialize: function(element) {
      this.element = element;
      this.sections = [];
      this.sortables = [];
      this.drawers = $$('.drawer_list');
      $('backend_drawer').insert('<div id="updater"><span>One moment as we save your changes...</span></div>', 'bottom');
      this.updater = $('updater');
      this.updater.hide();
      // Adding the listener behavior to show the move tool on roll over.
      $$('.drawer_list li').each( function(list_item) {
         new DraggableItem(list_item);
      });
      
      if(this.element.hasClassName('resortable_sections')) {
         $$('.drawer_list h2').each( function(list_item) {
            new DraggableItem(list_item);
         });
         Sortable.create( this.element.id, { 
            tag:'ul',
            handle:'handle',
            hoverclass:'dragged',
            onChange: this.setToDraggable.bind(this),
            onUpdate: this.sendSections.bind(this)
         });
      }
      // Building a list of section ids dynamically.  Is there an easier way to do this?
      this.drawers.each( function(list) { 
         this.sections[this.sections.length] = list.id
      }.bind(this));
      
      // Setting up each list item to be sortable now that we've built the list of sections for our containment rule.
      this.drawers.each( function(list) {
         this.sortables[this.sortables.length] = Sortable.create( list.id, { 
            tag:'li',
            handle:'handle',
            containment:this.sections,
            dropOnEmpty:true,
            hoverclass:'dragged',
            onChange: this.setToDraggable.bind(this),
            onUpdate: this.sendData.bind(this)
         });
      }.bind(this));
   },
   
   setToDraggable: function() {
      if(!this.element.hasClassName('dragged')) {
         this.element.addClassName('dragged');
      }
      window.clearTimeout(this.activation_request);
      this.activation_request = this.resetDraggable.delay(1,this);
   },
   
   resetDraggable: function(source) {
      if(source.element.hasClassName('dragged')) {
         source.element.removeClassName('dragged');
         window.clearTimeout(this.activation_request);
      }
   },
   
   sendData: function() {
      var params = {authenticity_token: window._token, 'resort[]': this.sections};
      this.drawers.each(function(section) {
         var order = Sortable.serialize(section.id); //hash - json
         params[section.id] = order;
      });
      this.handleRequest(params);
   },
   
   sendSections: function() {
      var params = {authenticity_token: window._token, resort: Sortable.serialize(this.element)};
      this.handleRequest(params,true);
   },
   
   handleRequest: function(params,sectionDataOnly) {
      if(!sectionDataOnly){
         path = window._controller_name
      } else {
         path = window._controller_name+'/section/new'
      }
      // We're inserting a notification div onto the page incase it doesn't exist.
      if(!$('notice')) { $('backend_nav').insert('<div id="notice"><div class="container"><p></p></div></div>', { position: 'after' }); }
      
      // We're checking for an existing request to prevent double requests from being sent when
      // we move objects to two different groups.  Each group will dispatch this method.
      if(!this.request) {
         this.updater.appear({ duration: 0.1 });
         this.request = new Ajax.Request('/'+path, {
           method: 'get',
           parameters: params,
           onSuccess: this.handleResponse.bind(this)
         });
      }
   },
   
   handleResponse: function(transport) {
      this.request = null;
      $('notice').down().down().innerHTML = 'Re-ordering has been successfully updated!';
      new AutoHide($('notice'));
      this.updater.fade({ duration: 1, delay: 0.25 });
      this.element.removeClassName('updating');
   }
});

// Extending all elements to support special interactive functionality.
function setupDraggableItems(e){ 
   if($$('.drawer_list li')) { 
      if($('drawer_content')) { new DraggableGroup($('drawer_content')); }
   }
}

Event.observe(window, 'load', setupDraggableItems);



// DRAWER OBJECT
var Accordion = Class.create({
  initialize: function(element) {
     this.element = element;
     this.contents = this.element.next();
     this.contents.hide();
     this.duration = 0.5;
     this.element.observe('click', this.toggleContent.bindAsEventListener(this));
  },
  toggleContent: function(e) {
     e.stop();
     if(this.contents.visible()) {
        new Effect.BlindUp(this.contents, {
           duration: this.duration
        });
        new Effect.Morph(this.element, {
           style: 'background:#f0f0f0; color: #000;',
           duration: this.duration
         });
     } else {
        new Effect.BlindDown(this.contents, {
          duration: this.duration
        });
       new Effect.Morph(this.element, {
           style: 'background:#7D4199; color: #fff;',
           duration: this.duration
         });
     }
  }
});

function loadAccordions(e) {
   $$('.accordion_toggle').each(function(toggle_item){
      new Accordion(toggle_item);
   });
}

Event.observe(window, 'load', loadAccordions, false);

function makeNumber(num) {
   return new Number(num.replace('px',''));
}

function calculateHeight(e) {
   var offset = makeNumber($('primary_navigation').getStyle('top'));
   var diff = makeNumber($('primary_content').getStyle('paddingTop')) - offset;
   if($('primary_content').getHeight() < ($('primary_navigation').getHeight()+offset)) {
     var targetHeight = ($('primary_navigation').getHeight()-diff+20)+"px";
     $('primary_content').setStyle({height: targetHeight, minHeight: targetHeight});
   }
   
   var max = 0;
   $('inline_sitemap').childElements().each(function(el) {
       if(el.getHeight() > max) { max = el.getHeight(); }
   }.bind(max));

   $('inline_sitemap').setStyle({height:max+"px"});
}

Event.observe(window, 'load', calculateHeight, false);


function addOrderFormListeners(e) {
   if($('order_same_as_billing')) {
      $$('.billing').each(function(el){
         el.observe('keyup', function(){
            matchForms();
         }); 
      });
      matchForms();
      togglePaymentFieldsets();
      
      $('order_product_id').observe('change', function() {
         togglePaymentFieldsets();
      });
      
      $('order_same_as_billing').observe('click', function(){
         matchForms();
      });
   }
}

function togglePaymentFieldsets(){
   if($F('order_product_id') == 'invoice') {
      $('invoice_fields').show();
      $('product_fields').hide();
   } else {
      $('product_fields').show();
      $('invoice_fields').hide();
   }
   if($F('order_product_id') == '') {
      $('product_fields').hide();
   }
}

function matchForms() {
   if($('order_same_as_billing').checked){
      $('order_shipping_state').disable();
      $('order_city').disable();
      $('order_address_1').disable();
      $('order_address_2').disable();
      $('order_first_name').disable();
      $('order_last_name').disable();
      $('order_zip').disable();
      $('order_shipping_state').value = $F('order_billing_state');
      $('order_city').value = $F('order_billing_city');
      $('order_address_1').value = $F('order_billing_address_1');
      $('order_address_2').value = $F('order_billing_address_2');
      $('order_first_name').value = $F('order_billing_first_name');
      $('order_last_name').value = $F('order_billing_last_name');
      $('order_zip').value = $F('order_billing_zip');
   } else {
      $('order_shipping_state').enable();
      $('order_city').enable();
      $('order_address_1').enable();
      $('order_address_2').enable();
      $('order_first_name').enable();
      $('order_last_name').enable();
      $('order_zip').enable();
   }
}

Event.observe(window, 'load', addOrderFormListeners, false);