// ---------- mygear ----------
var mygear, mygear_initstate, rules_mygear_dynamic;

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}

function eraseCookie(name) {
  createCookie(name,"",-1);
}


var MyGear = Class.create();
MyGear.prototype = {
     initialize: function() {
          //console.info('mygear.initialize()');
          // mygear components
          // mygear bar
          this.outputBar = $('mygear_bar');
          this.outputBar.outputItems = $('mygear_bar_items');
          this.outputBar.outputTotal = $('mygear_bar_total');
          
          // mygear main
          this.outputMain = $('mygear_main');
          
          // config
          //this.url = 'ajax_mygear.php';
          this.url = '/site/ord/cart_ajax.html';
          
          // ajax expiry
          this.ajax_expire_track = $('ajax_expire_track');
          
          // graphics
          this.ajaxSpinner = $('ajaxSpinner');
          
          var rules_mygear = {
               '#button_mygear': function(el) {
                    el = $(el);

                    el.onclick = function(ev) {
                         mygear.toggle();
                    }
               },
               '#button_mygear_bottomclose': function(el) {
                    el = $(el);
                    el.onclick = function(ev) {
                         mygear.toggle();
                    }
               },
               '#mygear_view': function(el) {
                    el.onclick = function() {
                         mygear.view();
                    }
               },
               '#mygear_empty': function(el) {
                    el.onclick = function() {
                         mygear.empty();
                    }
               },
               '#mygear_error': function(el) {
                    el.onclick = function() {
                         mygear.view();
                    }
               }
          }
          
          Behaviour.applySheet(rules_mygear);
          
          // init state
          this.initState();
          
          // init main
          this.showing = false;
          if (this.outputMain.empty() || !mygear_initstate) {
               //console.info('no state found - loading...');
               // no default state, load mygear from server
               this.outputMain.innerHTML = 'loading...';
               
               // load mygear
               this.view();
               
               // update display
               this.update();
          } else {
               //console.info('state found! using it...');
               // load mygear state and rules embedded in served page
               this.loadState(mygear_initstate, rules_mygear_dynamic);
          }
     },
     initState: function() {
          //console.info('mygear.initState()');
          this.state = {
               mygear: new Array(),
               mygear_count: 0,
               saved: new Array(),
               saved_count: 0,
               total: '0.00'
          }
          
          this.rules = null;
          this.rulesSheetId = -1;
     },
     loadState: function(newstate, newrules) {
          //console.info('mygear.loadState()');
          // load new state and rules
          if (!newstate) {
               this.initState();
          } else {
               // clear old rules
               if (this.rulesSheetId>-1) {
                    Behaviour.clearSheetId(this.rulesSheetId);
               }
               
               // new state
               this.state = newstate;
               //console.info('new mygear_count='+this.state.mygear_count);
               
               // new rules
               this.rules = newrules;
               this.rulesSheetId = Behaviour.applySheet(this.rules);
          }
          
          // update display
          this.update();
     },
     toggle: function() {
          //console.info('mygear.toggle()');
          // toggle main view
          this.showing ? this.hide() : this.show();
     },
     show: function() {
          //console.info('mygear.show()');
          this.showing = true;
          $('button_mygear').addClassName('selected');

          this.outputMain.addClassName('show');
          // Element.hide(this.outputMain);
          // Effect.Appear(this.outputMain);
     },
     hide: function() {
          //console.info('mygear.hide()');
          this.showing = false;
          $('button_mygear').removeClassName('selected');
          // var foo = this;
          // Effect.Fade(this.outputMain, { afterFinish: function() { foo.outputMain.removeClassName('show');} });

          this.outputMain.removeClassName('show');
     },
     clear: function() {
          this.outputMain.innerHTML = '';
     },
     update: function() {
          //console.info('mygear.update()');
          // update mygear view
          // bar
          this.outputBar.outputItems.innerHTML = this.state.mygear_count;
          this.outputBar.outputTotal.innerHTML = this.state.total;
     },
     
     // ajax calls
     view: function() {
          if (Ajax.activeRequestCount==0) {
               // container/{success,failure}, url, options
               var parameters = {
                    mode: 'view'
               };
               var parameters_hash = $H(parameters);
               this.ajax_add = new Ajax.Updater(
                    {success: this.outputMain},
                    this.url,
                    {
                         method: 'get',
                         parameters: parameters_hash.toQueryString(),
                         evalScripts: true,
                         onSuccess: this.onSuccess.bind(this),
                         onFailure: this.onFailure.bind(this),
                         onException: this.onException.bind(this)
                    }
               );
          }
     },
     add: function(itemid) {
          if (Ajax.activeRequestCount==0) {
               // container/{success,failure}, url, options
               var parameters = {
                    mode: 'add',
                    itemid: itemid
               };
               var parameters_hash = $H(parameters);
               this.ajax_add = new Ajax.Updater(
                    {success: this.outputMain},
                    this.url,
                    {
                         method: 'get',
                         parameters: parameters_hash.toQueryString(),
                         evalScripts: true,
                         onSuccess: this.onSuccess.bind(this),
                         onFailure: this.onFailure.bind(this),
                         onException: this.onException.bind(this)
                    }
               );
          }
     },
     add_item: function(itemid) {
          var selected_style = Form.Element.getValue('style_selector');
          if (selected_style == '' || selected_style == 'Please Select') {
               alert('Please select a size and colour before adding to My Cart');
               return;
          }


          
          var serialized_form = Form.serialize('form_product');
                
          if (Ajax.activeRequestCount==0) {
               this.ajax_expire_track.value = '1';
               this.ajaxSpinner.style.display = '';
               createCookie("ajax_expire_track", 1, 1);

               // container/{success,failure}, url, options
               this.ajax_add = new Ajax.Updater(
                    {success: this.outputMain},
                    '/site/order',
                    {
                    method: 'post',
                        parameters: serialized_form,
                        evalScripts: true,
                        onSuccess: function () {
                             mygear.show();
                             this.onSuccess.bind(this);
                        },
                        onFailure: this.onFailure.bind(this),
                        onException: this.onException.bind(this)
                        }
               );
          }
     },
     remove: function(itemid) {
          if (Ajax.activeRequestCount==0) {
               this.ajax_expire_track.value = '1';
               this.ajaxSpinner.style.display = '';
               createCookie("ajax_expire_track", 1, 1);

               // container/{success,failure}, url, options
               var parameters = {
                    remove_item_index: itemid
               };
               var parameters_hash = $H(parameters);
               this.ajax_add = new Ajax.Updater(
                    {success: this.outputMain},
                    this.url,
                    {
                         method: 'get',
                         parameters: parameters_hash.toQueryString(),
                         evalScripts: true,
                         onSuccess: this.onSuccess.bind(this),
                         onFailure: this.onFailure.bind(this),
                         onException: this.onException.bind(this)
                    }
               );
          }
     },
     refresh: function(quiet) {
          if (Ajax.activeRequestCount==0) {
               this.ajax_expire_track.value = '1';
               this.ajaxSpinner.style.display = '';
               createCookie("ajax_expire_track", 1, 1);
               
               // container/{success,failure}, url, options
               var parameters = {
               };
               var parameters_hash = $H(parameters);
               this.ajax_add = new Ajax.Updater(
                    {success: this.outputMain},
                    this.url,
                    {
                         method: 'get',
                         parameters: parameters_hash.toQueryString(),
                         evalScripts: true,
                         onSuccess: function () { this.onSuccess.bind(this); if(!quiet) {mygear.show();} },
                         onFailure: this.onFailure.bind(this),
                         onException: this.onException.bind(this)
                    }
               );
          }
     },
     update_add: function(itemid) {
          if (Ajax.activeRequestCount==0) {
               this.ajax_expire_track.value = '1';
               this.ajaxSpinner.style.display = '';
               createCookie("ajax_expire_track", 1, 1);
               
               // container/{success,failure}, url, options
               var parameters = {
                    mode: 'update_add',
                    itemid: itemid
               };
               var parameters_hash = $H(parameters);
               this.ajax_add = new Ajax.Updater(
                    {success: this.outputMain},
                    this.url,
                    {
                         method: 'get',
                         parameters: parameters_hash.toQueryString(),
                         evalScripts: true,
                         onSuccess: this.onSuccess.bind(this),
                         onFailure: this.onFailure.bind(this),
                         onException: this.onException.bind(this)
                    }
               );
          }
     },
     update_sub: function(itemid) {
          if (Ajax.activeRequestCount==0) {
               // container/{success,failure}, url, options
               var parameters = {
                 remove_item_index: itemid
               };
               var parameters_hash = $H(parameters);
               this.ajax_add = new Ajax.Updater(
                    {success: this.outputMain},
                    this.url,
                    {
                         method: 'get',
                         parameters: parameters_hash.toQueryString(),
                         evalScripts: true,
                         onSuccess: this.onSuccess.bind(this),
                         onFailure: this.onFailure.bind(this),
                         onException: this.onException.bind(this)
                    }
               );
          }
     },
     saveforlater: function(itemid) {
          if (Ajax.activeRequestCount==0) {
               // container/{success,failure}, url, options
               this.ajax_expire_track.value = '1';
               this.ajaxSpinner.style.display = '';
               createCookie("ajax_expire_track", 1, 1);

               var parameters = {
                    save_for_later_index: itemid
               };
               var parameters_hash = $H(parameters);
               this.ajax_add = new Ajax.Updater(
                    {success: this.outputMain},
                    this.url,
                    {
                         method: 'get',
                         parameters: parameters_hash.toQueryString(),
                         evalScripts: true,
                         onSuccess: this.onSuccess.bind(this),
                         onFailure: this.onFailure.bind(this),
                         onException: this.onException.bind(this)
                    }
               );
          }
     },
     saveforlater_remove: function(itemid) {
          if (Ajax.activeRequestCount==0) {
               // container/{success,failure}, url, options
               this.ajax_expire_track.value = '1';
               this.ajaxSpinner.style.display = '';
               createCookie("ajax_expire_track", 1, 1);

               var parameters = {
                    save_for_later_remove_index: itemid
               };
               var parameters_hash = $H(parameters);
               this.ajax_add = new Ajax.Updater(
                    {success: this.outputMain},
                    this.url,
                    {
                         method: 'get',
                         parameters: parameters_hash.toQueryString(),
                         evalScripts: true,
                         onSuccess: this.onSuccess.bind(this),
                         onFailure: this.onFailure.bind(this),
                         onException: this.onException.bind(this)
                    }
               );
          }
     },
     saveforlater_movetocart: function(itemid) {
          if (Ajax.activeRequestCount==0) {
               // container/{success,failure}, url, options
               this.ajax_expire_track.value = '1';
               this.ajaxSpinner.style.display = '';
               createCookie("ajax_expire_track", 1, 1);

               var parameters = {
                    save_for_later_move_to_cart_index: itemid
               };
               var parameters_hash = $H(parameters);
               this.ajax_add = new Ajax.Updater(
                    {success: this.outputMain},
                    this.url,
                    {
                         method: 'get',
                         parameters: parameters_hash.toQueryString(),
                         evalScripts: true,
                         onSuccess: this.onSuccess.bind(this),
                         onFailure: this.onFailure.bind(this),
                         onException: this.onException.bind(this)
                    }
               );
          }
     },
     movetocart: function(itemid) {
          if (Ajax.activeRequestCount==0) {
               // container/{success,failure}, url, options
               var parameters = {
                    mode: 'movetocart',
                    itemid: itemid
               };
               var parameters_hash = $H(parameters);
               this.ajax_add = new Ajax.Updater(
                    {success: this.outputMain},
                    this.url,
                    {
                         method: 'get',
                         parameters: parameters_hash.toQueryString(),
                         evalScripts: true,
                         onSuccess: this.onSuccess.bind(this),
                         onFailure: this.onFailure.bind(this),
                         onException: this.onException.bind(this)
                    }
               );
          }
     },
     removesaved: function(itemid) {
          if (Ajax.activeRequestCount==0) {
               // container/{success,failure}, url, options
               var parameters = {
                    mode: 'removesaved',
                    itemid: itemid
               };
               var parameters_hash = $H(parameters);
               this.ajax_add = new Ajax.Updater(
                    {success: this.outputMain},
                    this.url,
                    {
                         method: 'get',
                         parameters: parameters_hash.toQueryString(),
                         evalScripts: true,
                         onSuccess: this.onSuccess.bind(this),
                         onFailure: this.onFailure.bind(this),
                         onException: this.onException.bind(this)
                    }
               );
          }
     },
     empty: function() {
          if (Ajax.activeRequestCount==0) {
               // container/{success,failure}, url, options
               var parameters = {
                 empty_cart: 1
               };
               var parameters_hash = $H(parameters);
               this.ajax_add = new Ajax.Updater(
                    {success: this.outputMain},
                    this.url,
                    {
                         method: 'get',
                         parameters: parameters_hash.toQueryString(),
                         evalScripts: true,
                         onSuccess: this.onSuccess.bind(this),
                         onFailure: this.onFailure.bind(this),
                         onException: this.onException.bind(this)
                    }
               );
          }
     },
     onSuccess: function() {
          //console.info('onSuccess() '+mygear_initstate.mygear_count);
          //this.loadState();
     },
     onFailure: function(xhr_obj, json_obj) {
          //console.info('ajax failed: '+($H(this).inspect()));
          this.outputMain.innerHTML = '<div class="error">Sorry, there was an error - <span id="mygear_error">click here to reload</span></div>';
     },
     onException: function (ajax_request, e) {
          //console.info('ajax exception: '+($H(this).inspect()));
          this.outputMain.innerHTML = '<div class="error">Sorry, there was an error - <span id="mygear_error">click here to reload</span></div>';
     }
}


// ---------- init mygear ----------
function initMyGear() {
     //console.info('initMyGear()');
     mygear = new MyGear();

     // handle back
     if (mygear.ajax_expire_track.value == 1 || readCookie('ajax_expire_track') == '1') {
          mygear.refresh(1);
          mygear.ajax_expire_track.value = 0;
          eraseCookie('ajax_expire_track');
     }
}
