/*
  Author: Moises Beltran
  About: Used to dynamically replace breadcrumb based on the referrer
*/
var AlternateBreadcrumb = Base.extend({
  /* Holds url */
  top_level_url: '',
  /* Holds Default breadcrumb */
  default_breadcrumb: '', 
  all_categories: null,
  breadcrumb_names: {},
  all_crumbs: null,
  main_breadcrumb: null, /* expect {url: 'http://www.site.com/categories/html', name: 'Category Name'}*/
  ic: null,
  doc_referrer: null,
  constructor: function( tlu ){
    this.doc_referrer = (tlu ? tlu : document.referrer);
    this.top_level_url = this.doc_referrer.replace(".html", "");
    this.all_categories = this.top_level_url.split("/")
    this.all_crumbs = Array();
    this.ic = new TagCreator(); //initialize tag creator
  },
  init: function(){
    if(this.doc_referrer.length > 0 && this.doc_referrer.indexOf("categories") != -1){
      if(this.all_categories[ this.all_categories.length - 1] == "categories"){
        document.write(this.default_breadcrumb);
      }
      else{
        this.construct_categories_and_write();
      }
    }
    else{
      document.write(this.default_breadcrumb);
    }
  },
  get_category_name: function(key){
    return this.breadcrumb_names[key];
  },  
  construct_categories: function(){
    this.all_crumbs = Array( this.ic.li_a( this.main_breadcrumb['name'],{ href: this.main_breadcrumb['name']} ,{})  );
    crumbs = Array();
    for(i= this.all_categories.length - 1; i >= 0; --i){
      if(this.all_categories[i] == "categories") break;
      cname = this.get_category_name( this.all_categories[i] );
      link_options = {href: this.top_level_url+".html" };
      li_options = {};
      if( i == (this.all_categories.length) - 1){
        li_options['class'] = 'current';
        link_options['class'] = 'current';
      }
      /* Check for special categories */
      /* TODO: apply same logic to top_sellers and new_arrivals? */
      if( this.all_categories[i] == "view_all" && this.all_categories[i - 1]){
        cname = cname + ": " + this.breadcrumb_names[ this.all_categories[i - 1] ];
      }
      crumbs.push(  this.ic.li_a( cname,link_options ,li_options)  );
      this.top_level_url = this.top_level_url.replace("/"+this.all_categories[i],"");
    }
    crumbs = crumbs.reverse();
    this.all_crumbs.push(crumbs.join(""));
  },
  construct_categories_and_write: function(){
    this.construct_categories();
    document.write( this.all_crumbs.join("") );
  },
  enable_logger: true,
  logger: function(s){
    if( typeof console == "object" && this.enable_logger == true){
      console.log(s)
    }
  }
});