$(document).ready(function() {
  hideBackground();
  buildNavMenu();
  buildSearchBox();
  hideCategories();
  googleAnalytics();
});



/******************* Google analytics ************************************/
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));

function googleAnalytics() {
  if (top.addEventListener) { 
    top.addEventListener("load",_gaLoad,false); 
  } else if (top.attachEvent) { 
    top.attachEvent("onload",_gaLoad); 
  }
}


function _gaLoad () { 
  try {
    var pageTracker = _gat._getTracker("UA-3739507-3");
    pageTracker._trackPageview();
  } catch(err) {}
} 





/******************* Global vars ****************************************/
var host = window.location.host.replace("sslrelay.com", "artistsuppliesdirect.co.uk");
var baseUrl = window.location.protocol + "//" + host;
var secureUrl = "https://" + host;
var nonSecureUrl = "http://" + host;




/******************* Css changes ****************************************/

// Removes the standard background image
function hideBackground() {
  $('#main_body').css('background-image', 'none');
}




/******************** Extended navigation menu **************************/

function buildNavMenu() {
  productsMenuItem().append(menuContainerStart);
  appendCats();
  productsMenuItem().append(menuContainerEnd);
}

// appends new category menu items to the selected navigation menu item (productsMenuItem)()
function appendCats() {	
  productsMenuItem().append(menuListStart_1);

  // for each category
  $.each(jsonCats.Categories, function() {

    // display current category
    productsMenuItem().append(menuItemStart_1 + getCatUrl(this) + menuItemMiddle_1 + this.name + menuItemEnd_1);

    // display sub categories if applicable
    if (shouldDisplaySubCats(this))
      $.each(this.Subcats, function() {
        productsMenuItem().append(menuItemStart_2 + getCatUrl(this) + menuItemMiddle_2 + this.name + menuItemEnd_2);
      });

  });

  productsMenuItem().append(menuListEnd_1);
}

// returns the full url to the compareCat category parameter
function getCatUrl(compareCat) {
  return catBaseUrl + compareCat.id + compareCat.url;
}

// returns true if the compareCat category parameter is to have its sub-categories displayed
// checks if cat is either listed in breadcrumb trail, if it is currently displayed or if it is set to expand and if any subcats actually exist
function shouldDisplaySubCats(compareCat) {
  return (isInBreadcrumb(compareCat) || isCurrentlyDisplayedCat(compareCat) || (compareCat.alwaysExpand != null && compareCat.alwaysExpand == "1")) && 
	  compareCat.Subcats != null && compareCat.Subcats.length > 0;
}

// returns true if the current page is the same as the compareCat category parameter
function isCurrentlyDisplayedCat(compareCat) {
  var result = false;

  if (window.location.pathname == getCatUrl(compareCat).stripUrlHost())
    result = true;

  return result;
}

// returns true if the compareCat category parameter appears in the breadcrumb trail
function isInBreadcrumb(compareCat) {
  var result = false;

  // for each hyperlink contained in the overview breadcrumb
  $('#v2_shop_productoverview_breadcrumb_container a').each(function() {
    if (this.href.stripUrlHost().beginsWith(getCatUrl(compareCat).stripUrlHost()))
      result = true;
  });

  // for each hyperlink contained in the product detailbreadcrumb
  $('#v1_es_breadcrumb_container a').each(function() {
    if (this.href.stripUrlHost().beginsWith(getCatUrl(compareCat).stripUrlHost()))
      result = true;
  });

  return result;
}

// strips the protocol and host portion of a given (string) url
String.prototype.stripUrlHost = function() {
  var url = this;

  if (url.beginsWith(baseUrl))
    url = url.substring(baseUrl.length, url.length);

  return url;
}

// returns true if the given string starts with the parameter value
String.prototype.beginsWith = function(compare) { 
  return (compare.toLowerCase() == this.substring(0, compare.length).toLowerCase());  
}

// returns the (products) menu item to which the new menu items will be appended
function productsMenuItem() {
  return $('#main_nav_list').find('li').filter(':contains(Products)');
}

var menuContainerStart = '<div class="sub_nav_container">';
var menuContainerEnd = '</div>';

var menuListStart_1 = '<ul class="sub_nav_list" id="sub_nav_list1">';
var menuListEnd_1 = '</ul>';

var menuItemStart_1 = '<li><a class="sub_nav_item" id="sni2" href="';
var menuItemMiddle_1 = '">';
var menuItemEnd_1 = '</a></li>';

var menuItemStart_2 = '<li><a class="sub_nav_item" id="sni2" href="';
var menuItemMiddle_2 = '">&nbsp;&nbsp;&nbsp;&nbsp;';
var menuItemEnd_2 = '</a></li>';

var catFolder = "/shop/category_";
var catBaseUrl = nonSecureUrl + catFolder;

