/* -----------------------------------------------------------
/* ------------------------- The Controler ----------------------
*/
/* -----------------------------------------------------------
/* ------------------------- Main Initializer ---------------------
*/
function Ready_up(type){
  var self = this;
  this.root = $('#container');
  this.loaderChoose = function() {		
    self.jaxChoose();

    if (self.root.find('.page_tools').length > 0)
      new Page_tools(self.root.find('.page_tools'));
      
    if (self.root.find('#content').hasClass('home'))
      new Home_page(self.root.find('#content'));

    if (self.root.find('#checkout'))
      new Checkout_plus(self.root.find('#checkout'));
    
    this.product_div = self.root.find("#content.product");
    if (this.product_div.hasClass('detail') && !this.product_div.hasClass('noJax')) {
      new Product_detail(this.product_div);
    }
    new Navi(self.root.find('#header .navi.main'));
    new Window_fixer(self.root);
    new Main_Vehicle_chooser(self.root.find('.vehicle_chooser'));
    
    if (self.root.find('.map_chose').length > 0)
      new Map_choose(self.root.find('.map_chose'));
      
    if (self.root.find('#emailer').length > 0)
      new Emailer(self.root.find('#emailer'));

    if (self.root.find('#content').hasClass('upsells')) {
      for (var i = 0; i < self.root.find('.legend_of').length; i++) {
        new Three_columns(self.root.find('.legend_of').eq(i));
      }
    }
    
    new Three_columns(self.root.find('#footer .boiler_content'));

    for (var i = 0; i < self.root.find('.callout').length; i++) {
      new Callout_helper(self.root.find('.callout').eq(i));
    }
    
    if (self.root.find('#content #their_form').length > 0) {
      new Swich_forms(self.root.find('#content #their_form'));
    }

  }
  this.jaxChoose = function() {	
    External_link.init("class","external_link", "");
    
    if(self.root.find('.expand').length > 0)
      new Expandable(self.root.find('.expand'), 0);
    
    if(self.root.find('table.styled').length > 0)
      new Table_styled(self.root.find('table.styled'));
      
    if(self.root.find('table.striped').length > 0)
      new Table_styled(self.root.find('table.striped'));
      
    if(self.root.find('.framed').length > 0)
      new Framer(self.root.find('.framed'));
    
    if(self.root.find('.timeline').length > 0)
      new Timeline(self.root.find('.timeline'));
    
    for (var i = 0; i < this.root.find('blockquote').length; i++)
      this.root.find('blockquote').eq(i).html('<p>' + this.root.find('blockquote').eq(i).html() + '</p>');
  }
  
  if (type === 'load') 
    this.loaderChoose();
  else 
    this.jaxChoose();
}

function Swich_forms(element) {
  var self = this;
  this.root = element;
  this.inner_inputs = this.root.find('input');
  this.inner_inputs.each(function() {
    if (!$(this).is('input[type="checkbox"], input[type="radio"], input[type="submit"]') && $(this).prev().is('br')) {
      $(this).prev().remove();
    }
    switch (this.id) {
      case 'VehicleMake':
        this.value = (self.root.find('#Vehicle_Make').html());
        this.type = "hidden";
        $(this).prev('label').prev('br').andSelf().remove();
        break;
      case 'VehicleModel':
        this.value = (self.root.find('#Vehicle_Model').html());
        this.type = "hidden";
        $(this).prev('label').prev('br').andSelf().remove();
        break;
      case 'VehicleYear':
        this.value = (self.root.find('#Vehicle_Year').html());
        this.type = "hidden";
        $(this).prev('label').prev('br').andSelf().remove();
        break;
      case 'VehicleEngine':
        this.value = (self.root.find('#Vehicle_Engine').html());
        this.type = "hidden";
        $(this).prev('label').prev('br').andSelf().remove();
        break;
      }
  });
}

function Callout_helper(element) {
  var self = this;
  this.root = element;
  this.root.hover(function(e) {
    var me = $(this);
    me.addClass('over');
    if (me.parent().hasClass('side_callouts')) {
      me.animate({
        opacity: .7
      }, {duration: 450, 
        easing: "easeOutQuad",
        queue: false
      });
    } else {
      me.find('h4').animate({
        color: '#d81e2d'
      }, {duration: 450, 
        easing: "easeOutQuad",
        queue: false
      });

    }
  }, function(e) {
    var me = $(this);
    me.removeClass('over');
    if (me.parent().hasClass('side_callouts')) {
      me.animate({
        opacity: 1
      }, {duration: 450, 
        easing: "easeOutQuad",
        queue: false
      });
    } else {
      me.find('h4').animate({
        color: '#fff'
      }, {duration: 450, 
        easing: "easeOutQuad",
        queue: false
      });
    }
  });
}

