/***********************************************************************************************************************************
  AJAX OBJECT CONSTRUCTOR
***********************************************************************************************************************************/
// added to let theme know that this js is actually present in a page:
var ajxEngine = true;
// ajax object creation
function getHTTPObject() {
 var xhr = false;
 if (window.XMLHttpRequest) {
  xhr = new XMLHttpRequest(); 
 } else if (window.ActiveXObject) { // IE
  try {
   xhr = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
   try {
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (e) { // catch Mac IE 5 here
    xhr = false;
   }
  }
 }
 return xhr;
}
/* make a call via ajax */
function ajaxCall(reqPage, reqType) {
 // start the ajax object
 var request = getHTTPObject();
 if (request) {
  request.onreadystatechange = function() {
   // on the return, parse what comes back:
   if (reqType == 'collection') {
    insertCollection(request);
   } else if (reqType == 'sizeguide') {
    insertChart(request);
   } else {
    insertPage(request);
   }
  };
  // add to or create query string
  var ajaxPair = sortChars(reqPage);
  request.open("GET", reqPage + ajaxPair, true);
  request.send(null);
  return true;
 } else {
  return false;
 } 
}
// add '&' or '?' to query string for ajax calls - pass in the href
function sortChars(pageRef) {
 var rtnChar = '&';
 if (pageRef.indexOf('?') == -1) {
  rtnChar = '?';
 }
 rtnChar += 'ajax=true';
 return rtnChar;
}
// if the window has been scrolled vertically, move the panel appropriately:
function checkScroll(el) {
 var dist = window.getScrollTop();
 if (dist > el.getStyle('top').toInt()) {
  el.setStyle('top', dist);
 }
}
//***********************************************************************************************************************************//
//  PRODUCT PANEL - call, fade in, display and close
//***********************************************************************************************************************************//
/* fetch a PRODUCT - start with page fade: */
//Var necessary for webtrends to spoof a line in the log with the correct HREF
strWebtrendsHref = "";
function fetchPage(reqPage, clicker) {
 // check for existence! (ie related products!)
 strWebtrendsHref = reqPage;
 
 if ($('productPanel')) {
  fadePage(reqPage); // fade the page and pass through the requested page
 } else {
  // if we are on 'passthru' the fader div will already exist, and we need to leave it alone. Else create and fade in:
  if ($('overlay_screen')) {
   // if no fader needed, we'll call the product straight away:
   ajaxCall(reqPage);
  } else {
   // attach a loading bar immediately for feedback:
   stateMarker(clicker);
   // create the fader div
   var fader = new Element('div', {
    'id': 'overlay_screen'
   });
   // get the div we're appending to:
   var el = $('content');
   // tack it in after this div
   //el.appendChild(fader);
   $(fader).injectAfter(el);
   // set up the fade action
   var fader = new Fx.Style('overlay_screen', 'opacity', {
    duration: 500, 
    transition: Fx.Transitions.Quad.easeInOut,
    onComplete:function() {
     // once the fade is complete we are gonna begin the AJAX bit
     ajaxCall(reqPage, 'product');
    }
   });
   fader.set(0);
   fader.start(0.8);
  }
 }
}
/* insert a PRODUCT via ajax */
function insertPage(request) {
 if (request.readyState == 4) {
  if (request.status == 200 || request.status == 304) {
   // get the div we're appending to:
   var el = $('container');
   // fill a throwaway div with the returned html
   var throwEl = new Element('div', {
    'id': 'discard',
    'styles': {
    'display': 'none'
    }
   });
   throwEl.setHTML(request.responseText);
   el.appendChild(throwEl);
   // pluck the correct item:
   var plucked = $('productPanel').innerHTML;
   // now kill the discarded div
   $('discard').remove();
   // create the true node to use
   var newEl = new Element('div', {
    'id': 'productPanel',
    'class': 'js'
   });
   newEl.setHTML(plucked);
   el.appendChild(newEl);
   // set up the fade action
   var fader2 = new Fx.Style('productPanel', 'opacity', {
    duration: 500, 
    wait: false,
    transition: Fx.Transitions.Quad.easeInOut,
    onComplete:function() {
     // kill any horizontal loader bars present:
     killStateMarker();
     //Web Trends call inserted here
     //How do we find the product ID
     if (document.getElementById('productvarid')) {
      //New line to fix Smartview and visit tracking
      strdcsqry = strWebtrendsHref.split('?')[1];
      dcsMultiTrack('DCS.dcsqry',strdcsqry,'DCS.dcsref',window.location.href,'WT.si_n','ShoppingCart','WT.si_x','1','WT.pn_sku',document.getElementById('productvarid').value,'WT.tx_u','1','WT.tx_e','v');
     }
    }
   });
   // if the window has been scrolled, then set the top style
   checkScroll(newEl);
   // set the fade to transparent
   fader2.set(0);
   // now rip through the div and do what's needed: WHILE IT'S STILL HIDDEN
   // -- this is the caller to Zoom.js
   MagicZoom_findZooms();
   // set the "size select checker" on disabled btn:
   $('add_to_shopping_bag').onclick = checkSizeSelected; /* utility function (see bottom of this script) */
   // set the "add to basket enabler" on each size input:
   sizeSelectEvent(); /* utility function (see bottom of this script) */
   // hide the "post basket actions"
   responseSlide = new Fx.Style('post_basket_actions', 'height', {
    duration: 300, 
    wait: false,
    transition: Fx.Transitions.Quad.easeInOut
   });
   responseSlide.set(0); // initial hide
   // initialise the tabs area within the panel
   overlayTabs.init();
   // alter size guide link (test for existence first)
   if ($('sizeGuideLink')) {
    $('sizeGuideLink').onclick = function() {
     ajaxCall(this.href, 'sizeguide');
     return false;
    }
   }
   // sort the links for the 'related items' area only (test for existence)
   if ($('complete_the_look')) {
    $('complete_the_look').setStyle('overflow', 'hidden');
    prepLinks('complete_the_look');
   }
   // animate the fade in
   fader2.start(0,1);
  } else { // else die
   return false;
  }
 }
}

/* REMOVE a PRODUCT  panel */
function fadePage(passThru) {
 // set up the fade action
 var fadeout = new Fx.Style('productPanel', 'opacity', {
  duration: 250, 
  transition: Fx.Transitions.Quad.easeInOut,
  onComplete:function() {
   // if zoom is running, stop it now...
   try {
    MagicZoom_stopZooms();
   } catch(err) {}
   // on the completion of fade, KILL the two divs
   $('productPanel').remove();
   // if this is a 'passthru' (ie a related item within the product panel) then pass back to fetchPage
   if (passThru != undefined) {
    // re-establish loading graphic from last clicked item
    stateMarker(lastClicker);
    fetchPage(passThru);
   } else {
    // if not, delete the fade layer too
    $('overlay_screen').remove();
   }
  }
 });
 fadeout.start(0.8,0);
}
//***********************************************************************************************************************************//
//  SIZE GUIDE - call, display and toggle
//***********************************************************************************************************************************//
/* insert the returned SIZE CHART into the page */
function insertChart(request) {
 if (request.readyState == 4) {
  if (request.status == 200 || request.status == 304) {
   // get the div we're appending to:
   var parent = $('product_images');
   // fill in the new html
   var newHtml = request.responseText;
   var newEl = new Element('div', {
    'id': 'sizeGuideHolder',
    'styles': {
    'display': 'none'
    }
   });
   newEl.setHTML(newHtml);
   // append
   parent.appendChild(newEl);
   // change the onclick event for the link
   $('sizeGuideLink').onclick = function() {
    toggleSizeGuide();
    return false;
   }
   // finally show the size guide:
   toggleSizeGuide();
  } else { // else die
   return false;
  }
 }
}
/* show/hide SIZE CHART  */
function toggleSizeGuide() {
 var state = $('sizeGuideHolder').style.display;
 if (state == 'block') {
  $('sizeGuideHolder').style.display = 'none';
  // change the text:
  $('sizeGuideLink').childNodes[0].nodeValue = "Size guide";
  // Re-initialize Zoom
  MagicZoom_findZooms();
 } else {
  // stop any active zooms:
  MagicZoom_stopZooms();
  $('sizeGuideHolder').style.display = 'block';
  // change the text:
  $('sizeGuideLink').childNodes[0].nodeValue = "Hide size guide";
 }
}
//***********************************************************************************************************************************//
//  BUY ALL PANEL - call, fade in, display and close
//***********************************************************************************************************************************//
/* fetch a BUY ALL PANEL - start with page fade: */
function fetchCollection(reqPage) {
 
 if ($('collectionPanel')) {
  fadeCollection(reqPage); // fade the page and pass through the requested page
 } else {
  // if we are on 'passthru' the fader div will already exist, and we need to leave it alone. Else create and fade in:
  if ($('overlay_screen')) {
   // if no fader needed, we'll call the product straight away:
   collectionCall(reqPage);
  } else {
   // attach a loading bar immediately for feedback:
   stateMarker($('full_look').parentNode);
   // adjust the style in this specific instance
   $('stateMarker').setStyles({
    top: 240,
    left: 125
   });
   // create the fader div
   var fader = new Element('div', {
    'id': 'overlay_screen'
   });
   // get the div we're appending to:
   var el = $('content');
   // tack it in after this div
   //el.appendChild(fader);
   $(fader).injectAfter(el);
   // set up the fade action
   var fader = new Fx.Style('overlay_screen', 'opacity', {
    duration: 500, 
    transition: Fx.Transitions.Quad.easeInOut,
    onComplete:function() {
     // once the fade is complete we are gonna begin the AJAX bit
     ajaxCall(reqPage, 'collection');
    }
   });
   fader.set(0);
   fader.start(0.8);
  }
 }
 
}
/* insert a BUY ALL panel via ajax */
function insertCollection(request) {
 if (request.readyState == 4) {
  if (request.status == 200 || request.status == 304) {
   // get the div we're appending to:
   var el = $('page');
   // fill a throwaway div with the returned html
   var throwEl = new Element('div', {
    'id': 'discard',
    'styles': {
    'display': 'none'
    }
   });
   throwEl.setHTML(request.responseText);
   el.appendChild(throwEl);
   // pluck the correct item:
   var plucked = $('buyAllPanel').innerHTML;
   // now KILL IT!
   $('discard').remove();
   // create the true node to use
   var newEl = new Element('div', {
    'id': 'buyAllPanel',
    'class': 'js'
   });
   // and fill it with the 'plucked' html
   newEl.setHTML(plucked);
   el.appendChild(newEl);
   // set up the fade action
   var fader2 = new Fx.Style('buyAllPanel', 'opacity', {
    duration: 500, 
    transition: Fx.Transitions.Quad.easeInOut,
    onComplete: function() {
     // kill any horizontal loader bars present:
     killStateMarker();
    }
   });
   // set the fade to transparent
   fader2.set(0);
   // if the window has been scrolled, then set the top style
   checkScroll(newEl);
   // change close button
   el = $('closeBtn');
   el.firstChild.childNodes[0].nodeValue = "close";
   el.onclick = function() {
    fadeCollection();
    return false;
   }
   // animate the fade in
   fader2.start(0,1);
   //Do the webtrends thing
   if(document.getElementById('productVarIdList') && document.getElementById('productVarIdListQty')) {
    dcsMultiTrack('WT.si_n','ShoppingCart','WT.si_x','1','WT.pn_sku',document.getElementById('productVarIdList').value,'WT.tx_u',document.getElementById('productVarIdListQty').value,'WT.tx_e','v');
   }
  } else { // else die
   return false;
  }
 }
}
/* REMOVE a BUY ALL panel */
function fadeCollection(passThru) {
 // set up the fade action
 var fadeout = new Fx.Style('buyAllPanel', 'opacity', {
  duration: 250, 
  transition: Fx.Transitions.Quad.easeInOut,
  onComplete:function() {
   // on the completion of fade, KILL the two divs
   $('buyAllPanel').remove();
   $('overlay_screen').remove();
  }
 });
 fadeout.start(1,0);
}
//***********************************************************************************************************************************//
//  INIT PREP - hijack all links within an 'id'
//***********************************************************************************************************************************//
/* prep all links in a page */
function prepLinks(containerId) {
 // tests for support - stop it right now if the browsers not up to it...
 if (!document.getElementById) { return false }
 if (!document.getElementsByTagName) { return false }
 // if a container ID is passed and points to an element ID, restrict the loop to that, otherwise we use the document
 if ($(containerId)) {
  // get all the <a> tags
  var allLinks = $(containerId).getElementsByTagName('a');
 } else {
  // get all the <a> tags
  var allLinks = document.getElementsByTagName('a');
 }
 // a count var to plug into IDs:
 var count = 0;
 for (var i=0; i<allLinks.length; i++) {
 var el = allLinks[i];
 // search allLinks for rel='product' attributes: this indicates a product link
 if (el.getAttribute('rel') == 'product') {
  // if it's true hijack it
  el.onclick = function() {
   // on click, get the href attribute and pass it to the ajax function. return false to stop link working normally
   var myLink = this.getAttribute('href');
   fetchPage(myLink, this);
   return false;
  }
 } else if (el.getAttribute('rel') == 'buyCollection') {
  // this is a 'buy all' link as opposed to a product link
  el.onclick = function() {
   // on click, get the href attribute and pass it to the ajax function. return false to stop link working normally
   var myLink = this.getAttribute('href');
   fetchCollection(myLink);
   return false;
  }
 }
 // increment the count var:
 count++;
 }
}
//***********************************************************************************************************************************//
//  DISPLAY LOADER graphics - 1st set is for product panel upon stock check, next set is for the parent page on click
//***********************************************************************************************************************************// 
function displayLoader(targ) {
 // remove all loading indicators
 var fel = $$($('productPanel').getElementsByTagName('form'));
 var els = $$(fel[0].getElementsByTagName('span'));
 for (var i=0; i<els.length; i++) {
  els[i].removeClass('spinner');
  els[i].removeClass('message');
  els[i].setText('');
 }
 var el = $$($(targ).getElementsByTagName('span'))[0];
 el.addClass("spinner");
}
function removeLoader() {
 $('stockChecker_gr').setProperties({
  src: 'images/spacer.gif',
  alt: ''
 });
 if ($('stockChecker_gr').hasClass('loader')) {
  $('stockChecker_gr').setProperty('id', '');
 }
}
// display loader graphics per "Buy all" item:
function buyLoader(srcEl) {
 var imgEl = $(srcEl).getParent().getElementsByTagName('img')[0];
 $(imgEl).setProperties({
  src: 'images/structural/product/loader_smlPanel.gif',
  alt: 'checking stock...',
  id: 'stockChecker_gr'
 });
}
// display loading bars in parent page
function stateMarker(where) {
 // if it's a deeplink, and the "where" var isn't defined (it would be 'this' from the link), default to the first link...
 if ($defined(where) == false) {
  where = $('prodList').getElementsByTagName('a')[0];
 }
 // create a loading bar immediately for feedback:
 var loadImg = new Element('img', {
  'id': 'stateMarker',
  'alt': 'loading...',
  'src': 'images/structural/product/loader_horiz_lrg.gif'
 });
 where.appendChild(loadImg);
 // save the location of the last loader bar
 lastClicker = where;
}
// kill loading bars in parent page
function killStateMarker() {
 if ($('stateMarker')) {
  $('stateMarker').remove();
 }
}
/* Hobbs Overlay Tabs Script
 Related Job No.: hob287
 Author: Dan Scotton (danscotton@gmail.com)
 ----------------------------------------------------*/
 
overlayTabs = {
 tabIds: [],
 init: function() {
  this.tabs = document.getElementById('additional_info_nav');
  this.content = document.getElementById('additional_info_content');
  this.hideAllContent();
  this.addEventsToTabs();
  this.showContent(this.tabIds[0]);
 },
 addEventsToTabs: function() {
  var tabListItems = this.tabs.getElementsByTagName('li');
  for(var i = 0; i < tabListItems.length; i++) {
   tabListItem = tabListItems[i];
   tabLink = tabListItem.getElementsByTagName('a')[0];
   var that = this;
   tabLink.onclick = function(e) {
    e = e || window.event;
    if(e.preventDefault)
     e.preventDefault();
    else
     e.returnValue = false;
    that.setTab(this.parentNode.parentNode);    
    that.showContent(this.getAttribute('href').substr(this.getAttribute('href').indexOf('#')+1));
   }
   this.tabIds[i] = tabLink.getAttribute('href').substr(tabLink.getAttribute('href').indexOf('#')+1);
  }
 },
 showContent: function(contentId) {
  this.hideAllContent();
  document.getElementById(contentId).style.display = 'block';
 },
 hideAllContent: function() {
  var contentDivs = this.content.getElementsByTagName('div');
  for(var i = 0; i < contentDivs.length; i++) {
   contentDivs[i].style.display = 'none';
  }
 },
 setTab: function(tabListItem) {
  this.clearTabs();
  tabListItem['className'] = 'selected';
 },
 clearTabs: function() {
  var tabListItems = this.tabs.getElementsByTagName('li');
  for(var i = 0; i < tabListItems.length; i++) {
   tabListItems[i]['className'] = '';
  }
 }
}

/*******************************************************************************************/
/************************************ UTILITY FUNCS ****************************************/
var checkSizeSelected = function() {
 if ($('sContainer')) {
  var inputEls = $$($('sContainer').getElementsByTagName('input'));
  // $('sContainer') div is what's being passed here, so collect the inputs:
  var sizeChk = false;
  for (var i=0; i < inputEls.length; i++) {
   if (inputEls[i].checked) {
    sizeChk = true;
   }
  }
  if (sizeChk == false) {
   var el = $('add_to_shopping_bag').getNext();
   el.addClass('message');
   el.setHTML('<em class="error">Please choose a size</em>');
   return false;
  }
 } else if ($('pcolour')) {
  // if no size, there is a possibility of just colour, which could be selected by default AND out of stock:
  var colourObj = $('pcolour');
  if ((colourObj.options[colourObj.selectedIndex].getAttribute('disabled') == true) || (colourObj.options[colourObj.selectedIndex].getAttribute('disabled') == 'disabled')) {
   var el = $('add_to_shopping_bag').getNext();
   el.addClass('message');
   el.setHTML('<em class="error">Sorry, out of stock</em>');
   return false;
  };
 }
}
var sizeSelectEvent = function() {
 if ($('sContainer')) {
  var inputEls = $$($('sContainer').getElementsByTagName('input'));
  for (var i=0; i < inputEls.length; i++) {
   inputEls[i].onclick = function() {
    // catch for lte IE7 and out of stock colour (no support for <option disabled="disabled">)
    if ($('pcolour')) {
     colourObj = $('pcolour');
     if (colourObj.options[colourObj.selectedIndex].getAttribute('disabled') == true) {
      return false;
     }; // thanks IE
    }
    // ensure Add To Bag is enabled
    $('add_to_shopping_bag').removeClass('disabled');
    $$($('add_to_shopping_bag').getElementsByTagName('img'))[0].setProperties({
     'src' : 'images/structural/overlay/button_add_to_shopping_bag_2.png',
     'alt' : 'Add to Shopping Bag',
     'class' : ''
    });
   }
  }
 }
}

