function Dropdown_navigation(parent_naviagtion) {
  var self = this;
  
  this.parent_items = this.root.parent().addClass('parent');
  this.parent_naviagtion = this.root.parents('.navigation');
  
  this.start_up = function() {
    self.root.css({display : 'block'});
    self.set_size(self.root);
  }
  
  this.show_sub_nav = function(e) {
    $(e.currentTarget).addClass('hovered').children('ul').css('display', 'block');
  }
  
  this.hide_sub_nav = function(e) {
    $(e.currentTarget).removeClass('hovered').children('ul').css('display', 'none');
  }
  
  this.set_size = function(holder) {
    var children = holder.children().children('ul');
    for(var i = 0; i < children.length; i++) {
      self.set_size(children.eq(i));
    }
    holder.css({
      width: (holder.parent().outerWidth(true) < holder.width() ? holder.width() : holder.parent().outerWidth(true))
    });
    holder.css({display : 'none'}).parent().hover(self.show_sub_nav, self.hide_sub_nav);
  }
  
  return this;
}

function Homepage_Slideshow() {
  var self = this;
  
  this.active_index = 0;
  this.auto_play_on = true;
  this.auto_play_ammount = 7000;

  this.thumbs_holder = this.root.children('div.thumbs');
  this.basin_holder = this.root.children('div.basins');
  this.thumbs = this.thumbs_holder.children();
  this.basins = this.basin_holder.children();
  this.basins.eq(self.active_index).siblings().remove();
  this.actions = this.root.children('div.actions').children();

  this.start_up = function() {
    self.thumb_setup();
    self.thumbs.bind('click', self.slide_basin)
    self.actions.eq(0).bind('click', self.digress_one);
    self.actions.eq(1).bind('click', self.play_pause);
    self.actions.eq(2).bind('click', self.advance_one);
    self.auto_time = setTimeout(self.auto_play, 4000);
  }
  
  this.thumb_setup = function() {
    thumb_html = '';
    for (var i = 0; i < self.basins.length; i++) {
      if (i === self.active_index) {
        thumb_html+= '<span class="active">' + (i+1) + '</span>';
      } else {
        thumb_html+= '<span>' + (i+1) + '</span>';
      }
    }
    self.thumbs_holder.html(thumb_html);
    self.thumbs = self.thumbs_holder.children();
  }

  this.after_image_load = function(e) {
    if (!e.currentTarget.complete && typeof e.currentTarget.complete == 'boolean') { $(e.currentTarget).bind('load', self.after_image_load); return false;}
    self.auto_play();
  }
  
  this.play_pause = function() {
    if (self.auto_play_on) {
      if (self.auto_time) {clearTimeout(self.auto_time);}
      self.auto_play_on = false;
      self.actions.eq(1).html('play');
    } else {
      self.auto_play_on = true;
      self.basin_switch(self.active_index + 1);
      self.actions.eq(1).html('pause');
    }
  }
  
  this.advance_one = function(e) {
    self.basin_switch(self.active_index + 1);
  }
  
  this.digress_one = function(e) {
    self.basin_switch(self.active_index + -1);
  }
  
  this.auto_play = function() {
    if (self.auto_time) {clearTimeout(self.auto_time);}
    if (self.auto_play_on) {
      self.auto_time = setTimeout(function(){self.basin_switch(self.active_index + 1);}, self.auto_play_ammount);
    }
  }
  
  this.slide_basin = function(e) {
    e.preventDefault();
    var me = $(e.currentTarget);
    if (me.hasClass('active')) {return false;}
    if (self.auto_time) {clearTimeout(self.auto_time);}
    self.basin_switch(me.prevAll().length);
  }
    
  this.basin_switch = function(new_index) {
    if (self.active_index == new_index || self.thumbs.eq(self.active_index).hasClass('acitve')) { return false; }
    if (new_index >= self.thumbs.length) {new_index = 0;}
    else if (new_index < 0) {new_index = self.thumbs.length - 1}
    self.active_index = new_index;
    self.basin_holder.prepend(self.basins.eq(self.active_index).css({opacity : 1}));
    self.auto_play();
    self.basins.eq(self.active_index).bind('reloaded', self.basin_visiual_switch);
    self.basins.eq(self.active_index).trigger('reloaded');
  }

  this.basin_visiual_switch = function(e) {
    if (!e.currentTarget.complete && typeof e.currentTarget.complete == 'boolean') { $(e.currentTarget).bind('load', self.basin_visiual_switch); return false;}
    self.basins.eq(self.active_index).unbind();
    self.thumbs.eq(self.active_index).addClass('active');
    if ($.browser.msie) {
      self.auto_play_ammount = 5000;
      self.thumbs.eq(self.active_index).siblings().removeClass('active');
      self.basins.eq(self.active_index).siblings().remove();
    } else {
      self.skch(self.basins.eq(self.active_index).siblings(), {opacity : 0}, function(){
        self.thumbs.eq(self.active_index).siblings().removeClass('active');
        self.basins.eq(self.active_index).siblings().remove();
      }, 1, 'easeOutCubic');
    }
  }

  return this;
}