function Map_choose(element) {
  var self = this;
  this.root = element;
  this.root.children('.head').children('h6:last').toggle(function() {
    $(this).html('Hide Map');
    self.root.animate({
      width: '30%'
    }, {duration: 450, 
      easing: "easeOutQuad",
      queue: false
    });
  }, function() {
    $(this).html('Show Map');
    self.root.animate({
      width: '100%'
    }, {duration: 450, 
      easing: "easeOutQuad",
      queue: false
    });
  });
  this.root.children('.head').children('h6:last').click();
}
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/
function Checkout_plus(element) {
  var self = this;
  this.root = element;
  if (this.root.find('.checkout-progress-indicator').length > 0) {
    new Checkout_nav(this.root.find('.checkout-progress-indicator'));
  }
  for (var i = 0; i < this.root.find('.snippet_dialog').length; i++) {
    new Snippet_dialog(this.root.find('.snippet_dialog').eq(i));
  }
}
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/
function Three_columns(element) {
  var self = this;
  this.root = element.children('div, form, fieldset');
  for (var i = 0; i < this.root.length; i++) {
    if (i % 3 == 0) {
      this.root.eq(i).addClass('first');
    }
  }
}
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/
function Snippet_dialog(element) {
	var self = this;
	this.root = element;
	this.dialogizer = function(e) {
		self.root.unbind('click', self.dialogizer);
		e.preventDefault();
		$('#jax_content').append('<div id="new_box"> </div>');
		$('#new_box').load($(this).attr('href')).addClass('dialogized').dialog({
			modal: true,
			overlay: {
				backgroundColor: "#d9d1b6",
				 opacity: '.8'
			 },
			dialogClass: 'deskman',
			height: 700,
			width: 500,
			close: function()  {
				self.root.bind('click', self.dialogizer);
				$(this).dialog('destory').remove();
			}
		});
	}
	this.root.bind('click', this.dialogizer);
}

