function Navigation_hover() {
  var self = this;
  
  this.start_up = function() {
    self.root.parent().hover(function() {
      self.root.show();
    }, function() {
      self.root.hide();
    });
  }
  
  return this;
}

function Slideshow() {
  var self = this;
  
  this.thumbs = this.root.children('div.thumbs').children();
  this.basin_holder = this.root.children('div.basins');
  this.basins = this.basin_holder.children();

  this.active_index = 0;
  this.auto_play_on = true;
  this.auto_play_ammount = 8000;

  this.start_up = function() {
    self.basin_setup();
    self.basins.eq(self.active_index).bind('reload', self.after_image_load);
    self.basins.eq(self.active_index).trigger('reload');
  }
  
  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.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.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 (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');
    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.3, 'easeOutCubic');
  }

  return this;
}

function Territory_chooser(navigation_link, teritory_link) {
  var self = this;
  
  this.image_map = this.root.children('map');
  this.territories = this.image_map.children();
  this.region_map = this.root.children('img');
  this.origional_region_map_src = this.region_map.attr('src');
  
  this.navigation_link = navigation_link;
  
  this.options_out = false;
  this.hover_hack = null;
  
  this.start_up = function() {
    self.territories.bind('click', self.territory_switch);
    self.territories.bind('mouseenter', self.territory_hover);
    self.root.bind('mouseleave', self.back_to_starting_territory);
    self.navigation_link.add(teritory_link).bind('mouseenter', self.navigation_territory_switch);
    self.navigation_link.add(teritory_link).bind('mouseleave', self.remove_extra_territory_navigation);
  }
  
  this.navigation_territory_switch = function() {
    if (self.options_out) { clearTimeout(self.hover_hack); return false; }
    self.options_out = true;
    var other_terrirories = [{href_name : 'default', short_name : 'default'}];
    var location_text = self.navigation_link.children('a').addClass('active').html().replace(/[^a-z]/gi, '');
    switch (location_text) {
      case 'westwa' :
        other_terrirories[0].short_name = 'idaho';
        other_terrirories[0].href_name = 'idaho';
        /*
        other_terrirories[1].short_name = 'east wa';
        other_terrirories[1].href_name = 'eastern-washington';
        break;
      case 'eastwa' :
        other_terrirories[0].short_name = 'west wa';
        other_terrirories[0].href_name = 'western-washington';
        other_terrirories[1].short_name = 'idaho';
        other_terrirories[1].href_name = 'idaho';
        */
        break;
      case 'idaho' :
        other_terrirories[0].short_name = 'west wa';
        other_terrirories[0].href_name = 'western-washington';
        /*
        other_terrirories[1].short_name = 'east wa';
        other_terrirories[1].href_name = 'eastern-washington';
        */
        break;
    }
    for (var i = 0; i < other_terrirories.length; i++) {
      self.navigation_link.append('<a class="other ' + other_terrirories[i].href_name + '" href="/' + other_terrirories[i].href_name + '"> ' + other_terrirories[i].short_name + ' </a>');
    }
    //self.navigation_link.children('a.other').eq(0).css({ top : -self.navigation_link.children('a.other').eq(1).height() - 18 });
    self.navigation_link.children('a.other').css({ color : '#ffffff' });

    //self.skch(self.navigation_link.children('a.eastern-washington'), { color : '#777777' });
    self.skch(self.navigation_link.children('a.western-washington'), { color : '#777777' });
    self.skch(self.navigation_link.children('a.idaho'), { color : '#777777' });
    self.navigation_link.children('a.other').bind('click', self.territory_switch);
    self.navigation_link.children('a.other').bind('mouseeneter', function() {
      clearTimeout(self.hover_hack);
    });
  }
  
  this.remove_extra_territory_navigation = function() {
    self.hover_hack = setTimeout(function() {
      self.skch(self.navigation_link.children('a.other'), { color : '#ffffff' }, function() {
        self.navigation_link.children('a.active').removeClass('active').siblings().remove();
        self.options_out = false;
      });
    }, 500);
  }
  
  this.territory_switch = function(e) {
    e.preventDefault();
    if (location.pathname == '/') {
      document.location = $(e.currentTarget).attr('href') + '/';
    } else if (location.pathname.match(/.*?\/.*?\//)) {
      document.location = location.pathname.replace(/.*?\/.*?\//, $(e.currentTarget).attr('href') + '/');
    } else {
      document.location = $(e.currentTarget).attr('href') + '/';
    }
  }
  
  this.territory_hover = function(e) {
    e.preventDefault();
    self.region_map.attr('src', self.origional_region_map_src.replace(/_.*\.png/, '_' + $(e.currentTarget).attr('href').replace('/', '') + '.png'));
  }
  
  this.back_to_starting_territory = function(e) {
    self.region_map.attr('src', self.origional_region_map_src);
  }
  
  return this;
}

function Text_switch(element) {
  var self = this;
  
  this.field = element.addClass('filled');
  this.default_value = this.field.val();
  
  this.start_up = function() {
    self.field.bind('focus', self.focus_switch_out);
    self.field.bind('blur', self.blur_switch_out);
  }
  
  this.focus_switch_out = function() {
    if(self.field.val() == self.default_value) {
      self.field.removeClass('filled').val('');
    }
  }

  this.blur_switch_out = function() {
    if(self.field.val() != self.default_value && !self.field.val().match(/([A-Za-z0-9-]+)/)) {
      self.field.addClass('filled').val(self.default_value);
    }
  }
  
  return this;
}

function Product_sort(data_container) {
  var self = this;
  
  this.holder = data_container;
  
  this.search_query = this.root.find('input:first');
  this.current_query_value = '';

  this.taggers = this.root.find('ul li');
  
  this.instant_update = null;

  this.start_up = function() {
    new Text_switch(self.search_query).start_up();
    self.search_query.bind('focus', self.reget_data);
    self.search_query.bind('blur', self.stop_get_data);
    self.root.bind('submit', self.inside_notifier);
    self.taggers.bind('click', self.select_tags);
  }
  
  this.inside_notifier = function(tagged) {
    if (!tagged) {
      if (self.search_query.val() === self.current_query_value) { return false; }
      
      self.current_query_value = self.search_query.val();
    }
    $.ajax({
      url: self.root.attr('action'),
      type: "POST",
      data: self.root.serialize(),
      async: false,
      success: self.notify_success
    });
    return false;
  }
  
  this.reget_data = function() {
    self.instant_update = window.setInterval(function() {self.inside_notifier(false)}, 500);
  }
  
  this.stop_get_data = function() {
    self.instant_update = window.clearInterval(self.instant_update);
  }
  
  this.select_tags = function(e) {
    var me = $(e.currentTarget);
    if (me.hasClass('active')) {
      me.children('input').remove();
      me.removeClass('active');
    } else {
      var field_name = me.children('img').attr('src').replace('/media/icons/product/', '').replace('.png', '');
      me.append('<input type="hidden" name="' + field_name + '" value="1" />');
      me.addClass('active');
    }
    self.inside_notifier(true);
  }
  
  this.notify_success = function(data) {
    self.holder.find('tbody').html(data);
    new Table_styled(false, self.holder);
    
    var new_list_html = '';
    var current_letter = '';
    for (var i = 0; i < self.holder.find('tbody th').length; i++) {
      current_letter = self.holder.find('tbody th').eq(i).html().replace(/ /g, '');
      if (current_letter == '&nbsp;') { continue; }
      new_list_html += '<a href="#' + current_letter + '"> ' + current_letter + '</a>';
    }
    $('div.side-out').html(new_list_html);
    
  }
  
  return this;
}

function Logout_user() {
  var self = this;
  
  this.start_up = function() {
    self.root.bind('click', self.logout_user);
  }
  
  this.logout_user = function() {
    $.ajax({
      url: '/logout',
      type: "GET",
      async: false,
      success: self.user_logout
    });
  }
  
  this.user_logout = function() {
    window.location.reload();
  }
  
  return this;
}

function Updater(item_list) {
  var self = this;
  
  this.items = item_list;
  this.item_type = 'item';
  
  this.start_up = function() {
    self.root.bind('submit', self.update_data);
    self.items.bind('click', self.edit_data);
    self.root.find('tfoot a[href=#clear]').bind('click', self.clear_form);
    self.root.find('tfoot a[href=#deactivate]').bind('click', self.active_toggle);
  }
  
  this.clear_form = function() {
    self.root.find('input[type=hidden]').remove();
    self.root.find('input, textarea, select').val('');
    self.root.find('button').html('Add ' + self.item_type.capitalize());
    self.root.find('a[href=#deactivate]').html('');
    self.root.find('div.fileupload_holder img').attr('src', '/media/fpo/product-image-not-available.png');
    self.items.removeClass('selected');
    return false;
  }
  
  this.active_toggle = function() {
    $.ajax({
      url: self.root.attr('action').replace('edit', 'deactivate'),
      type: "POST",
      data: {
        'id' : self.root.find('input[name=id]').val(),
        "active" : (self.root.find('a[href=#deactivate]').html() == 'activate ' + self.item_type ? '1' : '0')
      },
      async: false,
      success: self.process_response
    });
  }
  
  this.update_data = function(e) {
    e.preventDefault();
    $.ajax({
      url: self.root.attr('action'),
      type: "POST",
      data: self.root.serialize(),
      async: false,
      success: self.process_response
    });
  }
  
  this.edit_data = function(e) {
    e.preventDefault();
    self.items.removeClass('selected');
    $(e.currentTarget).addClass('selected');
    $.ajax({
      url: self.root.attr('action').replace('edit', 'grab-data'),
      type: "POST",
      dataType: "json",
      data: {'id' : $(e.currentTarget).find('span.ider').html()},
      async: false,
      success: self.prepare_edit
    });
  }
  
  this.insert_data = function(data) {
    /* virtual function */
  }
  
  this.prepare_edit = function(data) {
    self.insert_data(data[0]);
    if (self.root.find('input[name=id]').length > 0) {
      self.root.find('input[name=id]').val(data[0]['id']);
    } else {
      self.root.find('button').after('<input type="hidden" name="id" value="' + data[0]['id'] +'" />');
    }
    if (data[0]['active'] == "0") {
      self.root.find('a[href=#deactivate]').html('activate ' + self.item_type);
    } else {
      self.root.find('a[href=#deactivate]').html('deactivate ' + self.item_type);
    }
    self.root.find('button').html('Update ' + self.item_type.capitalize());
    window.scrollTo(0,200);
  }

  this.process_response = function(data) {
    self.clear_form();
    location.reload();
  }
  
  return this;
}

function Employee_update(employee_list) {
  var self = this;
  
  Updater.call(this, employee_list);
  
  this.item_type = 'employee';
  this.jaxer = $('#jax_container');
  
  var current_item = current_over = new_current_over = new_insert = null;
  var start_position = {top: 0, left: 0};
  var x_leway = y_leway = 10;
  var start_move = false;
  var item_order_list = new Array();
  
  this.items.parent('tbody').addClass('sortable');

  var parent_start_up = this.start_up;
  this.start_up = function() {
    parent_start_up();
    self.items.bind('mousedown', self.start_employee_order);
    $(document.body).bind('mouseup', self.end_employee_order);
  }
  
  this.start_employee_order = function(e) {
    e.preventDefault();
    current_item = $(e.currentTarget);
    start_position = {top: e.pageY, left: e.pageX}
    $(document.body).bind('mousemove', self.employee_order);
  }
  
  this.employee_order = function(e) {
    if (!start_move) {
      var is_x_move = (e.pageX > start_position.left + x_leway || e.pageX < start_position.left - x_leway);
      var is_y_move = (e.pageY > start_position.top + y_leway || e.pageY < start_position.top - y_leway);
      if (is_x_move || is_y_move) {
        start_move = true;
        current_item.addClass('moving')
        current_over = $(document.elementFromPoint(e.pageX - window.scrollX, e.pageY - window.scrollY));
        self.ghoster = $('<div id="employee_ghost"> &nbsp; </div>').appendTo(self.jaxer).css({top: e.pageY - 10, left: e.pageX - 10});
        self.ghoster.html('<strong> ' + current_item.children('td:first').html() + ' </strong>');
      }
    } else {
      self.ghoster.css({top: e.pageY + 20, left: e.pageX + 20});
      new_current_over = $(document.elementFromPoint(e.pageX - window.scrollX, e.pageY - window.scrollY));
      if (current_over[0] != new_current_over[0]) {
        current_over = new_current_over;
        if (current_over.is('td') && current_over.parent().parent().hasClass('sortable')) {
          if (new_insert) {new_insert.remove();}
          new_insert = $('<tr><th colspan="5" class="inserted"> ' + current_item.children('td:first').html() + ' </th></tr>').insertBefore(current_over.parent());
        } else if (!current_over.hasClass('inserted')) {
          new_insert.remove();
        }
      }
      self.ghoster.css({top: e.pageY - 10, left: e.pageX - 5});
    }
  }
  
  this.end_employee_order = function(e) {
    if (start_move) {
      self.ghoster.remove();
      if (new_insert) {
        new_insert.replaceWith(current_item);
        self.items.removeClass('alt moving');
        Table_styled(false, self.items.parent().parent());
        for (var i = 0; i < self.items.length; i++) {
          item_order_list[i] = self.items.parent().children().eq(i).children('td:first').children('span.ider').html();
        }
        $.ajax({
          url: self.root.attr('action').replace('edit', 'order-items'),
          type: "POST",
          data: {'item_order' : item_order_list.join(',')},
          async: false
        });
        //console.log(item_order_list.join(','));
      } else {
        current_item.removeClass('moving');
      }
    }
    start_move = false;
    $(document.body).unbind('mousemove', self.employee_order);
  }

  this.insert_data = function(data) {
    self.root.find('input[name=name]').val(data['name']);
    self.root.find('input[name=phone]').val(data['phonedirect']);
    self.root.find('input[name=title]').val(data['title']);
    self.root.find('input[name=extension]').val(data['phoneext']);
    self.root.find('input[name=emailprefix]').val(data['emailPrefix']);
    self.root.find('input[name=position]').val(data['position']);
  }
  
  return this;
}

function Product_update(product_list) {
  var self = this;
  Updater.call(this, product_list);
  
  this.item_type = 'product';
  
  this.file_upload = new File_upload(this.root.find('div.fileupload_holder span'));
  this.file_upload.upload_button.bind('swf_loaded', function() {
    self.file_upload.upload_limit(1);
    self.file_upload.image_button('', [108,100]);
    self.file_upload.set_post_paramaters({
      'file_name' : self.root.find('input[name=name]').val(),
      'file_category' : self.item_type
    });
  });
  this.file_upload.upload_button.bind('dialog_close', function() {
    var temp_file_name = (self.root.find('input[name=name]').val()).toLowerCase();
    self.file_upload.set_post_paramaters({
      'file_name' : temp_file_name,
      'file_category' : self.item_type
    });
  });
  this.file_upload.upload_button.bind('upload_success', function(e, server_response) {
    self.root.find('input[name=fileName]').val(server_response);
    var uncache_image = '?new_image=' + new Date().getTime();
    self.root.find('div.fileupload_holder img').attr('src', '/media/uploads/' + self.item_type + '/' + server_response + uncache_image);
  });
  this.file_upload.start_up();
  //console.log(this.file_upload);
  
  var parent_start_up = this.start_up;
  this.start_up = function() {
    parent_start_up();
    self.root.find('ul li').bind('click', self.select_tags);
  }
  
  var parent_clear_form = this.clear_form;
  this.clear_form = function() {
    self.root.find('ul li').removeClass('active');
    return parent_clear_form();
  }

  this.select_tags = function(e) {
    var me = $(e.currentTarget);
    if (me.hasClass('active')) {
      me.children('input').val('0');
      me.removeClass('active');
    } else {
      var field_name = me.children('img').attr('src').replace('/media/icons/product/', '').replace('.png', '');
      me.append('<input type="hidden" name="' + field_name + '" value="1" />');
      me.addClass('active');
    }
  }
    
  this.insert_data = function(data) {
    self.root.find('input[name=name]').val(data['displayName']);
    self.root.find('textarea[name=description]').val(data['description']);
    self.root.find('input[name=webaddr]').val(data['webaddr']);
    self.root.find('input[name=fileName]').val(data['fileName']);
    if (data['fileName'] != '') {
      self.root.find('div.fileupload_holder img').attr('src', '/media/uploads/' + self.item_type + '/' + data['fileName']);
    } else {
      self.root.find('div.fileupload_holder img').attr('src', '/media/fpo/product-image-not-available.png');
    }
    var key = '';
    var tags = self.root.find('ul li');
    for (key in data) {
      if (key == 'displayName' || key == 'description' || key == 'webaddr' || key == 'active' || key == 'officeId' || key == 'id' || key == 'fileName') {continue;}
      if (Number(key) || key == '0') { continue; }
      if (data[key] != '0') {
        for (var i = 0; i < tags.length; i++) {
          if (tags.eq(i).children('img').attr('src').match(key)) {
            tags.eq(i).trigger('click');
          }
        }
      }
    }
  }
  
  return this;
}

function Sample_update(sample_grid) {
  var self = this;
  Updater.call(this, sample_grid);
  
  this.item_type = 'sample';
  
  this.sample = sample_grid;
  this.sample.find('a').unbind('click');
  this.sample.find('a').bind('click', function(e) {
    e.preventDefault();
    $(e.currentTarget).parent().trigger('click');
    return false;
  });
  
  this.file_upload = new File_upload(this.root.find('div.fileupload_holder span'));
  this.file_upload.upload_button.bind('swf_loaded', function() {
    self.file_upload.upload_limit(1);
    self.file_upload.image_button('', [106,98]);
  });
  this.file_upload.upload_button.bind('dialog_close', function() {
    var temp_file_name = self.root.find('input[name=name]').val() + '-' + self.root.find('input[name=companyname]').val();
    temp_file_name = temp_file_name.replace(/ /g, '-').toLowerCase()
    self.file_upload.set_post_paramaters({
      'file_name' : temp_file_name,
      'file_category' : self.item_type
    });
  });
  this.file_upload.upload_button.bind('upload_success', function(e, server_response) {
    self.root.find('input[name=fileName]').val(server_response);
    var uncache_image = '?new_image=' + new Date().getTime();
    self.root.find('div.fileupload_holder img').attr('src', '/media/uploads/' + self.item_type + '/' + server_response + uncache_image);
  });
  this.file_upload.start_up();

  
  this.insert_data = function(data) {
    self.root.find('input[name=name]').val(data['name']);
    self.root.find('textarea[name=description]').val(data['description']);
    self.root.find('input[name=webaddr]').val(data['webaddr']);
    self.root.find('input[name=companyname]').val(data['companyName']);
    self.root.find('textarea[name=sample_location]').val(data['sampleLocation']);
    self.root.find('input[name=oasis_id]').val(data['oasisId']);
    self.root.find('input[name=fileName]').val(data['fileName']);
    if (data['fileName'] != '') {
      self.root.find('div.fileupload_holder img').attr('src', '/media/uploads/' + self.item_type + '/' + data['fileName']);
    } else {
      self.root.find('div.fileupload_holder img').attr('src', '/media/fpo/product-image-not-available.png');
    }
  }
  
  return this;
}

function Home_update(sample_grid) {
  var self = this;
  
  this.number_of_files = 0;
  
  this.start_up = function() {
    
  }
  
  this.file_upload = new File_upload(this.root.find('div.fileupload_holder span'));
  this.file_upload.upload_button.bind('swf_loaded', function() {
    self.file_upload.upload_limit(10);
    self.file_upload.image_button('', [106,98]);
  });
  this.file_upload.upload_button.bind('dialog_close', function() {
    var temp_file_name = self.root.find('input[name=name]').val() + '-' + self.root.find('input[name=companyname]').val();
    temp_file_name = temp_file_name.replace(/ /g, '-').toLowerCase()
    self.file_upload.set_post_paramaters({
      'file_category' : 'home',
      'new_height' : 370,
      'new_width' : 960,
      'crop_image' : true
    });
  });
  this.file_upload.upload_button.bind('upload_success', function(e, server_response) {
    if (self.number_of_files == 0) {
      self.root.find('input[name=file_names]').val(server_response);
    } else {
      self.root.find('input[name=file_names]').val(self.root.find('input[name=file_names]').val() + '###' + server_response);
    }
    var uncache_image = '?new_image=' + new Date().getTime();
    if (self.number_of_files == 0) {
       self.root.find('div.fileupload_holder img').remove();
       self.root.find('div.fileupload_holder').prepend('<img class="framed" src="/media/uploads/home/' + server_response + uncache_image + ' />');
    } else {
       self.root.find('div.fileupload_holder').prepend('<img class="framed" src="/media/uploads/home/' + server_response + uncache_image + ' />');
    }
    self.number_of_files++;
  });
  
  this.file_upload.upload_button.bind('uploads_done', function(e, server_response) {
    self.number_of_files = 0;
  });
  
  this.file_upload.start_up();
  
  return this;
}

function User_update(user_list) {
  var self = this;
  
  Updater.call(this, user_list);

  this.item_type = 'user';

  this.insert_data = function(data) {
    self.root.find('input[name=username]').val(data['username']);
    self.root.find('select[name=level]').val(data['level']);
  }
  
  return this;
}

function Dummy() {
  $(document.body).trigger('google_maps_load');
}
function Location_finder() {
  var self = this;

  this.g_map = this.root[0];
  this.geocodes = new Array();
  this.markers = new Array();

	this.phys_lat = Number(this.root.children('span.latt').html());
	this.phys_lng = Number(this.root.children('span.long').html());
	this.google_map_link = this.root.children('span.map_link').html();

  this.start_up = function() {
    $.ajax({
      url: 'http://maps.google.com/maps/api/js?v=3.1&sensor=false&callback=Dummy',
      dataType: 'script',
      success: function() {
        $(document.body).bind('google_maps_load', self.build_map);
      }
    });
    $(window).bind('unload', self.destroy_map);
  }

  this.destroy_map = function() {
    if ($.browser.msie && $.browser.version < 8) {
      google = null;
    } else {
      google.maps.Unload();
    }
  }

  this.build_map = function() {
    var myOptions = {
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      scrollwheel: false,
      backgroundColor: 'white',
      mapTypeControl: false
    };
    self.g_map = new google.maps.Map(self.g_map, myOptions);
    self.geocodes[0] = new google.maps.LatLng(self.phys_lat, self.phys_lng)
    self.markers[0] = new google.maps.Marker({
      position: self.geocodes[0],
      map: self.g_map,
      title: "Pacific Lighting Systems"
    });
    self.g_map.setCenter(self.geocodes[0], 11);
    google.maps.event.addListener(self.markers[0], 'click', function() {
      window.open(self.google_map_link, '_blank');
    });
  }
  
  return this;
}