var jsonCats = { 
  "Categories": [
    {"name": "Mount & Foam Board", "id": "300", "url": "/Mount%2C-Backing-and-Foamboard.html", "alwaysExpand": "0",
      "Subcats": [
		{name: "Foamboard", id: "300100", "url": "/Daler-Rowney-Foamboard.html"},
		{name: "Mount and backing board", id: "300200", "url": "/Mount-and-Backing-Board.html"}
	  ]},
    {"name": "Brushes", "id": "700", "url": "/Brushes.html", "alwaysExpand": "0",
      "Subcats": [
		{name: "Acrylic", id: "700100", "url": "/Acrylic-Brushes.html"},
		{name: "Oil", id: "700200", "url": "/Oil-Brushes.html"},
		{name: "Watercolour", id: "700300", "url": "/Watercolour-Brushes.html"}
	  ]},
    {"name": "Canvas", "id": "200", "url": "/Canvas.html", "alwaysExpand": "0",
      "Subcats": [
		{name: "3D Stretched", id: "200100", "url": "/Daler-Rowney-3D-Stretched-Canvas-Packs-Of-4.html"},
		{name: "Premium Stretched", id: "200200", "url": "/Daler-Rowney-Premium-Stretched-Canvas-Packs-Of-6.html"}
	  ]},
    {"name": "Easels", "id": "400", "url": "/Easels.html"},
    {"name": "Paint", "id": "100", "url": "/Paint.html", "alwaysExpand": "0",
      "Subcats": [
		{name: "Acrylic 120ml Tubes", id: "100100", "url": "/Daler-Rowney-Acrylic-120ml-Paint-Tubes.html"},
		{name: "System-3 250ml Pots", id: "100200", "url": "/Daler-Rowney-System-3-250ml-Paint-Pots.html"},
		{name: "System-3 75ml Tubes", id: "100300", "url": "/Daler-Rowney-System-3-75ml-Paint-Tubes.html"},
		{name: "Georgian Oil 75ml Tubes", id: "100400", "url": "/Daler-Rowney-Georgian-Oil-75ml-Tube.html"},
		{name: "Artists' Watercolour 5ml Tubes", id: "100500", "url": "/Daler-Rowney-Artists'-Watercolour-5ml-Paint-Tube.html"}
      ]},
    {"name": "Palettes", "id": "500", "url": "/Palettes.html"},
    {"name": "Portfolio Cases & Sleeves", "id": "600", "url": "/Portfolio-Cases-and-Sleeves.html", "alwaysExpand": "0",
      "Subcats": [
		{name: "Artcases", id: "600100", "url": "/Daler-Rowney-Artcase.html"},
		{name: "Portfolio Sleeves", id: "600200", "url": "/Portfolio-Sleeves.html"}
	  ]},
    {"name": "Daler Rowney Simply Range", "id": "900", "url": "/Daler-Rowney-Simply-Range.html"},
    {"name": "Paper & Pads", "id": "800", "url": "/Paper-And-Pads.html"},
    {"name": "Clearance Lines", "id": "1000", "url": "/Clearance-Lines.html"}
  ]
};

http://artistsuppliesdirect.co.uk/shop/category_800/Paper-And-Pads.html?shop_param=cid%3D%26

/******************** Search box in header **************************/

// appends the search box to the body element
function buildSearchBox() {
  body().append(searchBoxDivStart +
    searchBoxFormStart + 
    searchBox +
    searchBoxButton +
    searchBoxCategory +
    searchBoxFormEnd +
    searchBoxDivEnd);
}

// finds body element
function body() {
  return $('body');
}

var searchBoxDivStart = '<div class="content" style="position: absolute; top: 102px; left: 747px;">';
var searchBoxDivEnd = '</div>';

var searchBoxButton = '&nbsp;<input type="submit" name="_shop_itemsearch_trigger_start" id="forum_search_button" value="Search">';
var searchBoxCategory = '<input type="hidden" name="_shop_itemsearch_category" id="_shop_itemsearch_category" value="" />';
var searchBox = '<input type="text" name="_shop_itemsearch_query" id="_shop_itemsearch_query" maxlength="50" size="18">';

var searchBoxFormStart = '<form method="post" action="' + nonSecureUrl + '/shop/catalog/search?shop_param=">';
var searchBoxFormEnd = '</form>';






/******************** Category hiding **************************/


var rightArrow = 'arrow_right.png';
var downArrow = 'arrow_down.png';
var scriptLocation = window.location.protocol + '//www.grahamhoyle.co.uk/ArtistSuppliesDirect/';

function hideCategories() {
  var table = furtherCategories();

  if (table.length > 0 && productCount() > 0)
    flipVisible(table);
}

function addArrow(table) {
  var arrow = header(table).find('img');
  var arrowName = null;

  if (firstContentRow(table).is(':hidden'))
    arrowName = scriptLocation + downArrow;
  else
    arrowName = scriptLocation + rightArrow;

  if (arrow.length == 0)
    header(table).prepend(buildArrow(arrowName)).live('click', function() {
      flipVisible(table);
    });
  else
    arrow.attr('src', arrowName);
}

// builds arrow
function buildArrow(arrowName) {
  return '<img style="cursor: pointer; vertical-align: middle;" src="' + arrowName + '" />&nbsp;';
}

// reverses visibility of each non-th table row
function flipVisible(table) {
  allRows(table).each(function() {
    $(this).toggle();
  });

  addArrow(table);
}

// selects table header
function header(table) {
  return table.find('th');
}

// selects selects first non-th row from table
function firstContentRow(table) {
  return allRows(table).eq(0);
}

// selects all rows except th
function allRows(table) {
  return table.find('tr:not(:has(th))');
}

// finds further categories element
function furtherCategories() {
  return $('.v2_shop_productoverview_category_list');
}

// returns the number of products displayed on the page
function productCount(){
  return $('.v2_shop_productoverview_article_list').find('.v2_shop_productoverview_article_desc').size();
}