function Checkout_nav(element) {
  var self = this;
  this.root = element;
  this.clickers = this.root.children('.before');
  this.clickers.click(function() {
    document.location = $(this).find('a').attr('href')
  });
}
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/
function Table_styled(element) {
  var self = this;
  this.root = element;
  this.table_rows = this.root.find('tbody tr');
  for (var i = 0; i < this.table_rows.length; i++) {
    if (i % 2 == 0) {
      this.table_rows.eq(i).addClass('alt');
    }
  }
  new Table_tip(this.root);
}
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/
function Table_tip(element) {
  var self = this;
  this.root = element;
  
  this.img = $('tbody th img', self.root);
  for (var i = 0; i < this.img.length; i++) {
    this.img.eq(i).data('tip', this.img.eq(i).parent().next().addClass('toolTip'));
    this.img.eq(i).css({left : this.img.eq(i).position().left + 3});
  }
  this.toolTip = $('.toolTip', self.root);
  this.img.bind('mouseover', function(e) {
    self.toolTip.fadeOut(0);
    $(this).data('tip').fadeIn('fast');
  });
  this.toolTip.bind('mouseout', function() {
    $(this).fadeOut('fast');
  });
  this.root.bind('mouseleave', function() {
    self.toolTip.fadeOut('fast');
  });
}
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/
function Tabber(element) {
  var self = this;
  this.root = element;
  
  this.tabs = this.root.children('ul').children();
  this.tab_content = this.root.children().not('ul');
  for (var i = 0; i < this.tabs.length; i++) {
    this.tabs.eq(i).data('cont', this.tab_content.eq(i));
  }
  
  this.show_tab_content = function(e) {
    self.tab_content.hide();
    $(this).siblings().removeClass('active');
    $(this).addClass('active').data('cont').show();
  }
  
  this.tabs.bind('click', this.show_tab_content);
  this.tabs.eq(0).click();
}
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/
function Social_expander(element) {
  var self = this;
  this.root = element;
  
  this.socials = this.root.children('ul').css('height', 'auto');
  this.ego = this.socials.height();
  this.socials.css('height', '0');
  this.root.children('h6').append('<em> click to share </em>');
  
  this.root.children('h6').toggle(function() {
    self.socials.animate({
      height: self.ego
    }, {duration: 350, 
      easing: "easeOutQuad",
      queue: false
    })
    self.socials.animate({
      opacity: 1
    }, {duration: 250, 
      easing: "easeOutQuad",
      queue: false,
      complete: function() {
        self.socials.css({opacity: ''});
      }
    });
  }, function() {
    self.socials.animate({
      height: 0,
      opacity: 0
    }, {duration: 350, 
      easing: "easeOutQuad",
      queue: false
    });
  });
}
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/
function Product_detail(element) {
  var self = this;
  this.root = element;
  
  if (this.root.find('.product-tabs').length > 0) {
    new Tabber(this.root.find('.product-tabs'));
  }
  
  if (this.root.find('.socials').length > 0) {
    new Social_expander(this.root.find('.socials'));
  }
  new Carousel(this.root.find('.column.left.liberal'), 7, false);
  
  this.available_parts = null;
  this.parts_chooser_box = null;
  this.current_selected_part = 0;
  this.give_price = function(e) {
    var me = $(this).children().eq(e.currentTarget.selectedIndex);
    this.current_price = me.data('price');
    self.current_selected_part = me.html();
    for (var i = 0; i < self.available_parts.length; i++) {
      var temp = me.html().toString().replace('&amp;', '&');
      console.log(self.available_parts[i].vehicle_part_assignment.description,  me.html().toString(), Number(self.available_parts[i].vehicle_part_assignment.id), Number(me.val()));
      if (self.available_parts[i].vehicle_part_assignment.description == temp && Number(self.available_parts[i].vehicle_part_assignment.id) != Number(me.val())) {
        this.other_price = self.available_parts[i].vehicle_part_assignment.price;
        break;
      }
    }
    this.other_price = this.other_price.toFixed(2);
    this.current_price = this.current_price.toFixed(2);
    if (Number(this.current_price) > Number(this.other_price)) {
      self.parts_chooser_box.find('input[name="flux"]').eq(0).next().children('strong').html('Total Price: $' + this.current_price + ' USD');
      self.parts_chooser_box.find('input[name="flux"]').eq(1).next().children('strong').html('Total Price: $' + this.other_price + ' USD');
    } else {
      self.parts_chooser_box.find('input[name="flux"]').eq(0).next().children('strong').html('Total Price: $' + this.other_price + ' USD');
      self.parts_chooser_box.find('input[name="flux"]').eq(1).next().children('strong').html('Total Price: $' + this.current_price + ' USD');
    }
  }
  this.choose_part = function(e) {
    self.parts_chooser_box.find('fieldset.dynamo:last').html('<label> Vehicle Modifications <span class="required" > * </span> </label><select name="vehicle_part_assignment_id"></select>');
    var temp_select = self.parts_chooser_box.find('fieldset').children('select:last');
    temp_select.append('<option value="">-- select --</option>');
    for (var i = 0; i < self.available_parts.length; i++) {
      if (self.available_parts[i].vehicle_part_assignment.flux.toString() == e.target.value.toString()) {
        temp_select.append('<option value="' + self.available_parts[i].vehicle_part_assignment.id + '">' + self.available_parts[i].vehicle_part_assignment.description + '</option>');
        temp_select.children(':last').data('price', self.available_parts[i].vehicle_part_assignment.price);
        if (self.available_parts[i].vehicle_part_assignment.description == self.current_selected_part) {
          self.current_selected_part = temp_select.children().length - 1;
        }
      }
    }
    if (typeof(self.current_selected_part) != 'number') {
      self.current_selected_part = 0;
    }
    temp_select.bind('change', self.give_price);
    if (self.current_selected_part != 0) {
      temp_select.attr('selectedIndex', self.current_selected_part);
    }
  }
  this.parts_setup = function(json, textStatus) {
    self.available_parts = json;
    var flux_yes = false;
    var flux_no = false;
    for (var i = 0; i < self.available_parts.length; i++) {
      if (self.available_parts[i].vehicle_part_assignment.flux == true) {
        flux_yes = true ;
      } else if (self.available_parts[i].vehicle_part_assignment.flux == false) {
        flux_no = true;
      }
    }
    self.parts_chooser_box = $('#jax_content').children('.part_choose').show();
    self.parts_chooser_box.dialog({
      height: 600,
      width: 550,
      title: "Flux and Tell Us About Your Vehicle",
      modal: true,
      buttons: {
        "Cancel": function() {
          $(this).dialog("close");
        },
        "Continue To Cart": function() {
          if($("[name=vehicle_part_assignment_id]").val() != "") {
            $(this).submit();
          }
        }
      },
      close: function() {
        $(this).dialog("destroy").remove();
      }
    });
    if (flux_yes != flux_no) {
      if (!flux_yes) {
        self.parts_chooser_box.children('fieldset').eq(0).html('<input type="hidden" name="flux" value="false" />');
      } else if (!flux_no) {
        self.parts_chooser_box.children('fieldset').eq(0).html('<input type="hidden" name="flux" value="true" />');
      }
      self.parts_chooser_box.find('h3').eq(0).remove();
      self.parts_chooser_box.find('input[name="flux"]').bind('click', self.choose_part);
      self.parts_chooser_box.find('input[name="flux"]').trigger('click');
    } else {
      self.parts_chooser_box.find('input[name="flux"]').bind('click', self.choose_part);
      self.parts_chooser_box.find('input[name="flux"]').eq(1).attr('checked', 'true').trigger('click');
    }
  }
  this.submit_form = function(e) {
    e.preventDefault();
    $.ajax({
      url: window.location + "/choose_part",
      type: 'get',
      success: function(html) {
        var jax = $('#jax_content').append(html).hide();
        var vid = jax.find("#vehicle_id").val();
        $.ajax({
          url: "/vehicle/parts.json?vehicle_id=" + vid, 
          dataType: 'json',
          success: self.parts_setup
        });
      }
    });
  }
  this.root.find('form').bind('submit', this.submit_form);
}
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/
function Framer(element) {
  for (var i = 0; i < element.length; i++) {
    element.eq(i).wrap('<span class="frame"></span>');
    if (element.eq(i).hasClass('right')) {
      element.eq(i).removeClass('right').parent().addClass('right');
    } else if (element.eq(i).hasClass('left')) {
      element.eq(i).removeClass('left').parent().addClass('left');
    }
  }
}
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/
function Slider(element, file_paths) {
  var self = this;
  this.root = element;
  this.slide_left = this.root.offset().left;
  this.slide_right = this.root.offset().left + this.root.outerWidth();
  this.root_width = this.root.outerWidth(true);
  this.slide_offset = 0;
  this.items = this.root.children().children();
  this.speed = this.items.eq(0).outerWidth(true) / 2;
  this.centered = true;
  this.home_local = 0;
  this.direction = 1;
  this.silde_amount = 4;
  this.number_visible = 8;
  
  this.root.wrap('<div class="smart_button" style="width:100%;"></div>');
  this.smart_button = self.root.parent();
  this.smart_button.data('iter', -1);
  
  this.content_reload = function() {
    self.items = self.root.children().children();
    for (var i = 0; i < self.items.length; i++) {
      self.first_visible = self.items.eq(0);
      self.items.eq(i).data('iter', i);
      self.items.eq(i).data('lefter', i * -self.items.eq(i).outerWidth(true));
    }
  }  
  
  this.pre_load = function() {
    var iter = self.active.data('iter');
    for (var i = iter; i < iter + self.slide_amount; i++) {
      
    }
  }

  this.set_current = function(current) {
    if (current.data('iter') == undefined) {
      self.set_current(current.parent());
    } else if (current.data('iter') < self.silde_amount && self.direction > 0) {
      self.first_visible = self.items.eq(0);
    } else if (current.data('iter') > self.items.length - self.number_visible && self.direction < 0) {
      self.first_visible = self.items.eq(self.items.length - self.number_visible);
    } else {
      self.first_visible = self.items.eq(current.data('iter') - (self.silde_amount * self.direction));
    }
  }

  this.move_on = function(e) {
    var me = $(e.target);
    if (e.target != e.currentTarget) {
      self.set_current(me);
    } else {
      self.set_current(self.first_visible);
    }
    self.big_move();
  }
  
  this.big_move = function() {
    self.root.children().animate({
      left: self.first_visible.data('lefter')
    }, {duration: 350, 
      easing: "easeOutQuad",
      queue: false
    });
  }

  this.back_home = function() {
    if (self.centered) {
      return;
    }
    self.smart_button.removeClass('left');
    self.smart_button.removeClass('right');
    self.big_move();
    self.centered = true;
  }
  this.little_move = function() {
    self.root.children().animate({
      left: self.first_visible.data('lefter') + (self.speed * self.direction)
    }, {duration: 350, 
      easing: "easeOutQuad",
      queue: false
    });
    self.centered = false;
  }
  this.half_way_hover = function(e) {
    if (e.pageX <= (self.slide_left + self.slide_offset) && !self.smart_button.hasClass('left')) {
      self.smart_button.removeClass('right');
      self.smart_button.addClass('left');
      self.direction = 1;
      self.little_move();
    } else if (e.pageX >= (self.slide_right - self.slide_offset) && !self.smart_button.hasClass('right')) {
      self.smart_button.removeClass('left');
      self.smart_button.addClass('right');
      self.direction = -1;
      self.little_move();
    } else if ((e.pageX < self.slide_right - self.speed - self.slide_offset) && (e.pageX > self.slide_left + self.speed + self.slide_offset) && !self.centered) {
      self.direction = 1;
      self.back_home();
    }
  }
  this.content_reload();
  this.smart_button.bind('mouseleave', this.back_home);
  this.smart_button.bind('mousemove', this.half_way_hover);
  this.smart_button.bind('click', this.move_on);
}
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/
function Vehicle_chooser(element) {
  var self = this;
  this.root = element;
  this.chooser = this.root.children('.chooser');
  
  this.run_through = function() {
    for (var iter = 0; iter < this.json.length; iter++) {
      this.single_display(iter);
    }
  }
  
  this.wrap_up_proper = function(wrapper) {
    if (!self.chooser.find('.' + this.kind).html()) {
      self.chooser.append('<div class="' + this.kind + ' outer">' + wrapper + '</div>');
      this.temp_wrap = self.chooser.children('.' + this.kind).children('.wrap');
    } else {
      this.temp_wrap.html('');
    }
    self.run_through.call(this);
    if (this.slideon) {
      this.slideon.content_reload();
    } else if (self.slide_side) {
      this.slideon = new Slider(this.temp_wrap.parent());
    }
  }
  
  this.chooser_linkup = {
    brand : {
      kind: 'brand',
      name: 'brand_id', 
      json_name: 'id',
      value: null,
      json: null,
      file_path: function(name) {
        return '/images/vehicle/brands/' + name + '.png'
      },
      state: 1,
      url: function() {
        return '/vehicle/brands.json'
      },
      single_display: function(i) {
        this.temp_wrap.append('<li><img src="' + this.json[i].vehicle_brand.logo + '" alt="' + this.json[i].vehicle_brand.name + '" /><h6>' + this.json[i].vehicle_brand.name + '</h6></li>');
        this.temp_wrap.children(':last').data(this.json_name, this.json[i].vehicle_brand[this.json_name]);
        this.temp_wrap.children(':last').data('state', this.state);
        this.temp_wrap.children(':last').bind('click', self.choose);
        this.file_paths[i] = '/images/vehicle/brands/' + this.json[i].vehicle_brand.name + '.png'
      },
      display: function() {
        this.file_paths = new Array();
        self.wrap_up_proper.call(this, '<ul class="wrap"></ul>');
      }
    },
    year : {
      kind: 'year',
      name: 'year', 
      json_name: 'years',
      value: null,
      json: null,
      state: 2,
      url: function() {
        return '/vehicle/brands/' + self.chooser_linkup.brand.value
      },
      single_display: function(i) {
        this.temp_wrap.append('<li>' + this.json.years[i] + '</li>');
        this.temp_wrap.children(':last').data(this.json_name, this.json.years[i]);
        this.temp_wrap.children(':last').data('state', this.state);
        this.temp_wrap.children(':last').bind('click', self.choose);
      },
      run_over: function() {
        for (var iter = 0; iter < this.json.years.length; iter++) {
          this.single_display(iter);
        }
      },
      display: function() {
        var temp_function = self.run_through;
        self.run_through = this.run_over;
        self.wrap_up_proper.call(this, '<h3>Choose Your ' + this.kind + '</h3><ul class="wrap"></ul>');
        self.run_through = temp_function;
      }
    },
    model : {
      kind: 'model',
      name: 'model_id', 
      json_name: 'id',
      value: null,
      json: null,
      state: 3,
      url: function() {
        return '/vehicle/models.json?' + self.chooser_linkup.brand.name + '=' + self.chooser_linkup.brand.value + '&' + self.chooser_linkup.year.name + '=' + self.chooser_linkup.year.value
      },
      single_display: function(i) {
        if (i % 7 == 0) {
            this.temp_wrap.append('<ul></ul>');
            this.temp_ul = this.temp_wrap.children(':last');
          }
          this.temp_ul.append('<li><h4>' + this.json[i].vehicle_model.name + '</h4></li>');
          for (var j = 0; j < this.json[i].vehicles.length; j++) {
            this.temp_ul.children('li:last').append('<a href="' + self.chooser_linkup.detail.url(this.json[i].vehicles[j].vehicle[this.json_name]) + '" >' + (this.json[i].vehicles[j].vehicle.engine ? this.json[i].vehicles[j].vehicle.engine : '<em>Get Notified </em>') + '</a>');
          }
          this.temp_ul.children(':last').data(this.json_name, this.json[i].vehicle_model[this.json_name]);
          this.temp_ul.children(':last').data('state', this.state);
      },
      display: function() {
        var temp_slide = self.slide_side;
        self.slide_side = false;
        self.wrap_up_proper.call(this, '<h3>Choose Your ' + this.kind + '</h3><div class="wrap"></div>');
        self.slide_side = temp_slide;
      }
    },
/*
    vehicle : {
      kind: 'vehicle',
      name: '', 
      json_name: 'id',
      value: null,
      json: null,
      state: 4,
      url: function() {
        return '/vehicle/vehicles.json?' + chooser_linkup.model.name + '=' + chooser_linkup.model.value + '&' + chooser_linkup.year.name + '=' + chooser_linkup.year.value
      },
      single_display: function(i) {
        if (chooser_linkup.vehicle.json.length == 1) {
          document.location = '/vehicle/vehicles/' +chooser_linkup.vehicle.json[0].vehicle[chooser_linkup.vehicle.json_name];
        } else {
          for (var i = 0; i < chooser_linkup.vehicle.json.length; i++) {
            container.append('<a href="/vehicle/vehicles/' + chooser_linkup.vehicle.json[i].vehicle[chooser_linkup.vehicle.json_name] + '>' + chooser_linkup.vehicle.json[i].vehicle.engine + '</a>');
          }
        }
      },
      display: function() {
        self.wrap_up_proper.call(this, '<h3>Choose Your ' + this.kind + '</h3><ul class="wrap"></ul>');
      }
    },
*/
    detail : {
      url: function(model_id) {
        if (model_id) {
          self.chooser_linkup.model.value = model_id
        }
        return '/vehicle/vehicles/' + self.chooser_linkup.model.value;
      }
    }
  }
  var _ar = ['brand', 'year', 'model']
  this.state = 0;
  this.slide_side = false;
  
  this.visual_switch = function() {
    self.chooser.animate({
      height: self.chooser.children().eq(self.state).position().top + self.chooser.children().eq(self.state).outerHeight(true)
    }, {duration: 350, 
      easing: "easeOutQuart",
      queue: false,
      complete: self.up_state
    });
  }
  
  this.up_state = function() {
    self.state++;
  }
  
  this.display_result = function(json) {
    if (json) {
      self.chooser_linkup[_ar[self.state]].json = json
    }
    self.chooser_linkup[_ar[self.state]].display();
    self.visual_switch();
  }
  
  this.choose = function(e) {
    var me = $(this);
    if (self.state <= 0 || me.data('state') <= 0) {
      self.state = 0;
    } else if (me.data('state') == undefined) {
      self.state--;
      self.root.children('.x_actions').trigger('click');
    }
    else {
      $(this).siblings().removeClass('active');
      $(this).addClass('active');
      if (self.state != me.data('state')) {
        self.state = me.data('state')
      }
      self.chooser_linkup[_ar[self.state - 1]].value = me.data(self.chooser_linkup[_ar[self.state - 1]].json_name);
    }
    if (self.state < _ar.length) {
      $.getJSON(self.chooser_linkup[_ar[self.state]].url(), self.display_result);
    } else {
      document.location = self.chooser_linkup.detail.url();
    }
  }
}
/* -----------------------------------------------------------
/* ------------------------- home vehicle chooser ---------------
  this extends the vehicle chooser.
*/
function Home_Vehicle_chooser(element) {
  var self = this;
  Vehicle_chooser.call(this, element);
  
  this.visual_switch = function() {
    self.chooser.animate({
      left: -self.chooser.children().eq(self.state).position().left
    }, {duration: 450, 
      easing: "easeOutQuart",
      queue: false,
      complete: self.up_state
    });
  }
  
  this.attach_brand = function() {
   this.t_json = self.chooser_linkup.brand.json;
    for (var i = 0; i < this.t_json.length; i++) {
      if (this.t_json[i].vehicle_brand[self.chooser_linkup.brand.json_name] == self.chooser_linkup.brand.value) {
        this.temp_name = this.t_json[i].vehicle_brand.name;
        this.temp_logo = this.t_json[i].vehicle_brand.logo
        break;
      }
    }
    self.chooser.before('<div class="brand_stay"><img src="' + this.temp_logo + '" alt="' + this.temp_name +'" /><h4>' + this.temp_name + '</h4><span>reset</span></div>');
    this.reseter = self.chooser.prev().children('span');
    this.reseter.data('state', 0);
    this.reseter.one('click', self.choose);
    this.reseter.one('click', function() {
      self.chooser.prev().animate({
        height: (($.support.boxModel) ? (0) : (1))
      }, {duration: 450, 
        easing: "easeOutQuart",
        queue: false,
        complete: function() {
          $(this).remove();
        }
      });
    });
  }

  this.chooser_linkup.year.display = function() {
    var temp_function = self.run_through;
    self.run_through = this.run_over;
    self.attach_brand();
    self.wrap_up_proper.call(this, '<h3>Choose Your ' + this.kind + '</h3><ul class="wrap"></ul>');
    self.run_through = temp_function;
  }

  this.choose();
}
/* -----------------------------------------------------------
/* ------------------------- main vehicle chooser ----------------
  this extends the Vehicle_chooser class
*/
function Main_Vehicle_chooser(element) {
  var self = this;
  Vehicle_chooser.call(this, element);
  
  
  if (this.root.children('img').length < 2) {
    this.root.append('<img class="arrow for_x" src="/images/global/icons/left_arrow.png" alt="chooser arrow" />')
  }
  
  this.arrower = this.root.children('img:first');
  this.for_x = this.root.children('img:last');
  
  this.winder = $(window);
  
  this.set_x_left = function() {
    return self.winder.width() + 50
  }
  
  this.root.children().not('div').wrapAll('<div class="x_actions"></div>')
  
  this.outside_open = function() {
    self.for_x.css({left : self.set_x_left()});
    self.arrower.add(self.for_x).animate({
      left: self.root.width() - self.arrower.position().left - 30
    }, {duration: 450, 
      easing: "easeOutQuart",
      queue: false
    });
    self.for_x.show().animate({
      left: self.root.width() - self.arrower.position().left - 36
    }, {duration: 450, 
      easing: "easeOutQuart",
      queue: false
    });
    if (self.state != 0) {
      self.chooser.show().animate({
        height: self.chooser.children().eq(self.state - 1).position().top + self.chooser.children().eq(self.state - 1).outerHeight(true)
      }, {duration: 450, 
        easing: "easeOutQuart",
        queue: false
      });
    } else {
      self.root.trigger('click');
    }
  }
  
  this.outside_close = function() {
    self.chooser.animate({
      height: (($.support.boxModel) ? (0) : (1))
    }, {duration: 450, 
      easing: "easeOutQuart",
      queue: false
    });
    self.arrower.animate({
      left: 0
    }, {duration: 450, 
      easing: "easeOutQuart",
      queue: false
    });
    self.for_x.animate({
      left: self.set_x_left()
    }, {duration: 450, 
      easing: "easeOutQuart",
      queue: false
    }).hide();
  }
  
  this.root.children('.x_actions').toggle(this.outside_open, this.outside_close);
  $('a[href="#vehicle_chooser"]').toggle(this.outside_open, this.outside_close);
  
  this.slide_side = true;
  
  this.root.one('click', this.choose);
}
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/     
function Window_fixer(element) {
  var self = this;
  this.root = element;
  this.wind = $(window);
  this.foot = this.root.find('#footer');
  
  this.set_sizes = function() {
    self.foot_height = self.foot.children('.boiler').height();
    self.root_width = self.root.width();
    self.root_height = self.root.outerHeight();
  }

  this.footer_widther = function()  {
    self.set_sizes()
    if (self.root_width < self.wind.width()) {
      this.widther = (self.wind.width() - self.root_width) / 2;
      if (!$.support.boxModel) {
        self.foot.css({
          'padding-left' : this.widther,
          'padding-right' : this.widther,
          'margin-left' : -this.widther,
          width : 964 + this.widther * 2
        });
      } else {
        self.foot.children('.boiler').andSelf().css({
          'padding-left' : this.widther,
          'padding-right' : this.widther,
          'margin-left' : -this.widther
        });
      }
    }
    if (self.root_height <= self.wind.height()) {
      this.heighter = (self.wind.height() - self.root_height);
      self.foot.children('.boiler').height(self.foot_height + this.heighter);
    }
    else {
      self.foot.children('.boiler').css({
        'height' : 'auto'
      });
    }
  }
  this.window_fix = function()  {
    if (self.wind.width() < self.root.width()) {
      if (!self.fixer.hasClass('fixed')) {
        self.fixer.addClass('fixed');
      }
    } else {
      if (self.fixer.hasClass('fixed')) {
        self.fixer.removeClass('fixed');
      }
    }
  }
  //this.wind.bind('resize', self.window_fix);
  this.wind.bind('resize', this.footer_widther);
  this.wind.bind('load', this.footer_widther)
}
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/
function Expandable(element, first_open) {
  var self = this;
  this.root = element;
  this.exander = this.root.find('h3');
  
  this.set_slide = function(target) {
    this.slides = target.next();
    this.temp = this.slides.next();
    target.append('<span>&nbsp;</span>');
    while (!this.temp.is('h3') && this.temp.html()) {
      this.slides = this.slides.add(this.temp);
      this.temp = this.temp.next();
    }
    this.slides.wrapAll('<div class="wrapper"></div>');
    target.toggle(function() {
      $(this).next().slideDown(300, "easeOutQuad");
      $(this).addClass('open');
    }, function() {
      $(this).next().slideUp(300, "easeOutQuad");
      $(this).removeClass('open');
    });
  }
  for (var i = 0; i < this.exander.length; i++)
    this.set_slide($(this.exander[i]));
  this.root.find('.wrapper').slideUp(0);
  if (typeof(first_open) === "number")
    this.exander.eq(first_open).click();
}
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/
function Home_page(element) {
  var self = this;
  this.root = element;
  new Carousel(this.root.find('.carousel'), 7, true, 'home_carousel');
  new Home_Vehicle_chooser(self.root.find('.column.right.thin'));
}
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/
function CookieHandler() {
  this.setCookie = function (name, value, days_around) {
    if (typeof(seconds) != 'undefined') {
      this.date = new Date();
      date.setTime(date.getDate() + days_around);
      this.expires = "; expires=" + date.toGMTString();
    }
    else {
      this.expires = "";
    }
    document.cookie = name + "=" + value + this.expires + "; path=/";
  }
  this.getCookie = function (name) {
    name += "=";
    var carray = document.cookie.split(';');
    for(var i=0;i < carray.length;i++) {
      var c = carray[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(name) == 0) return c.substring(name.length,c.length);
    }
    return null;
  }
  this.deleteCookie = function (name) {
    this.setCookie(name, "", -1);
  }
}
/* -----------------------------------------------------------
/* ------------------------- Carouseler ------------------------
*/
function Carousel(element, delay, auto, name_of_cookie) {
  var self = this;
  this.root = element;
  this.automate = auto;
  this.delay = delay;
  this.cookie_name = name_of_cookie;
  this.main_items = this.root.children();
  if (this.main_items.length <= 1) {
    return;
  }
  
  this.cookier = new CookieHandler();
  this.on_own = null;
  this.root.prepend('<div class="thumb_container"></div>');
  this.thumb_containter = this.root.children(':first');
  for (var i = 0; i < this.main_items.length; i++) {
    this.thumb_containter.append('<img src="/images/home/carousel_marker.png" alt="replace" />');
    this.thumb_containter.children(':last').data('item', this.main_items.eq(i));
    this.thumb_containter.children(':last').data('iter', i);
  }
  this.thumbs = this.thumb_containter.children();
    
  this.large_switch = function(new_item, old_item) {
    self.thumb_containter.after(new_item.css('display', 'block'));
    old_item.animate({
      opacity: 0
    }, {duration: 800, 
      easing: "easeOutQuad",
      queue: false,
      complete:  function() {
        old_item.removeAttr('style').remove();
      }
    });
  }
  this.button_over = function(e) {
    $(this).animate({
      opacity: 0.65
    }, {duration: 250, 
      easing: "easeOutQuad",
      queue: false
    });
  }
  this.button_out = function(e) {
    if ($(e.currentTarget).data('iter') == self.active.data('iter')) {
      this.opacity = .8;
    } else {
      this.opacity = .4
    }
    $(this).animate({
      opacity: this.opacity
    }, {duration: 250, 
      easing: "easeOutQuad",
      queue: false
    });
  }
  this.button_on = function(e) {
    if ($(e.currentTarget).data('iter') == self.active.data('iter')) {
      return false;
    }
    self.cookier.setCookie(self.cookie_name, $(this).data('iter'), 10);
    self.large_switch($(this).data('item'), self.active.data('item'));

    self.active.animate({
      opacity: 0.4
    }, {duration: 500, 
      easing: "easeOutQuad",
      queue: false
    });
    $(this).animate({
      opacity: 0.8
    }, {duration: 500, 
      easing: "easeOutQuad",
      queue: false
    });

    self.active = $(this);
    if (self.automate) {
      self.timer_set();
    }
  }
  this.next_up = function() {
    if (self.active.next().is('img')) {
      self.active.next().trigger('click');
    } else {
      self.thumbs.eq(0).trigger('click');
    }
  }
  this.timer_set = function() {
    if (self.on_own != null) {
      clearTimeout(self.on_own);
    }
    self.on_own = setTimeout(function() {
      self.next_up();
    }, self.delay * 1000);

  }
  this.thumbs.bind('click', self.button_on);
  this.thumbs.hover(self.button_over, self.button_out);
  
  this.tempIter = Number(this.cookier.getCookie(self.cookie_name));
  if (!this.tempIter) {
    this.tempIter = 0;
  }
  this.main_items.remove();
  this.active = this.thumbs.eq(this.tempIter);
  this.root.append(this.active.data('item'));
  
  this.thumbs.eq((this.tempIter + 1) % this.main_items.length).trigger('click');
}
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/
function Page_tools(element) {
  var self = this;
  this.root = element;
  new Text_resizer(self.root.find('#text_resize'));
}
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/
function Text_resizer(element) {
  var self = this;
  this.root = element;
  this.current_size = 10;
  this.root.children('a[href="#increse"]').click(function() {
    $('.deskman').css({fontSize: ++self.current_size});
  });
  this.root.children('a[href="#decrese"]').click(function() {
    if (self.current_size > 10)
      $('.deskman').css({fontSize: --self.current_size});
  });
}
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/
function ToolTip(element, tipper, tip_name, replace) {
  var self = this;
  self.root = $('#jax_content');
  self.root.append(element);
  self.root.children('.toolTip:last').addClass(tip_name);
  var toolTip = self.root.find('.' + tip_name);
  if (replace)
    toolTip.children('.tip_cont').html(tip_name.replace(/_/g, ' '));
  toolTip.show();
  toolTip.css({
    top: (tipper.offset().top - toolTip.outerHeight() + 7),
    left: (tipper.offset().left - (toolTip.outerWidth() * .4) - 30),
    height: toolTip.children('.tip_cont').height() + 4,
    width: toolTip.children('.tip_cont').outerWidth() + 10
  });
  toolTip.children('.tip_cont').css('width', toolTip.width()-6);
  toolTip.hide();
  tipper.hover(
    function() {
      toolTip.show();
    },
    function() {
      toolTip.hide();
    }
  );
}
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/
function Emailer(element) {
  var self = this;
  this.root = element;
  /*	
  this.printer = this.root.siblings('a');
  this.print_tip = null;
  this.email_tip = null;
  if (this.printer.length > 0)
    $.ajax({
      url:"/print_tooltip",
      success: function(html) {
        self.print_tip = new ToolTip(html, self.printer, 'print', false);
      }
    });
    
  $.ajax({
    url:"/email_tooltip",
    success: function(html) {
      self.email_tip = new ToolTip(html, self.root, 'email', false);
    }
  });
  */
  
  this.ajaxed = null;
  this.openForm = function() {
    self.root.unbind('click', self.openForm);
    $.ajax({
      url: "/contact/refer",
      async: false,
      success: function(html) {
        $('#jax_content').append(html);
        self.ajaxed = $('#jax_content').children('form:last').addClass('deskman');
        self.ajaxed.dialog({
          modal: true,
          overlay: {
            backgroundColor: "#d9d1b6",
             opacity: '.9'
           },
          title: "Refer a Friend",
          height: 450,
          width: 500,
          resizable: true,
          buttons: {
            send: function() {
              var formData = self.ajaxed.serialize();
              $.ajax({
                url: "/contact/refer",
                type: "POST",
                data: formData,
                async: false,
                success: function(html) {
                  var tempHtml = $(html).find('#errorExplanation');
                  self.ajaxed.find('#errorExplanation').remove();
                  if (tempHtml.hasClass('errorExplanation')) {
                    self.ajaxed.prepend(tempHtml);
                  }
                  else {
                    self.ajaxed.html("<h3> Success </h3>");
                    self.ajaxed.fadeOut(500, function() {self.ajaxed.dialog('close')});
                  }
                }
              });
              //self.ajaxed.dialog('close');
            }	
          },
          close: function() {
            self.root.bind('click', self.openForm);
            self.ajaxed.dialog('destory').remove();
          }
        });
      }
    });
  }	
  this.root.bind('click', self.openForm);
}