function Product_sorter() {
  var self = this;
  
  this.start_up = function() {
    self.root.bind('change', self.sort_products);
  }
  
  this.sort_products = function(e) {
    window.location = $(e.currentTarget).val();
  }
  
  return this;
}

function Side_dropdown_navigation() {
  var self = this;
  
  this.current_category = this.root.children('h4');
  this.category_list = this.root.children('ul');
  this.category_list.css({height : 'auto'});
  this.open_list_height = this.category_list.height();
  this.category_list.css({height : 0});
  
  this.start_up = function() {
    self.current_category.bind('click', self.open_category_list);
  }
  
  this.open_category_list = function() {
    if (self.category_list.hasClass('open')) {
      self.current_category.removeClass('open');
      self.skch(self.category_list, {
        height : 0, 
        paddingTop : 0, 
        paddingBottom : 0
      }, function() {self.category_list.removeClass('open');});
    } else {
      self.current_category.addClass('open');
      self.skch(self.category_list, {
        height : self.open_list_height, 
        paddingTop : 3, 
        paddingBottom : 3
      }, function() {self.category_list.addClass('open');});
    }
  }
  
  return this;
}

function Region_switch() {
  var self = this;
  this.root.find('select').removeAttr('onchange');
  this.country_select = this.root.find('select[title="Country"]');
  this.region_select = this.root.find('[title="State/Province"]');
  
  this.start_up = function() {
    self.country_select.bind('change', self.get_new_regions);
  }
  
  this.get_new_regions = function(e) {
    e.preventDefault();
    $.ajax({
      url : '/checkout/cart/getRegions',
      type : 'post',
      data : {'country' : self.country_select.val()},
      dataType : 'json',
      success : self.set_up_regions
    })
  }
  
  this.set_up_regions = function(data) {
    console.log(self.region_select);
    if (data.length > 0) {
      self.region_select.replaceWith('<select name="' + self.region_select.attr('name') + '" title="State/Province"></select>');
      var region_options = '';
      for (var i = 0; i < data.length; i++) {
        region_options+= '<option value="' + data[i].region_id + '"> ' + data[i].default_name + ' </option>';
      }
      self.region_select = self.root.find('select[title="State/Province"]');
      self.region_select.html(region_options);
    } else {
      self.region_select.replaceWith('<input type="text" name="' + self.region_select.attr('name') + '" title="State/Province" />');
      console.log(self.region_select);
      self.region_select = self.root.find('input[title="State/Province"]');
    }
    
  }
  
  return this;
}

function Form_plus(form) {
  var self = this;
  Manipulator.call(this, form);
  this.former = form;
  this.inputs = this.former.find('input');
  this.fieldsets = this.former.find('fieldset');
  
  this.start_up = function() {
    if (self.inputs.filter('[name=allow_gift_messages]').length > 0) {
      self.gift_messages_choice = self.inputs.filter('[name=allow_gift_messages]');
      self.gift_messages = self.fieldsets.filter('.gift_messages');
      self.gift_messages_short_height = self.gift_messages.height();
      self.gift_messages_tall_height = self.gift_messages.css({'height' : 'auto'}).height();
      self.gift_messages.css({height : self.gift_messages_short_height});
      self.gift_messages_choice.bind('click', self.expand_gift_message);
    }
  }    
  
  this.expand_gift_message = function(e) {
    self.gift_messages.parents('div.stage').css({height : 'auto'});
    self.skch(self.gift_messages, { height : (self.gift_messages_choice.attr('checked') ? self.gift_messages_tall_height : self.gift_messages_short_height ) });
  }
  
  return this;
}


