var BendicksApp = {
  init : function() {
    this.replace_menu();
    this.track_external_links();
    this.init_faq();
    this.init_countries();
    this.init_tabs();
    this.init_page_history();
    this.init_accordion();
    this.c10000_fi_layer();
    this.c10000_ba_switch();
  },
  // initializes the country selection on the "buy our products in store" page
  init_countries: function() {
    $(".switchitem").hide();
  },
  // initializes the FAQ (hide not selected items)
  init_faq : function () {
    $(".faqitem").hide();
    window.setTimeout(function () {
      $(".faqwrapper img").css({
        visibility: 'hidden'
      });
      }, 20);
  },
  // initializes the page history function (hash navigation)
  init_page_history : function() {
    $.historyInit(this.pageload, "jquery_history.html");
    $("a[rel='history']").click(function () {
      var hash = this.href;
      hash = hash.replace(/^.*#/, '');
      $.historyLoad(hash);
      this.blur();
      return false;
    });
  },
  // Initializes the tabs for nutrition facts etc on the product pages
  init_tabs : function() {
    $("div#subcontent .tab").hide();
    $("#b11110 div#content, #b11120 div#content, #b11130 div#content, #b11210 div#content, #b11220 div#content, #b11230 div#content, #b12100 div#content, #b12200 div#content, #b12300 div#content, #b13000 div#content").css({
      height: '470px'
    });
  },
  // Initializes the accordion on c10000
  init_accordion : function() {
    var id = $('#accordion > div.active').attr("id");
    if (id == undefined) {
      id = 'our-story';
    }
    BendicksApp.accordion_to(id);
  },
  // Switches the accordion to the given ID
  accordion_to : function(id) {
    BendicksApp.track(window.location.pathname + "/" + id, $('meta[name=WT.ti]').attr("content") + " - " + id);
    
    $('#accordion > div').removeClass("active");
    var current = $('#' + id).addClass("active");
    var found_active = false;
    $('#accordion > div').each(function() {
      var elem = $(this);
      var old_pos = elem.css("left");
      var new_pos = (found_active ? elem.attr("data-right") : elem.attr("data-left")) + "px";
      if (new_pos != old_pos) {
        if (old_pos == "0px") {
          elem.css({'left' : new_pos });
        }
        else {
          elem.animate({'left' : new_pos});
        }
      }
      
      if (elem.hasClass("active")) {
        found_active = true;
      }
    });
  },
  // Switch between "A british affair" & "The royal warrant"
  c10000_ba_switch : function() {
    $('#c10000 #a-british-affair p:not(.first)').hide();
    $('#c10000 #a-british-affair div.tab').css({"cursor" : 'pointer'}).click(function() {
      var me = $(this);
      var other = $('#c10000 #a-british-affair div.tab:not(#'+ me.attr('id') +')');
      me.find('h1 .hl').attr("src", me.find('h1 .hl').attr("src").replace(/-off\.png/, "-on.png"));
      other.find('h1 .hl').attr("src", other.find('h1 .hl').attr("src").replace(/-on\.png/, "-off.png"));
      me.find('h1 .arrow').attr('src', '/images/arrow-down.png');
      other.find('h1 .arrow').attr("src", "/images/arrow-right.png");
      me.addClass("touched active");
      other.addClass("touched").removeClass("active");
      me.find("p").show();
      other.find('p').hide();
      me.css({'cursor' : 'default'});
      other.css({'cursor' : 'pointer'});
    });
    // Image caching
    $('<img src="/images/c10000/a-british-affair/hl-british-off.png" alt="" /><img src="/images/c10000/a-british-affair/hl-royal-off.png" alt="" />');
  },
  // Shows the layer in c10000 "Finest Ingredients"
  c10000_fi_layer : function() {
    $('#c10000 #cocoa95').hover(function() {
      $('#c10000 .darkening').css({'display' : 'block', 'opacity' : '0.0'}).fadeTo(500, 0.5);
      $('#c10000 .box').fadeIn(500);
    }, function() {
      $('#c10000 .darkening').fadeOut(500);
      $('#c10000 .box').fadeOut(500);
    });
  },
  // Loads the specific tab, if the hash of the url changes or is set initial
  pageload : function(hash) {
    var link;
    if (hash) {
      if (hash.match(/^faq[0-9]+$/)) {
        $("div.active").removeClass("active");
        $("div.faqwrapper img").css({
          visibility: 'hidden'
        });
        $("div.faqwrapper .faqlink").css({
          backgroundImage: "url(/images/arrow-right.png)"
        }, 100);
        $(".faqitem:visible:not(#"+ hash +"-body)").slideUp();
        link = $(".faqlink[data-href]");
        link.attr("href", link.attr("data-href"));
        link.removeAttr("data-href");
        $("#"+ hash +"-body").slideDown();
        $("#"+ hash +"-wrapper").addClass("active");
        window.setTimeout(function() {
          $("#"+ hash +"-wrapper img").css({
            visibility: 'visible'
          });
        }, 100);
        $("#"+ hash +"-wrapper .faqlink").css({
          backgroundImage: "url(/images/arrow-down.png)"
        });
        link = $(".faqlink[href=#" + hash + "]");
        link.attr("data-href", link.attr("href"));
        link.attr("href", "#faq0");
        if (hash != "faq0") {
          var wt_ti = $("body").attr("id").toUpperCase() + " - " + hash.toUpperCase() + " - "+ $("#"+ hash +"-wrapper .faqlink").text().replace(/%/, " percent").replace(/[^a-zA-Z0-9 ?]/g, "");
          BendicksApp.track(window.location.pathname + "/" + hash, wt_ti);
        }
      }
      else if (hash.match(/^acc-.+$/)) {
        BendicksApp.accordion_to(hash.substr(4));
      }
      else if (hash == "germany" || hash == "sweden" || hash == "gibraltar" || hash == "nocountry") {
        $("div.active a.switchlink").css({
          backgroundImage: "url(/images/arrow-right.png)"
        });
        $("div.active").removeClass("active");
        $(".switchitem:visible:not(#"+ hash +"-body)").slideUp();
        link = $(".switchlink[data-href]");
        link.attr("href", link.attr("data-href"));
        link.removeAttr("data-href");
        $("#"+ hash +"-body").slideDown();
        $("#"+ hash +"-wrapper").addClass("active");
        $("div.active a.switchlink").css({
          backgroundImage: "url(/images/arrow-down.png)"
        });
        link = $(".switchlink[href=#" + hash + "]");
        link.attr("data-href", link.attr("href"));
        link.attr("href", "#nocountry");
      }
      else if (hash == "nutritional-info" || hash == "gda" || hash == "ingredients" || hash == "notab") {
        $(".tab").stop(true, true);
        $("div#subcontent a.active").removeClass("active");
        $(".tab:visible:not(#"+ hash +"-tab)").hide();
        link = $(".tablink[data-href]");
        link.attr("href", link.attr("data-href"));
        link.removeAttr("data-href");
        $("#"+ hash +"-tab").slideDown();
        $("a[href=#"+ hash +"]").addClass("active");
        link = $("a[href=#" + hash + "]");
        link.attr("data-href", link.attr("href"));
        link.attr("href", "#notab");
        //$("div#subcontent a img").attr("src", "/images/arrow-right.png");
        //$("div#subcontent a.active img").attr("src", "/images/arrow-down.png");
        if (hash == "notab") {
          $("#content").animate({
            height: '470px'
          });
        }
        else {
          var wt_ti = hash.toUpperCase();
          if (wt_ti == "NUTRITIONAL-INFO") {
            wt_ti = "Nutritional Info";
          }
          else if (wt_ti == "INGREDIENTS") {
            wt_ti = "Ingredients";
          }
          wt_ti = $("body").attr("id").toUpperCase() + " - " + wt_ti;
          BendicksApp.track(window.location.pathname + "/" + hash, wt_ti);
          $("a[href=#"+ hash +"]").attr("src", "/images/arrow-down.png");
          $("#content").animate({
            height: '700px'
          });
        }
      }
    }
  },
  // Replaces the HTML menu with grafics
  replace_menu : function() {
    if ($.browser != "msie" && $.browser.version != "6.0") {
      $('#navigation a, #c10000 .next').each(function() {
        var itm = $(this);
        if (itm.hasClass('active')) {
          itm.html('<img src="/images/menu/' + itm.text().toLowerCase().replace(/[^a-z0-9]/g, "-") + '-on.png" alt="' + itm.text() + '" title="">');
        }
        else {
          itm.html('<img src="/images/menu/' + itm.text().toLowerCase().replace(/[^a-z0-9]/g, "-") + '-off.png" alt="' + itm.text() + '" title="">');
          itm.hover(
            function() {
              $(this).children()[0].src = $(this).children()[0].src.replace(/-off\.png$/, "-on.png");
            },
            function() {
              $(this).children()[0].src = $(this).children()[0].src.replace(/-on\.png$/, "-off.png");
            }
          );
        }
      });
      $('#navi3 a').each(function() {
        var itm = $(this);
        if (itm.hasClass('active')) {
          itm.html('<img src="/images/menu/' + itm.text().toLowerCase().replace(/[^a-z0-9]/g, "-") + '-on.png" alt="' + itm.text() + '" title="">');
        }
        else {
          itm.html('<img src="/images/menu/' + itm.text().toLowerCase().replace(/[^a-z0-9]/g, "-") + '-off.png" alt="' + itm.text() + '" title="">');
          itm.hover(
            function() {
              $(this).children()[0].src = $(this).children()[0].src.replace(/-off\.png$/, "-on.png");
            },
            function() {
              $(this).children()[0].src = $(this).children()[0].src.replace(/-on\.png$/, "-off.png");
            }
          );
        }
      });
      $('#subcontent a').each(function() {
        var itm = $(this);
        if (itm.hasClass('active')) {
          itm.html('<img src="/images/menu/' + itm.text().toLowerCase().replace(/[^a-z0-9]/g, "-") + '-on.png" alt="' + itm.text() + '" title="">');
        }
        else {
          itm.html('<img src="/images/menu/' + itm.text().toLowerCase().replace(/[^a-z0-9]/g, "-") + '-off.png" alt="' + itm.text() + '" title="">');
          itm.hover(
            function() {
              $(this).children()[0].src = $(this).children()[0].src.replace(/-off\.png$/, "-on.png");
            },
            function() {
              $(this).children()[0].src = $(this).children()[0].src.replace(/-on\.png$/, "-off.png");
            }
          );
        }
      });
      $('#d11000 a#back, #d10000 a#online, #d11000 a#online, a#store, #j10000 #submit a').each(function() {
        var itm = $(this);
        if (itm.hasClass('active')) {
          itm.html('<img src="/images/menu/' + itm.text().toLowerCase().replace(/[^a-z0-9]/g, "-") + '-on.png" alt="' + itm.text() + '" title="">');
        }
        else {
          itm.html('<img src="/images/menu/' + itm.text().toLowerCase().replace(/[^a-z0-9]/g, "-") + '-off.png" alt="' + itm.text() + '" title="">');
          itm.hover(
            function() {
              $(this).children()[0].src = $(this).children()[0].src.replace(/-off\.png$/, "-on.png");
            },
            function() {
              $(this).children()[0].src = $(this).children()[0].src.replace(/-on\.png$/, "-off.png");
            }
          );
        }
      });
      $('#b11000 #boxed_button, #b11000 #tube_button, #b12000 #button_collection, #b12000 #button_crisps, #b12000 #button_victorian').each(function() {
        var itm = $(this);
        if (itm.hasClass('active')) {
          itm.html('<img src="/images/menu/' + itm.text().toLowerCase().replace(/[^a-z0-9]/g, "-") + '-on.png" alt="' + itm.text() + '" title="">');
        }
        else {
          itm.html('<img src="/images/menu/' + itm.text().toLowerCase().replace(/[^a-z0-9]/g, "-") + '-off.png" alt="' + itm.text() + '" title="">');
          itm.hover(
            function() {
              $(this).children()[0].src = $(this).children()[0].src.replace(/-off\.png$/, "-on.png");
            },
            function() {
              $(this).children()[0].src = $(this).children()[0].src.replace(/-on\.png$/, "-off.png");
            }
          );
        }
      });
      $('#d11000 .switchlink').each(function() {
        var itm = $(this);
        if (itm.hasClass('active')) {
          itm.html('<img src="/images/menu/' + itm.text().toLowerCase().replace(/[^a-z0-9]/g, "-") + '.png" alt="' + itm.text() + '" title="">');
        }
        else {
          itm.html('<img src="/images/menu/' + itm.text().toLowerCase().replace(/[^a-z0-9]/g, "-") + '.png" alt="' + itm.text() + '" title="">');
          itm.hover(
            function() {
              $(this).children()[0].src = $(this).children()[0].src.replace(/-off\.png$/, ".png");
            },
            function() {
              $(this).children()[0].src = $(this).children()[0].src.replace(/-on\.png$/, ".png");
            }
          );
        }
      });
      $('.tablink').append('<span>&nbsp;</span>');
      $('.active span').addClass('hi');
    }
  },
  // Issues a tracking call in production and logs everywhere else to to console (if available).
  track : function(uri, title) {
    if (typeof dcsMultiTrack == "function") {
      dcsMultiTrack('DCS.dcsuri', uri, 'WT.ti', title);
    }
    else if (typeof console == "object") {
      console.log("Tracked title: " + title);
    }
  },
  // Adds listeners to all external links for tracking calls.
  track_external_links : function() {
    $("a[href^=http://]").click(function () {
      var wt_ti = "External Link";
      if (this.href.search(/^http:\/\/www\.facebook\.com/) != -1) {
        wt_ti = "Facebook Link";
      }
      else if (this.href.search(/^http:\/\/www\.chocolatesdirect\.co\.uk/) != -1) {
        wt_ti = "Ext. Buy Online Link";
      }
      BendicksApp.track('/link/'+this.href.substr(7), wt_ti)
      return true;
    });
  }
}

$(document).ready(function() {
  BendicksApp.init();
});