$(document).ready(function() {
  new Ready_up('load');
});
/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/

function countryAndStateSelector() {
  var self = this;
  this.country_selectory = $('.select-country select');
  this.state_box = $('.select-state');
  
  this.get_states = function() {
		$.getJSON('/countries/'+ $(this).val() +'/states.json', self.populate_state);
  }
  this.populate_state = function(states) {
    if (states.length > 0) {
      self.state_box.html('<select id="address_state" name="address[state]"><option value="">Choose a state or province</option></select>');
      var state_selectory = self.state_box.find('select');
      for (var i = 0; i < states.length; i++) {
        states[i] = eval('(' + states[i] + ')');
        state_selectory.append('<option value="'+states[i].state.code+'">' + states[i].state.name + '</option>');
        self.state_box.siblings('td').find('.required').html('*');
      }
    } else {
      self.state_box.html('<input type="text" id="address_state" name="address[state]" />');
      self.state_box.siblings('td').find('.required').html('&nbsp;');
    }
  }
  this.start_up = function() {
    self.country_selectory.bind('change', self.get_states);
  }
  
  this.start_up();
}


function addToWishlist(link) {
	var variation_id = $('form.cart-add input[name=product_variation_id]').val();
	if(variation_id) {
		$(link).parents('form').
						children('input[name=product_variation_id]').
							val(variation_id).
							end().
						submit();
	}
}