function Checkout_stages(steps, sidebar) {
  var self = this;
  this.page_stage = this.prev_page_stage = 0;
  this.steps = steps;
  this.stages = steps.children('div.stage');
  this.stage_titles = this.steps.children('h2');
  this.sidebar = sidebar;
  
  
  this.form_plus = new Form_plus(this.root).start_up();
  this.start_up = function() {
    self.root.bind('submit', function(e) {e.preventDefault();});
    self.root.eq(self.page_stage).bind('submit', self.next_stage);
    self.stage_titles.children('a').bind('click', self.edit_stage);
  }
  
  this.edit_stage = function(e) {
    e.preventDefault();
    var stage = $(e.currentTarget).parent().siblings('div.stage');
    self.root.unbind('submit', self.next_stage);
    self.stages.eq(self.page_stage).css({height : 0});
    self.page_stage = stage.parent().prevAll('div').length;
    self.root.eq(self.page_stage).bind('submit', self.next_stage);
    stage.css({height : 'auto'});
  }
  
  this.next_stage = function(e) {
    e.preventDefault();
    $(e.currentTarget).unbind('submit', self.next_stage);
    self.stages.children('ul.messages').remove();
    self.prev_page_stage = self.page_stage;
    var me = self.root.eq(self.page_stage++);
    console.log(me, self.page_stage, self.prev_page_stage, self.root.length)
    var data = me.serialize();
    if (self.page_stage == self.root.length) {
      data += $('div#payment').find('form').serialize()
    }
    $.ajax({
      url : me.attr('action'),
      type : 'post',
      data : data,
      dataType : 'json',
      success : self.setup_data
    });
  }
  
  this.setup_data = function(data) {
    if (data.error != '' && data.error != undefined) {
      var message = '<ul class="messages error">';
      if (data.message != '' && data.message != undefined) {
        if (data.message instanceof Array) {
          for (var i = 0; i < data.message.length; i++) {
            message += '<li> ' + data.message[i] + ' </li>';
          }
        } else {
           message += '<li> ' + data.message + ' </li>';
        }
      } else if (data.error_messages != '' && data.error_messages != undefined) {
        if (data.error === 'true' || (data.error === true)) {
          message += '<li> ' + data.error_messages + ' </li>';
        } else {
          message += '<li> ' + data.error + ' </li>';
        }
      } else if (data.error != '' && data.error != undefined) {
        message += '<li> ' + data.error + ' </li>';
      }
      message += '<li> </li></ul>';
      
      if (self.stages.eq(self.page_stage - 1).children('ul.messages').length > 0) {
        self.stages.eq(self.page_stage -1).children('ul.messages').replaceWith(message);
      } else {
        self.stages.eq(self.page_stage -1).prepend(message);
      }
      self.page_stage--;
    } else if (data.goto_section != '' && data.goto_section != undefined) {
      var new_goto_stage = self.steps.filter('#' + data.goto_section).prevAll().length;
      if (new_goto_stage != self.page_stage) {
        self.page_stage = new_goto_stage;
      }
      if (data.update_section != undefined && data.update_section.name && data.update_section.name != '' && data.update_section.name != undefined) {
        if (self.root.eq(self.page_stage).find('fieldset.' + data.update_section.name).length > 0) {
          self.root.eq(self.page_stage).find('fieldset.' + data.update_section.name).replaceWith(data.update_section.html);
        } else {
          self.root.eq(self.page_stage).find('fieldset:last').before(data.update_section.html);
        }
      }
    }
    
    self.root.eq(self.page_stage).bind('submit', self.next_stage);
    //self.root.eq(self.prev_page_stage).bind('submit', self.next_stage);
    self.steps.eq(self.page_stage).addClass('allow').prevAll().addClass('done').addClass('allow');
    self.skch(self.stages.eq(self.prev_page_stage), {height : 0});
    var new_height = self.stages.eq(self.page_stage).css({height : 'auto'}).height();
    self.stages.eq(self.page_stage).css({height : 0});
    self.skch(self.stages.eq(self.page_stage), {height : new_height});
    
    if (self.page_stage >= self.root.length) {
      window.location = '/checkout/onepage/success/';
    } else {
      self.getAdditional();
    }
  }
  
  this.getAdditional = function() {
    $.ajax({
      url : '/checkout/onepage/progress/',
      type : 'post',
      //data : me.serialize(),
      //dataType : 'json',
      success : function(data) {
        self.sidebar.html(data);
      }
    });
    /*
    $.ajax({
      url : window.location.pathname + 'getAdditional/',
      type : 'post',
      //data : me.serialize(),
      //dataType : 'json',
      success : function(data) {//console.log(data)
        }
    });
    */
  }
  
  return this;
}

function Estimate_shipping() {
  var self = this;
  
  this.estimate_form = this.root.children().eq(0);
  
  this.start_up = function() {
    ///self.estimate_form.bind('submit', self.get_form);
  }
  
  this.get_form = function(e) {
    e.preventDefault();
    
    $.ajax({
      url : self.estimate_form.attr('action'),
      type : 'post',
      data : self.estimate_form.serialize(),
      success : function(data) {console.log(data)}
    });
  }
  
  return this;
}



function Product_Media() {
  var self = this;
  
  this.thumbs_holder = this.root.children('div.thumbs');
  this.thumbs = this.thumbs_holder.children('a');
  this.main = this.root.children('a');
  this.basins = this.main.children();
  
  Image_gallery.call(this);
  this.start_up = function() {
    self.basin_setup();
    self.gallery_items_setup();
    self.thumbs.bind('click', self.image_switch);
    self.main.bind('click', self.bring_gallery);
    self.poduct_options_switch();
  }
  
  this.poduct_options_switch = function() {
  }
  
  this.basin_setup = function() {
    for (var i = 0; i < self.thumbs.length; i++) {
      if (i === self.active_index) {self.thumbs.eq(i).addClass('active'); continue}
      var new_basin = new Image();
      new_basin.src = self.thumbs.eq(i).attr('href');
      self.basins.push(new_basin);
    }
  }

  this.gallery_items_setup = function() {
    var new_basin = new Image();
    new_basin.src = self.main.children('span').html();
    self.gallery_items = $(new_basin);
    for (var i = 0; i < self.thumbs.length; i++) {
      var new_basin = new Image();
      new_basin.src = self.thumbs.eq(i).children('span').html();
      self.gallery_items.push(new_basin);
    }
  }

  
  this.image_switch = function(e) {
    e.preventDefault();
    self.active_iter = $(e.currentTarget).prevAll('a').length + 1;
    $(e.currentTarget).addClass('active').siblings().removeClass('active');
    self.main.children().eq(0).attr('src', $(e.currentTarget).attr('href'));
  }
  
  return this;
}


function Image_Popin_view() {
  var self = this;
  
  Popin_view.call(this);
  
  self.view.popin_title += '';
    self.view.popin_actions += '<a href="#left" class="arrow"> < </a>';
    self.view.popin_actions += '<a href="#right" class="arrow"> > </a>';
    self.view.popin_actions += '<a href="#close" class="close"> close </a>';
  self.view.popin_content += '';
  
  return this;
}