// Use this to load a new URL when you want to ensure that the address will be
// loaded over HTTP instead of, for example, HTTPS.
//
// Currently this function only accepts absolute paths.
var redirect_over_http = function(path) {
		window.location = 'http://' + window.location.host + path;
};
var redirect_over_https = function(path) {
		window.location = 'https://' + window.location.host + path;
};

var submit_code = function() {
		window.location = "/cart/claim?code=" + $('#code')[0].value;
};

var submit_order_total_modification = function() {
  var order_total_adjustment        = $('#order_total_adjustment').val(),
      order_total_adjustment_type   = $('#order_total_adjustment_type').val(),
      shipping_cost_adjustment      = $('#shipping_cost_adjustment').val(),
      shipping_cost_adjustment_type = $('#shipping_cost_adjustment_type').val(),
      get_url = "/cart/total";
      parameters = [];
  if (order_total_adjustment) {
    parameters.push("order_total_adjustment=" + order_total_adjustment);
    parameters.push("order_total_adjustment_type=" + order_total_adjustment_type);
  }
  if (shipping_cost_adjustment) {
    parameters.push("shipping_cost_adjustment=" + shipping_cost_adjustment);
    parameters.push("shipping_cost_adjustment_type=" + shipping_cost_adjustment_type);
  }
  redirect_over_http(get_url + '?' + parameters.join('&'));
};

var ajax_submit = function(form, callback, errorCallback) {
  if (typeof(callback) !== 'function') {
    callback = function() { };
  }
  if (typeof(errorCallback) !== 'function') {
    errorCallback = function() { };
  }
  $(form).submit(function (e) {
    $.ajax({
      type: "POST",
      url: $(this).attr('action') + ".json",
      data: $(this).serialize(),
      success: callback,
      error: errorCallback
    });
    if (e.stopPropagation) { 
      e.stopPropagation();
    }
    return false;
  }); 
};

/* -----------------------------------------------------------
/* ------------------------- cLone ----------------------------
*/