function Image_gallery() {
  var self = this;
  
  
  this.gallery_items = this.root.children('a');
  
  this.jaxer = $('#content');
  this.current_popin = null;
  this.show_items = null;
  this.unopened = true;
  this.active_iter = 0;
  
  
  this.start_up = function() {
    self.gallery_items.bind('click', self.bring_gallery);
  }
  
  this.bring_gallery = function(e) {
    e.preventDefault();
    var gallery_html = '<div class="wrapper">';
    for (var i = 0; i < self.gallery_items.length; i++) {
      gallery_html += '<img src="' + self.gallery_items.eq(i).attr('src') + '" />';
    }
    gallery_html += '</div><div class="image_description deskman"> </div>';
    self.popin_whipup(gallery_html);
    self.start_gallery();
  }
  
  this.start_gallery = function() {
    self.show_items.eq(self.active_iter).bind('reload', self.after_image_load);
    self.show_items.eq(self.active_iter).trigger('reload');
  }
  
  this.after_image_load = function(e) {
    if (!e.currentTarget.complete && typeof e.currentTarget.complete == 'boolean') { 
      //$(e.currentTarget).bind('load', self.after_image_load); 
      //return false;
    }
    self.current_popin.overlay.set_size();
    self.show_items.eq(self.active_iter).css({display:'block'}).siblings().css({display:'none'});
    var popin_width = self.show_items.eq(self.active_iter).width();
    self.current_popin.popin.css({width : popin_width, marginLeft : -popin_width/2});
    self.current_popin.popin_content.children('div.wrapper').css({height : self.show_items.eq(self.active_iter).height()});
    self.current_popin.bring_popin();
    self.show_items.bind('click', self.advance_forward);
    self.current_popin.popin_actions.children('a.arrow').eq(0).bind('click', self.advance_back);
    self.current_popin.popin_actions.children('a.arrow').eq(1).bind('click', self.advance_forward);
  }
  
  this.advance_forward = function() {
    if (++self.active_iter >= self.show_items.length) {
      self.active_iter = 0;
    }
    if (self.active_iter > 0) {
      self.thumbs.eq(self.active_iter - 1).trigger('click');
    }
    self.visual_switch();
  }
  
  this.advance_back = function() {
    if (--self.active_iter < 0) {
      self.active_iter = self.show_items.length - 1;
    }
    self.thumbs.eq(self.active_iter - 1).trigger('click');
    self.visual_switch();
  }
  
  this.visual_switch = function() {
    self.show_items.eq(self.active_iter).css({display:'block'}).siblings().css({display:'none'});
    var popin_width = self.show_items.eq(self.active_iter).width();
    if (popin_width > self.current_popin.overlay.jax_space.width()) {
      popin_width = self.current_popin.overlay.jax_space.width() - 40;
    }
    //self.current_popin.overlay.overlay.height(popin_height + 20);
    self.current_popin.popin.css({width : popin_width, marginLeft : -popin_width/2});
    self.current_popin.popin_content.children('div.wrapper').css({height : self.show_items.eq(self.active_iter).height()});
    self.current_popin.popin_actions.siblings().html(self.gallery_items.eq(self.active_iter).attr('title'));
  }

  this.popin_whipup = function(html) {
    var popin = new Image_Popin_view();
    //popin.view.popin_title += '<h4>' + self.gallery_items.eq(self.active_iter).attr('title') + '</h4>';
    popin.view.popin_content += html;
    self.current_popin = new Popin(popin);
    self.current_popin.plugin_popin(self.jaxer);

    self.show_items = self.current_popin.popin_content.children('div.wrapper').children();
    self.image_description = self.current_popin.popin_content.children('div.image_description');
    self.current_popin.overlay.set_size();
    self.current_popin.popin_actions.children('a.close').bind('click', self.current_popin.close_popin);
    self.current_popin.overlay.overlay.bind('click', self.current_popin.close_popin);
  }

  return this;
}


function Active_navigation() {
  var self = this;
  
  this.linkers = this.root.find('a');
  
  this.start_up = function() {
    self.linkers.removeClass('active');
    var active_link = self.linkers.filter('a[href="' + document.location + '"]');
    if (active_link.length < 1) {
      active_link = self.linkers.filter('a[href$="' + document.location.pathname + document.location.search + '"]');
    }
    console.log(active_link, 'a[href$="' + document.location.pathname + document.location.search + '"]');
    active_link.addClass('active').parents('ul').siblings('a').addClass('active');
  }
  
  return this;
}

function Quick_search() {
  var self = this;
  
  this.start_up = function() {
    self.text_switch = new Text_switch(self.root.find('input'));
    self.text_switch.start_up();
  }
  
  return this;
}

