var zIndex = null;
var i=0;
var timer = null;
var timer2 = null;
var ar_drag = new Array();
var object = new Array();
// setting this var in head_section.php now
//var render = 'scatter';
var clickBlock = false;
var hoverBlock = false;
var cookieBlock = false;
var dragMode = false;
var original='';
var dim;
var storedM;
var myCookie = '';
var displaylocked;
var sortflag = false;
var admin;
var loader = '<img src="'+virtual_path+'/media/gif/interface/ajax-loader.gif" />';
var menu = new Array();
var tooltipfade_fx;
var page_loaded = false;
var allow_random = true;
var allow_grid = true;

//if(typeof(pagetype) != 'undefined')
//{
//alert(pagetype);

function roundNumber(num, dec) {
  var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
  return result;
}

switch(pagetype){

  case 'thingsilove':
	  // update virtual path to https
	  virtual_path = virtual_path.replace('http://', 'https://');
	  // set loader graphic
	  loader = '<img src="'+virtual_path+'/media/gif/interface/ajax-loader.gif" />';
	
	  document.addEvent( 'domready' , function(){
	
		//if($('template_2_col_1')) $('template_2_col_1').dispose();
		winOnLoad();
	
	  }, false);
	
	  break;
	
	  // MAY HAVE TO CREATE NEW CLAUSE FOR SEARCH ##
  case 'ecomcol':
	  allow_random = false;
	  render = 'grid';
	  document.addEvent( 'domready' , function(){
		/*
		if (render == "grid" )
		{
		  $('rand_grid').removeClass('random');
		  $('rand_grid').addClass('grid');
		}
		else
		{
		  $('rand_grid').removeClass('grid');
		  $('rand_grid').addClass('random');
		}
		*/
	
		//$('rand_grid').addClass('grid');
		$('rand_grid').addClass('disabled_grid');
	  }, false);
	
	  break;

  case 'ecomcat':
	  allow_random = false;
	  render = 'grid';
	  document.addEvent( 'domready' , winOnLoad, false);
	  document.addEvent( 'domready' , function(){
		/*
	    if (render == "grid" )
		{
		  $('rand_grid').removeClass('random');
		  $('rand_grid').addClass('grid');
		}
		else
		{
		  $('rand_grid').removeClass('grid');
		  $('rand_grid').addClass('random');
		}
	*/
		//$('rand_grid').addClass('grid');
		$('rand_grid').addClass('disabled_grid');
	  }, false);
	
	  break;

  case 'ecomoverview':
	  allow_grid = false;
	  render = 'scatter';

	  document.addEvent( 'domready' , function(){
		/*
		if (render == "grid" )
		{
		  $('rand_grid').removeClass('random');
		  $('rand_grid').addClass('grid');
		}
		else
		{
		  $('rand_grid').removeClass('grid');
		  $('rand_grid').addClass('random');
		}
		*/
		$('rand_grid').addClass('disabled_grid');
	  }, false);
	
	  break;

  case 'ecomhome':
	  document.addEvent( 'domready' , winOnLoad, false);

	  // prevent grid/random button interaction
	  allow_grid = false;
	  render = 'scatter';

	  document.addEvent( 'domready' , function(){
		/*
		if (render == "grid" )
		{
		  $('rand_grid').removeClass('random');
		  $('rand_grid').addClass('grid');
		}
		else
		{
		  $('rand_grid').removeClass('grid');
		  $('rand_grid').addClass('random');
		}
		*/
		$('rand_grid').addClass('disabled_grid');
	  }, false);
	
	  break;

  case 'ecomprod':
	  document.addEvent( 'domready' , function(){
		// build shop menu
		callForShopMenu('Item',cname+'.ecomcat.'+cid);
		// add actions to size guide button
		sizechart();
	  }, false);
	  window.addEvent( 'load' , initProductDetail, false);
	
	  break;

  case 'basket':
	  // update virtual path to https
	  virtual_path = virtual_path.replace('http://', 'https://');
    
    virtual_path = virtual_path.replace('http://', 'https://');
	  loader = '<img src="'+virtual_path+'/media/gif/interface/ajax-loader.gif" />';
    
    //document.addEvent('domready' , myLoader, false);
    document.addEvent('domready' , sendTil, false);
    //window.addEvent('load' , myLoader, false);
    
	
	  break;
	  
  case 'collection':
	  render = 'grid';
	  window.addEvent('load', initEcomCol, false);
	
	  // Added by Tim to load styling for 'things i love'
	  document.addEvent( 'domready' , ThingsILoveTooltip, false);
	
	  break;

  case 'wordpress':
  case 'ecommedia':
	  // Added by Tim to load styling for 'things i love'
	  document.addEvent( 'domready' , ThingsILoveTooltip, false);
	
	  //initSlideShow();
	  window.addEvent( 'load' , initWordPress, false);
	
	  break;
	
	  // OVERVIEW PAGE. NAVIGATION
	
	  default:
	  //render = 'grid';
	  //initSlideShow();
	  window.addEvent( 'load' , initSlideShow, false);
	
	  break;
}
//}

//document.addEvent( 'domready' , resizelogo, false);

document.addEvent( 'domready' , initSite, false);
window.addEvent( 'load' , pageloaded, false);

// Run this when the pages loads
function pageloaded ()
{
  page_loaded = true;
}

/*
window.onresize = function() {
resizelogo();
}
*/

function initSite()
{
  initSlideShow(); // line 445
  initMainMenu(); // line 201
  init_scrolling_thumbs(); // line 1741
  thingsilove_buy(); // line 1840
  //
  // form tips
  fn_input_placeholders(); // line 1578
}

function initWordPress()
{
  initSlideShow();
  locateObjs();
  myLoader("off");
}

function initProductDetail()
{
  initiProductDetailJs();
  locateObjs();
  myLoader("off");
}

function initMainMenu()
{
  // animations for main navigation menu
  $$('.subnav').each(function(el, index){
    var myEffect;
    // override default CSS - give submenu height and set overflow to hidden
    el.set('styles',{'display':'block','overflow':'hidden'});
    // now that submenu has height, calculate it
    var size = el.getSize();
    var myh = size.y;
    // identify parent - the main menu item that needs the mouse events
    var p = el.getParent();
    // store the key variables in an array
    menu.push({ 'submenu':el, 'height':myh, 'mainmenu':p});
    // set submenu to no height and make invisible
    el.set('styles',{'height':0});
    el.set('opacity',0);
    // add mouse events to parent
    p.addEvent( 'mouseenter',	function(event, index){
      // This morphes the opacity and height
      menu[index].submenu.set('styles',{'display':'block'});
      if(myEffect)myEffect.cancel();
      myEffect = new Fx.Morph(menu[index].submenu, {duration: 250, transition: Fx.Transitions.Sine.easeOut});
      myEffect.start({
        height: menu[index].height,
        opacity: 0.9
      });
    }.bindWithEvent(this, index));
    p.addEvent( 'mouseleave',	function(event, index){
      // This morphes the opacity and height
      if(myEffect)myEffect.cancel();
      myEffect = new Fx.Morph(menu[index].submenu, {duration: 250, transition: Fx.Transitions.Sine.easeOut});
      myEffect.start({
        height: 0,
        opacity: 0
      });
      /*
      */
    }.bindWithEvent(this, index));
  });
  // Init logo resize as we have hijacked this DOM on load event
  //resizelogo();
}

function menuMouseEnter(menuitem)
{
  alert(menuitem+":"+menuitem.height+":"+menuitem.submenu.nodeName);
  //menuitem.submenu.morph({height:menuitem.height,opacity:1});
}

function menuMouseLeave(menuitem)
{
  //menuitem.submenu.morph({height:0,opacity:0});
}

function screenDimensions(){
  
  d = document;
  if (typeof window.innerWidth != "undefined")
  {
    h = window.innerHeight;
    w = window.innerWidth;
  }
  else if (d.documentElement && typeof d.documentElement.offsetWidth != "undefined" && d.documentElement.offsetWidth != 0)
  {
    h = d.documentElement.offsetHeight;
    w = d.documentElement.offsetWidth;
  }
  else if (d.body && typeof d.body.offsetWidth != "undefined")
  {
    h = d.body.offsetHeight;
    w = d.body.offsetWidth;
  };

  return[w,h];
}
function resizeLimiter(){
  if(timer) clearTimeout(timer);
  timer = setTimeout(function(){
    winOnLoad();
  },500)
}
function hideTips(){
  $$('.custom-tip').each(function(el){
    el.setProperty('style','display:none');
  })
}
function removeTips(){

  $$('.custom-tip').each(function(el){
    el.dispose();
  })
}
var addToLoved = function(el){
  // Is the location outside of WordPress scope?
  var loc = el.getFirst('a').get('href');

  var stepNo = '2';

  if(pagetype=='wordpress' || pagetype=='ecommedia' || pagetype=='ecomprod'){
    //we are in wordpress link so link to the current request page
    loc = page;
  }
  if(pagetype=='wordpress' || pagetype=='ecommedia'){
    stepNo = '3';
  }
  if(pagetype=='ecommedia'){
    //this is a Collection page - need to get image src from class
    var linkel = $$('.draggable a.current');
    var imgsrc = linkel[0].getFirst('img').get('src');
  } else if(pagetype=='wordpress'){
    // For instances where we have a video with a play button, 
    // play button is the first image followed by the actual image, so get the second image (actual image) 
    var imgsrc = el.getFirst('a').getLast('img').get('src'); 
  } else
  {
    var imgsrc = el.getFirst('a').getFirst('img').get('src'); 
  }

  //alert('function=addtobag_step&stepNo=2&item='+el.id+'&location='+loc+'&imgSrc='+imgsrc);

  new Request.HTML({
    method: 'post',
    url: path_to_root + 'scripts/php/logic.php',
    data: { 'do' : '1' },
    async: false,
    update: 'capture',
    onComplete: function(response) {
      if($('popup_form')) {
        $('popup_form').setStyle("top", "30%");
        $('popup_form').setStyle("position", "fixed");
      }
      if(pagetype!=="wordpress" && pagetype!=="collection" && pagetype!=="ecommedia")
	  {
		  initiProductDetailJs(); // this sets up all of the code required on the colour option buttons, if present
		  if(pagetype!=="ecomprod")
		  {
			// we don't want this at the product detail level
			reloadObjs(); // this loads up all of the grid / scatter images
		  }
		  sizechart(); // this adds functionality to the size chart graphic, if present
		  //reloadObjs();
	  }
      if($('item_exists')){
        //var window_top = window.pageYOffset;
        var myFx = new Fx.Tween('popup_form',{duration: '1500',property: 'opacity'});
        myFx.start.pass([1, 0],myFx).delay(2000);
      }
    }
  }).send('function=addtobag_step&stepNo='+stepNo+'&item='+el.id+'&location='+loc+'&imgSrc='+imgsrc); //addtobag  
}

var removeFromLoved = function(iid){


  new Request.HTML({
    method: 'post',
    url: path_to_root + 'scripts/php/logic.php',
    data: { 'do' : '1' },
    async: false,
    onComplete: function(response) {
    }
  }).send('function=removefrombag&item='+iid);

}
function resizelogo(){

  dim = screenDimensions();

  propHeight = dim[1] / 3.75;
  //	console.log(console,'propheight ' + propHeight);

  // minimum reduction
  if(propHeight.round() < 110){
    propHeight = 110;
  }
  if(propHeight.round() > 195){
    propHeight = 195;
  }
  var newheight = propHeight.round();
  var newwidth = (propHeight * 1.62).round();

  if(browser == 'ie' && browserversion < 8 && browserversion > 6){

    $("logo").setStyle("height", 'auto');
    $("logo_img").setStyle("height", 'auto');

    //ie7 swap out image sizes
    if(newwidth < 201){
      newwidth = 200;
      $("logo").setStyle("width", '200px');
      $("logo_img").setStyle("width", '200px');
      $("logo_img").set("src", path_to_root+'media/interface/logo-vw-ie200.png');

    }else if(newwidth < 251){
      newwidth = 250;
      $("logo").setStyle("width", '250px');
      $("logo_img").setStyle("width", '250px');
      $("logo_img").set("src", path_to_root+'media/interface/logo-vw-ie250.png');

    }else if(newwidth < 276){
      newwidth = 275;
      $("logo").setStyle("width", '275px');
      $("logo_img").setStyle("width", '275px');
      $("logo_img").set("src", path_to_root+'media/interface/logo-vw-ie275.png');

    }else if(newwidth < 301){
      newwidth = 300;
      $("logo").setStyle("width", '300px');
      $("logo_img").setStyle("width", '300px');
      $("logo_img").set("src", path_to_root+'media/interface/logo-vw-ie300.png');

    }else { //if(newwidth < 401)
      /*
      newwidth = 400;
      $("logo").setStyle("width", '400px');
      $("logo_img").setStyle("width", '400px');
      $("logo_img").set("src", virtual_path+'/media/interface/logo-vw-ie400.png');
      */

      // Tim: using default of 275px because 400px was too big for the things i love section

      newwidth = 275;
      $("logo").setStyle("width", '275px');
      $("logo_img").setStyle("width", '275px');
      $("logo_img").set("src", path_to_root+'media/interface/logo-vw-ie275.png');
    }// ELSE ITS HUGE?!

    $("logo_img").setStyle("visibility","visible");
    $("logo").setStyle("margin-left",-(newwidth/2)+'px');
  }else{

    $("logo").setStyle("height", newheight + 'px');
    $("logo").setStyle("width", newwidth + 'px');

    $("content").setStyle("padding-top", (propHeight * 1.2).round() + 'px');
    $("logo").setStyle("margin-left", (-propHeight * 0.81).round() + 'px');

    $("logo_img").setStyle("width", newwidth+'px');
    $("logo_img").setStyle("height", newheight+'px');
    $("logo_img").setStyle("visibility","visible");
  }

}
function initSlideShow(){

  //
  // Slide show js
  if($$('.thumbs'))
  {
    $$('.thumbs').each(function(el){
      el.setProperty('style','overflow-y: hidden; height: 270px;');
    });
  }

  // Original
  /*
  if($$('.multiple_images'))
  {
  $$('.multiple_images').each(function(el){
  //el.setStyle("overflow-y", "hidden");
  //el.setStyle("height", "288px");

  $$('#'+ el.id +' a').each(function(ela, index){
  if(index != 0)
  {
  ela.setStyle("display", "none");
  }
  else
  {
  ela.addClass('current');
  }
  });
  });
  }
  */

  // If the page type is ecom media, skip this bit as we set display and class on the template level
  if(pagetype != "ecommedia")
  {
    if($$('.multiple_images'))
    {
      $$('.multiple_images').each(function(el){
        //el.setStyle("overflow-y", "hidden");
        //el.setStyle("height", "288px");

        $$('#'+ el.id +' a').each(function(ela, index){
          if(index != 0)
          {
            ela.setStyle("display", "none");
          }
          else
          {
            ela.addClass('current');
            ela.setStyle("display", "block");
          }
        });
      });
    }
  }

  if($$('.item_thumbs a'))
  {
    $$('.item_thumbs').each(function(eltmp){
      $$('#'+ eltmp.id +' a').each(function(el, index){
        el.addEvent("click",function(event, index){
          event.stop();
          elp = el.getParent().getParent().getNext();
          var itemid = el.id;

          $$('#'+ elp.id +' div a.current')[0].setStyle("display", "none").removeClass("current");

          $(itemid+'_lg').setStyle("display", "block").addClass("current");
          //$$('#'+ elp.id +' a:nth-child('+ (index + 1) +')')[0].setStyle("display", "block").addClass("current");
          //}.bind(this, index));
        }.bindWithEvent(this, index));
      });
    });
  }

}

function winOnLoad()
{

  myLoader("on");
//   if($('top_menu')){
//     render = 'grid';
//     //var displaylocked = 'yes';
//   }

  dim = screenDimensions();


  //
  // GET OBJETS LIST
  new Request({
    method: 'get',
    url: path_to_root + 'scripts/php/cookielogic.php',
    data: { 'do' : '1' },
    async: false,
    onComplete: function(response) {

      myCookie = response;
    }
  }).send('func=get_layout&pagepath='+page);

  if(myCookie==null) myCookie='';

  if(pagetype != 'ecomprod'){

    //if(pagetype == 'ecomhome'){
    new Request({
      method: 'get',
      url: path_to_root + 'scripts/php/objectAr_inc.php',
      data: { 'do' : '1' },
      async: false,
      onComplete: function(response) {
        buildObjects(response,render) }
    }).send('page='+page+'&pageType='+pagetype+'&node_glue='+nodeglue+'&render='+render+'&screenWidth='+dim[0]+'&screenHeight='+dim[1]+'&u_layout='+myCookie+'&node_id='+node_id);

    if(displaylocked!='yes')
    locateObjs();
    //}

  } else if (pagetype!='thingsilove') {
    // nothing
  } else
  {
    // is product detail page - init drag and drop of main image
    locateObjs();
  }

  initShopMenu();

  //
  // reset cookie
  if($('cookie_reset'))
  {
    $('cookie_reset').addEvents({'click':function(e){

      //Cookie.dispose('userlayout');
      new Request({
        method: 'get',
        url: path_to_root + 'scripts/php/cookielogic.php',
        data: { 'do' : '1' },
        async: false,
        onComplete: function(response) {
          alert('cookie cleared')
          //myCookie = response;
        }
      }).send('func=remove_layout&pagepath='+page);
    }})
  }



  //
  // fire sort
  /*if($('sortexe')){
  $('sortexe').addEvents({
  'click':function(e){
  e.stop();
  pagetype = 'ecomcat';
  render = 'grid';
  reloadObjs();
  }
  })
  }*/
}

function initShopMenu(){

  if($('shop_menu')){
    var timerfilters = null;
    fn_init_menuslide();


    $('shop_menu').addEvents({
    'mouseenter': function(e){
      if (page_loaded ===true)
      {
        $('filters').setStyle('display','block');
        clearTimeout(timerfilters);
      }
    },
    'mouseleave': function(e){
      if (page_loaded ===true)
      {
        var timeperiod = 900;
        if(sortflag === true) timeperiod = 3000;

        timerfilters = setTimeout(function(){
          setTimeout(function(){
            if(storedM && $(storedM)){
              var filterList_tmp = $(storedM);
              filterList_tmp.get('slide').hide();
            }
            $('filters').setStyle('display','none');
            $('filters').setStyle('opacity','1');
          },"400");

        },timeperiod)
      }
    }
    });
    ThingsILoveTooltip();
  }

  // Disable on click function if buttton is meant to be disabled ie : has a class disabled_grid 
  if (($('rand_grid').className != 'disabled_grid' && allow_random) && ($('rand_grid').className != 'disabled_random' && allow_grid))
  {
    // grid/scatter trigger
    //alert($('rand_grid').className);
    $('rand_grid').addEvent("click",function(){

      if(render=='scatter'){
        render='grid';
        $('rand_grid').removeClass('random');
        $('rand_grid').addClass('grid');
      }
      else{
        render='scatter';
        $('rand_grid').removeClass('grid');
        $('rand_grid').addClass('random');
      }

      reloadObjs()
    })
  }
}

function ThingsILoveTooltip()
{
  //
  // Things I Love ToolTip HINT

	/*
	 * Removed 20120106 - STU
  var tilHelp = $('thingsILoveHover');
  tilHelp.set('styles',{'display':'block'});
  tilHelp.set('opacity',1);
  setTimeout(function(){
    tooltipfade_fx = new Fx.Tween('thingsILoveHover',{duration: '3000'});
    //Immediately sets the background color of the element to red:
    tooltipfade_fx.start('opacity', '1', '0');
  },700); 
	 */

  /*
  //var FadeTipText = $('thingsILove').getProperty('alt');
  var FadeTipText = $('heart').getProperty('alt');

  //var FadeTipEl = new Element('div',{'id' : 'msg', 'class' : 'custom-tip', 'html': FadeTipText, 'style': 'position:absolute;width:150px;bottom:45px;right:75px'} );
  var FadeTipEl = new Element('div',{'id' : 'msg', 'class' : 'custom-tip', 'html': FadeTipText, 'style': 'position:absolute;padding:4px 7px;margin:12px 0 0 0;height:20px;width:477px;bottom:45px;right:75px;font-weight:bold;font-size:18px;line-height:17px;'} );

  FadeTipEl.injectInside($('shop_bag'));
  setTimeout(function(){
  var myFx = new Fx.Tween('msg',{duration: '3000'});
  //Immediately sets the background color of the element to red:
  myFx.start('opacity', '1', '0');
  },700)

  // Things I love tool tip
  //    var TipBag = new Tips($('thingsILove'), {
  //		className: 'custom-tip'
  //	});

  // Things i love tool tip BIG heart
  var TipBag = new Tips($('heart'), {
  fixed:true,
  className: 'custom-tip'
  });
  */
}

function reloadObjs(){
  
  // Tim: Get the latest layout
  // GET OBJETS LIST
   new Request({
    method: 'get',
    url: path_to_root + 'scripts/php/cookielogic.php',
    data: { 'do' : '1' },
    async: false,
    onComplete: function(response) {

      myCookie = response;
    }
  }).send('func=get_layout&pagepath='+page);
  //
  
  dim = screenDimensions();
  myLoader("on");
  removeTips();
  // search criteria
  var searchcriteria = $$('#searchCriteria input');
  var criteriastr = '';
  searchcriteria.each(function(ele){
    criteriastr += "&"+ele.id+"="+encodeURIComponent(ele.value);
  })
  //alert('page='+page+'&pageType='+pagetype+'&node_id='+nod  e_id+'&node_glue='+nodeglue+'&screenWidth='+dim[0]+'&screenHeight='+dim[1]+'&u_layout='+myCookie+'&render='+render + criteriastr);
  new Request({
    method: 'get',
    url: path_to_root + 'scripts/php/objectAr_inc.php',
    data: { 'do' : '1' },
    async: false,
    evalScripts: true,
    onComplete: function(response) {
      buildObjects(response,render);
      locateObjs();
      //myLoader();
    }
  }).send('page='+page+'&pageType='+pagetype+'&node_id='+node_id+'&node_glue='+nodeglue+'&screenWidth='+dim[0]+'&screenHeight='+dim[1]+'&u_layout='+myCookie+'&render='+render + criteriastr);
}

function locateObjs(){

  var dropElement = new Array();
  dropElement[0] = $('shop_bag');

  document.ondragstart = function () { return false; }; //IE drag hack

  //if($$('#dragContainer div:not(.clear)'))
  if($$('div.draggable'))
  {
    //$$('#dragContainer div:not(.clear)').each(function(element){
    $$('div.draggable').each(function(element){

      ar_drag[i] = new Drag.Move(element,{
        onBeforeStart: function(el) {
          //zIndex = zIndex + 1;
          //el.setStyle('zIndex', zIndex);

          // get start position
          if($('dragContainer')) {
            var posTo = $('dragContainer');
          } else {
            var posTo = $('content');
          }
          ObjCoords=el.getCoordinates(posTo);
		  
        },
        preventDefault: false,
        droppables: dropElement,
        revert: true,
        //container: $$('.constrain')[0],	//$$('.constrain') is nothing on first load of the page after dropping into 'things i love' it then becomes an html object collection but as this wasnt called after drop anyway this seems pointless
		//container: $(document.documentElement),
        onStart: function(el){		//start dragging
          //morphObject.start({width:0});
          clearTimeout(timer);
          clearTimeout(timer2);
          clickBlock=true;
          hoverBlock=true;


          //$(document.documentElement).addClass('constrain');
          if(el.getFirst('a').getFirst('img.rollover')){
            el.getFirst('a').getFirst('img').setStyle('display','block');
            el.getFirst('a').getFirst('img.rollover').setStyle('display','none');
          }

          //var children = el.getLast().getChildren();
          //children[1].setStyle('display','none');
          //children[0].setStyle('display','block');
        },
        onComplete: function(){

          if(render!='grid' & pagetype != 'wordpress' & pagetype != 'ecommedia' & cookieBlock != true & admin != true){
			//
			// This is the full drag and drop scatter view experience, where visitors can move stuff around at will
			// and the system will remember what they have done on future visits
            var posString='';
            //$$('#dragContainer div:not(.clear)').each(function(element){
            $$('div.draggable').each(function(element){
              ObjCoords=element.getCoordinates($('dragContainer'));
              // get image size
              if(element.getFirst('a').getFirst('img')){
                var imgsrc = element.getFirst('a').getFirst('img').get('src');
              }

              if(imgsrc){
                var parts = imgsrc.split(/\//);
              }

              if(parts) {
                var iName = parts.pop();
                var iSize = parts.pop();
              }

              posString += ObjCoords.left+","+ObjCoords.top+","+iSize+"@";
            })

            // save the cookie.
            new Request({
              method: 'get',
              url: path_to_root + 'scripts/php/cookielogic.php',
              data: { 'do' : '1' },
              async: false,
              onComplete: function(response) {
              }
            }).send('func=save_layout&pagepath='+page+'&posString='+posString);

          }

          setTimeout(function(){clickBlock=false; hoverBlock=false; cookieBlock=false;},100);
        },
        onEnter: function(el,dr){
          //dr.setStyle('border','1px #333 dashed');
          //console.log(el, 'entered', dr);
          dr.getLast().setStyle('width','80px');
        },
        onLeave: function(el,dr){
          //dr.setStyle('backgroundColor','transparent');
          //dr.setStyle('border','0px #fff none');
          dr.getLast().setStyle('width','70px');
        },
        onDrop: function(el, dr) {

          if (!dr) {
            //
            //reset position if in grid mode

            if(typeof(render)!=="undefined"){
              if(render=='grid' || pagetype=='wordpress' || pagetype=='ecommedia' || pagetype=='ecomprod' || pagetype=='collection'){
                ObjCoordsNow=el.getCoordinates(el);
                var myEffect = new Fx.Morph(el, {duration: 'short'});
                myEffect.start({
                'left': '0px',
                'top': '0px'
                });
              }
            }
          } else {
            cookieBlock=true;
            dr.setStyle('backgroundColor','transparent');
            dr.setStyle('border','0px #fff none');
            //dr.highlight('#667C4A');
            // render = 'grid';	//fix for bug for dropping media from the story section for some reason simply checking that rende exists doesnt satisfy it needs to be set
            if(typeof(render)!=="undefined"){
              if(render=='grid' || pagetype=='wordpress' || pagetype=='ecommedia' || pagetype=='ecomprod' || pagetype=='collection'){
                //
				// GRID MODE
				// animate element back to grid position
				ObjCoordsNow=el.getCoordinates(el);
                var myEffect = new Fx.Morph(el, {duration: 'short'});
                myEffect.start({
                'left': '0px',
                'top': '0px'
                });
              }
            }else{
              //
			  // SCATTER MODE
			  // remove element and then reappear a second later in its previous position
			  el.setStyles({display:'none','left': ObjCoords.left, 'top': ObjCoords.top});
              setTimeout(function(){
                el.setStyle('display','block');
              },1000)
            }

            //
            // send request to the handller
            addToLoved(el);

          };
        }
      });
	  // hack to force correct position of wordpress news images
	  if(pagetype=='wordpress'){
		element.setStyle('left','0px');
		element.setStyle('top','0px');
	  }
      i++;
    })
  }

  myLoader("off");
}

function buildObjects(jsonObj,render) {
  if($('dragContainer'))
  {
    $('dragContainer').innerHTML = '';
    var objects = JSON.decode(jsonObj);
    var object = objects.objAr;
    var filters = objects.filterAr;
    var objLen=object.length;
    var className = 'draggable';

    /*
    var debugoutput = print_r(filters['']['filterVals'][0],true);
    alert(debugoutput);
    */

    if(render=='grid') className += ' gridItem';

    for(var i=0; i<objLen; i++)
    {
      /*<span class="iefix"></span>*/
      var img = '<span class="iefix"></span><img id="img_'+i+'" class="image img_'+i+'" border="0" src="'+ object[i]['imgSrc']+'"';
	  
	  // add in fixed height or width for wordpress images
	  if(typeof(object[i]['is_wordpress'])!=='undefined')
	  {
		  if(object[i]['is_wordpress']==1 && render == 'grid')
		  {
			  img += ' width="205"';
		  } else if(object[i]['is_wordpress']==1 && render == 'scatter')
		  {
			  var rnd = Math.floor(Math.random()*200)+200;
			  img += ' height="'+rnd+'"';
		  }
  	  }
	  img += ' />';
	  
      // If in scatter mode use add rollover images
      if (render == 'scatter'){
        if(object[i]['imgSrcAlt']) img += '<img class="rollover" border="0" src="'+ object[i]['imgSrcAlt']+'" style="display:none" />';
      }

      //if(object[i]['imgSrcAlt']) img += '<img class="rollover" border="0" src="'+ object[i]['imgSrcAlt']+'" style="display:none" />';

      // imagestamps. out of stock, limited etc.
      if(object[i]['status'])
      {
        switch(object[i]['status'])
        {
          case 'soldout':
          img += '<img class="stamp" border="0" src="'+ virtual_path +'/media/ecommerce_skin/soldout.png" />';
          break;
          case 'limitedstock':
          img += '<img class="stamp" border="0" src="'+ virtual_path +'/media/ecommerce_skin/limited.png" />';
          break;
          case 'comingsoon':
          img += '<img class="stamp" border="0" src="'+ virtual_path +'/media/ecommerce_skin/comingsoon.png" />';
          break;
        }
      }


      if(render=='scatter')
      {
        var my_div = new Element(
        'div',
        {
        'id': object[i]['imgType']+'_'+object[i]['obj_id'],
        'class' : className,
        'styles' :
        {
        'left': parseInt(object[i]['posLeft']) + 'px',
        'top': parseInt(object[i]['posTop']) + 'px',
        'zIndex': object[i]['iStack']
        },
        'events':
        {
        'mouseenter': function()
        {
          // change image source
          if(hoverBlock===false && page_loaded === true)
          {
            this.addClass('draggable_hover');
            if(this.getFirst('a').getFirst('img.rollover'))
            {

              // get the current image size and transpose
              var size = this.getFirst('a').getFirst('img').getSize();
              this.getFirst('a').getFirst('img.rollover').setStyle('width',size.x+'px');
              this.getFirst('a').getFirst('img.rollover').setStyle('height',size.y+'px');
              this.getFirst('a').getFirst('img').setStyle('display','none');
              this.getFirst('a').getFirst('img.rollover').setStyle('display','block');
            }
          }

        },
        'mouseleave': function()
        {
          if(hoverBlock===false && page_loaded === true)
          {
            this.removeClass('draggable_hover');
            if(this.getFirst('a').getFirst('img.rollover'))
            {
              this.getFirst('a').getFirst('img').setStyle('display','block');
              this.getFirst('a').getFirst('img.rollover').setStyle('display','none');
            }
          }
        },
        'mouseup':function()
        {
          hoverBlock = false;
          $(document.documentElement).removeClass('constrain');
          this.addClass('draggable_hover');
          if(this.getFirst('a').getFirst('img.rollover'))
          {
            this.getFirst('a').getFirst('img').setStyle('display','none');
            this.getFirst('a').getFirst('img.rollover').setStyle('display','block');
          }
        }
        }
        });
      }else{
        var my_div = new Element(
        'div',
        {
        'id': object[i]['imgType']+'_'+object[i]['obj_id'],
        'class' : className,
        'html': object[i]['imgText'],
        'style':'left:0px;top:0px;'
        } );
      }

      //
      // build the anchor tag adding the image within
      //
      // set target if link is external, not empty and not VW
      if(object[i]['node_type']=="extlink" && object[i]['node_glue']!="" && object[i]['node_glue'].indexOf("http://www.viviennewestwood.co.uk")==-1){
    	  target = "_blank";
      } else {
    	  target = "_self";
      }
    	  
      var myAnchor = new Element('a',
      {
      'id': 'link_'+object[i]['obj_id'],
      //'href': (pagetype=='thingsilove'?virtual_path:'') + object[i]['imgLink'],
      'href': object[i]['imgLink'],
      'target': target,
      'html': img,
      'events':
      {
      'click': function(e)
      {
        if(clickBlock===true)
        {
          new Event(e).stop();
        }
      },
      'mouseenter': function()
      {
        // change image source
        if(hoverBlock===false)
        {
        }
      },
      'mouseleave': function()
      {
        if(hoverBlock===false)
        {
        }
        //this.getFirst().src=original;
      }
      }
      });


      if(pagetype == 'thingsilove' && object[i]['imgType'] == 'product' && object[i]['product_stock']>0)
      {
        var myBuy = new Element('a',
        {
        'class': 'button buy',
        'id': object[i]['obj_id'] + '-buy',
        'html': 'BUY',
        //'href': virtual_path + object[i]['imgLink']
        'href': object[i]['imgLink']
        })
        myBuy.injectInside(my_div);
      }

      //
      // Only display on basket / things i love
      if(pagetype == 'thingsilove')
      {
        var myControlContainer = new Element('span',
        {
        'class': 'actions',
        'html': ''
        });
        myControlContainer.injectInside(my_div);

        var myControlView = new Element('a',
        {
          //'href': virtual_path + object[i]['imgLink'],
          'href': object[i]['imgLink'],
          'class': 'control view',
          'html': 'view'
        });
        myControlView.injectInside(myControlContainer);

        var myControlRmv = new Element('a',
        {
        'id': object[i]['obj_id'] +'_'+ object[i]['fav_id'],
        'class': 'control remove',
        'events':
        {
        'click': function(e)
        {
          //new Event(e).stop();
          //var href = this.href;
          //removeFromLoved(this.id)
        }
        },
        'html': 'remove',
        // Original
        //'href': page + '?rm_til=' + object[i]['obj_id'] + '&fav_id=' + object[i]['fav_id']+ '&location=' + object[i]['imgLink']

        'href': page + '?rm_til=' + object[i]['obj_id'] + '&fav_id=' + object[i]['fav_id']+ '&location=' + encodeURIComponent(object[i]['imgLink'])
        })
        myControlRmv.injectInside(myControlContainer);
      }


      myAnchor.injectInside(my_div);
      my_div.injectInside($('dragContainer'));

      //
      // TOOLTIPS // Display image tool tip if hover image doesnt exist.
      // STU: edit - also display tooltip if inside TIL or if in Grid mode
      if(!object[i]['imgSrcAlt'] || pagetype == 'thingsilove' || pagetype == 'basket' || render == 'grid')
      {
        // alert(print_r(object[i], true));
        // extract title from imgLink if type = media
        if(object[i]['imgType'] == 'media' || object[i]['imgType'] == 'wordpress')
        {
          var imgLinkParts = object[i]['imgLink'].split('/');
          object[i]['title'] = imgLinkParts[imgLinkParts.length-1].replace(/-/g,' '); // global replace to catch every instance of '-'
        }
        if(object[i]['title']!="#")
        {
          new Tips(
          $( object[i]['imgType']+'_'+object[i]['obj_id'] ),
          {
            className: 'custom-tip'
          }
          );
        }
      }

      $( object[i]['imgType']+'_'+object[i]['obj_id'] ).store('tip:title', object[i]['title']);
      if(object[i]['price']!= undefined && object[i]['price'] != '')
	  {
		  var currencySymbol = '';
		  if(object[i]['currencySymbol'])
		  {
			  currencySymbol = object[i]['currencySymbol'];
		  }
		  var cLen = currencySymbol.length;
		  var oldP = new Number(object[i]['price'].substring(cLen));
		  
		  if(object[i]['discount_price']!= undefined && object[i]['discount_price'] != '')
		  {
			  var newP = new Number(object[i]['discount_price'].substring(cLen));
			  $( object[i]['imgType']+'_'+object[i]['obj_id'] ).store('tip:text', 'Price: <span class="old-price">' + currencySymbol + oldP.toFixed(2) + '</span> <span class="discount-price">' + currencySymbol + newP.toFixed(2) + '</span>');
		  } else
		  {
			  $( object[i]['imgType']+'_'+object[i]['obj_id'] ).store('tip:text', 'Price: ' + currencySymbol + oldP.toFixed(2));
		  }
	  }

    }

    if($('shop_menu')){
      buildFilters(filters);
    }
    //fn_init_menuslide();

    if(render=='grid')
    {
		$('dragContainer').addClass('grid');
		//$('dragContainer').set('class', 'grid');
		
		//$('dragContainer').innerHTML += '<div class="clear"></div>';
		
		var myClear = new Element('div', {
		'class': 'clear',
		'style': 'position:relative',
		'html': ''
		});
		
		myClear.injectInside($('dragContainer'));
		//myLoader();

    }
    else
    {
      // Commented this out, as it was affecting images reloading between scatter/grid modes in IE.
      // Dosent seem to break anything so far
      //$('dragContainer').removeClass('grid'); 
    }
  }
}

/*
BUILD THE FILTER MENU FROM THE JSON RETURN AR
*/
function buildFilters(filters){

  var filterlists = $$('#filters li.fli');
  filterlists.destroy();
  //filters
  var filtercount = filters.length;

  for( var i=0; i<filtercount; i++){

    var fSafeName = filters[i]['filterName'].replace('Std_','');
    var fName = filters[i]['filterName'];

    //
    // create the filter LI
    if(!$('fli_'+fName)){
      var myLI = new Element('li', {
      'id': 'fli_'+fName,
      'html': '',
      'class': 'fli'
      });
      myLI.inject($('filters'),'top');
    }

    //
    // Create the filter a tag
    if(!$('fli_a_'+fName)){

      var myFLink = new Element('a', {
      'id': 'fli_a_'+fName,
      'html': fSafeName +':<span id="label_'+fName+'">all</span>',
      'class': 'subfilter_lnk'
      });
      myFLink.inject($('fli_'+fName),'bottom');
    }

    var attCount = filters[i]['filterVals'].length;
    if(attCount>0){

      if(!$(filters[i]['filterName'])){
        var myFSubul = new Element('ul', {
        'id': filters[i]['filterName'],
        'class': 'subfilter'//,
        //'style': 'max-height:'+ (dim[1] - 260) + 'px'
        });
        myFSubul.inject($('fli_'+fName),'bottom');
      }
      //
      // GET FILTER GROUP
      var grpFilters = $$('#' + filters[i]['filterName'] + ' li');
      grpFilters.each(function(ele){
        ele.setProperty('class','disabled')
      });

      //
      // Create the filter capture fields
      if(!$('c_'+filters[i]['filterName'])){

        var theid = 'c_'+filters[i]['filterName'];
        var myInput = new Element('input',{
        'id': theid,
        'name': theid,
        'type': 'hidden'
        });
        myInput.inject($('searchCriteria'));
      }

      //
      // LOOP THROUGH THE FILTER ATTRIBUTES/OPTIONS
      for ( var n=0; n<attCount; n++){
        var theclass='';
        var fValSafe = filters[i]['filterVals'][n]['value'];
        fValSafe = fValSafe.replace(" ","_");

        if(!$(filters[i]['filterName'] + '_' + fValSafe)){

          //
          // activate the selected filter
          if($('c_'+filters[i]['filterName']) && $('c_'+filters[i]['filterName']).value == filters[i]['filterVals'][n]['val'] || filters[i]['filterVals'][n]['selected'] == 1){
            theclass = 'activeFilter';

            if(filters[i]['filterVals'][n]['nodetype'] != undefined){
              if($('c_'+filters[i]['filterName']).value == '')
              $('c_'+filters[i]['filterName']).value = filters[i]['filterVals'][n]['value'] + '.'+filters[i]['filterVals'][n]['nodetype']+'.'+filters[i]['filterVals'][n]['controlid'];
            }else{
              $('c_'+filters[i]['filterName']).value = filters[i]['filterVals'][n]['value'];
            }
          }

          //
          // build the a tag URL this is utlised to grab the value pair from (attribute = value)
          var hrefbuild = page + '/' + filters[i]['filterName']+'/'+encodeURIComponent(filters[i]['filterVals'][n]['value']);
          if(filters[i]['filterVals'][n]['nodetype'] != undefined) hrefbuild += '.'+filters[i]['filterVals'][n]['nodetype']+'.'+filters[i]['filterVals'][n]['controlid'];
          if(filters[i]['filterVals'][n]['disable']==1) theclass = 'disabled';

          //
          // Create the list item and inject into the correct filter
          var myFSubli = new Element('li', {
          'id': filters[i]['filterName'] + '_' + fValSafe,
          'html': '<a class="'+theclass+'" id="'+filters[i]['filterName'] + '_' + fValSafe + '_a"  href="'+hrefbuild+'">'+filters[i]['filterVals'][n]['value']+'</a>',
          'class': theclass
          });
          myFSubli.inject($(filters[i]['filterName']),'bottom');
        }else{
          if(filters[i]['filterVals'][n]['disable']==1)theclass = 'disabled'
          $(filters[i]['filterName'] + '_' + fValSafe).setProperty('class',theclass);
        }
      }

    }


    var getCheckedFilterVal = $('c_'+filters[i]['filterName']).value;
    if(getCheckedFilterVal != ''){
      //
      // Display attribute/item selection within label
      if(filters[i]['filterName']=='Item'){
        var itemparts = getCheckedFilterVal.split(/\./);
        $('label_'+filters[i]['filterName']).innerHTML = itemparts[0];
        if($(filters[i]['filterName'] + '_' + itemparts[0] + '_a')){
          $(filters[i]['filterName'] + '_' + itemparts[0] + '_a').setProperty('class','activeFilter');
        }
      }else{
        $('label_'+filters[i]['filterName']).innerHTML = decodeURIComponent(getCheckedFilterVal);
        if($(filters[i]['filterName'] + '_' + getCheckedFilterVal + '_a')){
          $(filters[i]['filterName'] + '_' + getCheckedFilterVal + '_a').setProperty('class','activeFilter');
        }
      }

    }else{
      $(filters[i]['filterName'] + '_all_a').setProperty('class','activeFilter');
    }


  }
  scanFilterMenu();
}

function scanFilterMenu(){

  //console.log(console,'scanfiltermenu');

  var filterSelections = $$('.subfilter li a');
  var heldaid;
  filterSelections.removeEvents('click');
  filterSelections.addEvents({
  'click':function(e){
    new Event(e).stop();
    sortflag = true;

    // extract value pair
    var plink =  $(this).href;
    var parts = plink.split(/\//);

    var criteriaVal = parts.pop();
    var criteriaEle = parts.pop();

    //
    // Is the element item and have they selected all?
    if($(this).getParent().getParent().id=='Item'){
      if($('c_Colour')){$('c_Colour').value = "";}
      if($('c_Std_Size')){$('c_Std_Size').value = "";}
      if($('c_Label')){$('c_Label').value = "";}
      // do some poker jiggery
      if(criteriaVal=='all'){
        // Get the parent category to send
        $$('#'+$(this).getParent().getParent().id+' a.activeFilter').each(function(el){
          plink = el.href;
        })

        parts = plink.split(/\//);
        criteriaVal = parts.pop();
        criteriaEle = parts.pop();

      }
    }

    filterSelections.each(function(ele){ ele.setProperty('class','') })
    //$(this).setProperty('class','activeFilter');

    if($('c_'+criteriaEle).value == criteriaVal){
      $('c_'+criteriaEle).value = '';
      $(this).setProperty('class','');
    }else{
      $('c_'+criteriaEle).value = criteriaVal;
      $(this).setProperty('class','activeFilter');
    }

    //
    // Rebuild shop menu 'sort atts' if 'item' selection is made
    if($(this).getParent().getParent().id=='Item'){

      var filterList_tmp = $(storedM);
      filterList_tmp.get('slide').hide();
      //myLoader("on");

      new Request.JSON({
        url: path_to_root + 'scripts/php/logic.php',
        async:false,
        onComplete: function(response) {
          var filters = response.filters;
          var filtercount = filters.length;
          // clear att filters then rebuild
          for( var i=0; i<filtercount; i++){
            //						var fName = filters[i]['filterName'].replace('Std_','');
            var fName = filters[i]['filterName'];
            if($('fli_'+fName)){
              $('fli_'+fName).getFirst('div').dispose();
              $('fli_'+fName).getFirst('a').getFirst('span').innerHTML='all';
              $('c_'+fName).value='';
            }
          }
          buildFilters(filters);
          initShopMenu();
          //myLoader("off");
          sortflag = false;

        }
      }).send('function=genShopMenu&element='+criteriaEle+'&val='+criteriaVal);


      var filterList_tmp = $(storedM);
      filterList_tmp.get('slide').toggle();
    }else{

      //				console.log(console,'apply filter: '+ criteriaEle + ' val: ' + criteriaVal);

      //myLoader("on");

      var searchcriteria = $$('#searchCriteria input');
      var criteriastr = '';

      //
      // GET THE PARENT DOM OBJECT
      var checkclass = $(this).getParent().className;
      if(checkclass=='disabled'){
        //
        // reset the filters
        criteriastr+= "&resetfilters=yes&lastselected="+'c_'+criteriaEle;
        var lastselected = 'c_'+criteriaEle;
      }
      searchcriteria.each(function(ele){
        if(checkclass =='disabled' && ele.id != 'c_Item'){

          if( lastselected != ele.id ){
            ele.value='';
          }

        }else{
          criteriastr += "&"+ele.id+"="+ele.value;
        }
      });


      new Request.JSON({
        url: path_to_root + 'scripts/php/logic.php',
        data: { 'do' : '1' },
        async: false,
        onComplete: function(response) {
          if($(storedM)){
            var filterList_tmp = $(storedM);
          }

          var filters = response.filters;
          var filtercount = filters.length;
          // clear att filters then rebuild
          for( var i=0; i<filtercount; i++){
            //								var fName = filters[i]['filterName'].replace('Std_','');
            var fName = filters[i]['filterName'];

            if($('fli_'+fName).getFirst('div')){
              $('fli_'+fName).getFirst('div').dispose();
            }
            //$('fli_'+fName).getFirst('a').getFirst('span').innerHTML='all';
            //$('c_'+fName).value='';
          }

          buildFilters(filters);
          initShopMenu();
          //myLoader("off");
          sortflag = false;
        }
      }).send('function=genShopMenu&page='+page+'&pageType='+pagetype+'&node_glue='+nodeglue+'&render='+render+'&screenWidth='+dim[0]+'&screenHeight='+dim[1]+'&u_layout='+myCookie+'&node_id='+node_id+criteriastr);


      if($(storedM)){
        var filterList_tmp = $(storedM);
        filterList_tmp.get('slide').toggle();
      }

      //				reloadObjs();

    }

    //what is this for?! can someone tell me?! cause so far all it does is vommit errors!
    //if($(this).getParent().className == 'disabled'){
    // do something. reset filters?
    //alert('Not available in this variation')

    //}

  }
  })

}

/*

STAGES
1/ SAVE VARIATION
2/ PROMPT LOGIN / REGISTER

*/
function fn_addtobag_nextstep(iid,stepNo){

  var additionalparams = '';
  $$('#popup_form input').each(function(el){
    additionalparams += '&'+el.id+'='+el.value;
  })

  if($('item_id')){
    var loc = $('i_location').value;
    var imgsrc = $('i_imgSrc').value;
  }else{
    var loc = $(iid).getFirst('a').get('href');
    var imgsrc = $(iid).getFirst('a').getFirst('img').get('src');
  }

  //the request path
  var rPath = path_to_root + 'scripts/php/logic.php';

  new Request.HTML({
    method: 'post',
    url: rPath,
    data: { 'do' : '1' },
    async: false,
    update: 'capture',
    onComplete: function(response) {
      initiProductDetailJs();
      sizechart();
      //       reloadObjs();
      if($('popup_form')) {
        $('popup_form').setStyle("top", "30%");
        $('popup_form').setStyle("position", "fixed");
      }
      if($('item_exists')){
        var myFx = new Fx.Tween('popup_form',{duration: '1500',property: 'opacity'});
        myFx.start.pass([1, 0],myFx).delay(1000);
      }
    }
  }).send('function=addtobag_step&stepNo='+stepNo+'&item='+iid+'&location='+loc+'&imgSrc='+imgsrc+additionalparams);
}

function fn_bypass_variation(iid){

  // get location and image source. try and locate input fields first
  if($('item_id')){
    var loc = $('i_location').value;
    var imgsrc = $('i_imgSrc').value;
  }else{
    var loc = $(iid).getFirst('a').get('href');
    var imgsrc = $(iid).getFirst('a').getFirst('img').get('src');
  }
  new Request.HTML({
    method: 'post',
    url: path_to_root + 'scripts/php/logic.php',
    data: { 'do' : '1' },
    async: false,
    update: 'capture',
    onComplete: function(response) {
      if($('item_exists')){
        var myFx = new Fx.Tween('popup_form',{duration: '1500',property: 'opacity'});
        myFx.start.pass([1, 0],myFx).delay(1000);
      }
    }
  }).send('function=addtobag&item='+iid+'&bypass=yes&location='+loc+'&imgSrc='+imgsrc);
}
//
// Add title tips into text areas to aid user on forms
function fn_input_placeholders(){
  var t_fields = $$('.hint');
  if(t_fields){
    t_fields.each(function(field){
      if(field.value == '') field.value=field.title;
      //if(field.name == 'customer_login_password') field.setProperty('type','text');
      field.addEvents({
      'blur': function(e){
        if(field.value == '') field.value=field.title;
        //if(field.name == 'customer_login_password') field.setProperty('type','text');
      },
      'focus':function(){
        if(field.name=='customer_login_password'){
          //field.setProperty('type','password');
        }
        if(field.value == field.title){
          field.value = '';
        }
      }
      })
      /*
}).up('form').observe("submit",function () {
if (field.value == field.title) {
field.value = '';
}
})*/
    })
  }
}


function makeScrollbar(content,scrollbar,handle,horizontal,ignoreMouse){
  var diff = content.getScrollSize().y - content.getSize().y;
  if(diff<=0){
    scrollbar.setStyle('display','none');
    return;
  }
  var steps = (horizontal?(content.getScrollSize().x - content.getSize().x):(content.getScrollSize().y - content.getSize().y))

  var slider = new Slider(scrollbar, handle, {
    steps: steps,
    mode: (horizontal?'horizontal':'vertical'),
    onChange: function(step){
      // Scrolls the content element in x or y direction.
      var x = (horizontal?step:0);
      var y = (horizontal?0:step);
      content.scrollTo(x,y);
    }
  })
  slider.set(0);
    //alert('here');

  if( !(ignoreMouse) ){
    // Scroll the content element when the mousewheel is used within the
    // content or the scrollbar element.
    $$(content, scrollbar).addEvent('mousewheel', function(e){
      e = new Event(e).stop();
      var step = slider.step - e.wheel * 30;
      slider.set(step);
    });
  }
  // Stops the handle dragging process when the mouse leaves the document body.
  $(document.body).addEvent('mouseleave',function(){slider.drag.stop()});
  
  //this version of mootools does not support touch gestures so we have to get
  //around it by writing them in mostly pure javascript
  var contentElement = document.getElementById(content.get('id'));
    var scrollElement = document.getElementById(scrollbar.get('id'));

    var touchScroll = function(e){
        //e = new Event(e).stop();
        var targetEvent =  e.touches.item(0); 
        //console.log(targetEvent.clientY - $(this).getPosition().y);
        var windowTop = document.documentElement.scrollTop ? 
              document.documentElement.scrollTop : 
              document.body.scrollTop;
        var top = this.scrollTop ? 
              this.scrollTop : 
              this.scrollTop;
        var fingerPos = windowTop+(targetEvent.clientY - $(this).getPosition().y);
        var diff = content.getScrollSize().y - content.getSize().y;
        var percentage = (fingerPos/content.getSize().y)*100;
        slider.set((steps/100)*percentage);
        return false;  
    }
    contentElement.ontouchmove = touchScroll;
    scrollElement.ontouchmove = touchScroll;
}

function fn_init_menuslide(){
  // animation for SHOP BY: filter menu

  $('shop_menu').getElements('a.subfilter_lnk').each(function(el){

    var filterList = el.getNext();
    filterList.set('slide', {duration: 'short', transition: Fx.Transitions.Sine.easeOut});

    filterList.slide('hide')

    el.removeEvents("click");
    el.addEvents({
    'click': function(e) {
      if(storedM && (storedM != filterList.id) && $(storedM)){
        var filterList_tmp = $(storedM);
        filterList_tmp.get('slide').hide();

      }

      //                        mySlide.toggle(); //show-hide login panel
      filterList.get('slide').toggle();

      storedM = filterList.id;
      e = new Event(e);
      e.stop();

      Element.implement(
      {
        removeStyle: function(ele)
        {
          regex  = new RegExp('[~;\\s]' + ele + '.*?[;~]', "i");
          search = '~' + this.get('style') + '~';

          this.set('style', search.replace(regex, '').replace('~', ''));
        }
      });

      //       filterList.removeStyle("height");
      filterList.setStyle("height","");


      //       filterList.getParent().removeStyle("height");
      filterList.getParent().setStyle("height","");
      //filterList.getParent().removeStyle("max-height");
      //$("Item_scrollbar").remove();

      //
      // Work out filter menu height and invoke sliderbar if required
      var h = filterList.getStyle('height');
      h = parseInt(h);
      dim = screenDimensions();
      var avail = dim[1] - 260;
      filterList.setStyle('overflow-y','hidden');
      //filterList.setStyle('max-height','none');


      //
      // Do we need a scollbar
      if( h > avail && !$(filterList.id + '_scrollbar') ){
//      if( h > avail ){

        //
        // calculate scollbar handle percentile
        // var shandlesize = h - avail;
        // shandlesize = h - shandlesize*2;
        var shandlesize = 30;

        //
        // limit heights
        filterList.setStyle('height',avail+'px');
        //filterList.getParent().setStyle('max-height',avail+'px');
        filterList.getParent().setStyle('height',avail+'px');
        //
        // not enough space create scroller
        var myscroll = new Element('div', {
        'id': filterList.id + '_scrollbar' ,
        'class': 'scrollbar',
        'style': 'height:'+ avail +'px'
        });
        myscroll.inject(filterList.getParent());
        //
        // create scroll bar handle
        var myhandle = new Element('div', {
        'id': filterList.id + '_handle' ,
        'class': 'scrollbar_handle',
        'style': 'height:'+shandlesize+'px',
        'title': 'Scroll filters'
        });
        myhandle.inject($(filterList.id + '_scrollbar'));
        //
        // Initalise scrollbar
        makeScrollbar( filterList, $(filterList.id+'_scrollbar'), $(filterList.id+'_handle'), false );

      }

      else
      {
        if ($(filterList.id + '_scrollbar'))
        {
          $(filterList.id + '_scrollbar').dispose();
        }
      }

    }
    })
  })
}

function init_scrolling_thumbs()
{
  if($('content').getElements('div.thumbs_container')) {
    $('content').getElements('div.thumbs_container').each(function(thumb_container){
      if(thumb_container)
      {
        // Work out filter menu height and invoke sliderbar if required
        $$('#'+ thumb_container.id +' a').getLast().addClass("last");
        var h =  parseInt(thumb_container.getStyle('height'));
        thumb_container.setStyle('overflow-y','hidden');

        //
        // Do we need a scollbar
        if( h > 270 ){

          //
          // calculate scollbar handle percentile
          var shandlesize = 30;//h - 270;
          //shandlesize = h - shandlesize*2;

          //
          // limit heights
          thumb_container.setStyle('height','270px');
          thumb_container.getParent().setStyle('max-height','270px');
          //
          // not enough space create scroller
          var myscroll = new Element('div', {
          'id': thumb_container.id + '_scrollbar' ,
          'class': 'scrollbar',
          'style': 'height:270px'
          });
          myscroll.inject(thumb_container.getParent());
          //
          // create scroll bar handle
          var myhandle = new Element('div', {
          'id': thumb_container.id + '_handle' ,
          'class': 'scrollbar_handle',
          'style': 'height:'+shandlesize+'px',
          'title': 'Scroll thumbnails'
          });
          myhandle.inject($(thumb_container.id + '_scrollbar'));
          //
          // Initalise scrollbar
          makeScrollbar( thumb_container, $(thumb_container.id+'_scrollbar'), $(thumb_container.id+'_handle'), false );

          //makeScrollbar(content,scrollbar,handle,horizontal,ignoreMouse)
        }
      }
    });
  }
}


function addToBasket(){
  //
  // check variations are all selected
  var atts = $$('.att select');
  var check = true;
  atts.each(
  function(el){

    if(el.name != 'att_quantity'){
      if(el.value == ''){
        check = false;
      }
    }
  }
  )
  if(check != false){

    //alert('add to basket product ' + $('pid').value);

    new Request.HTML({
      method: 'post',
      url: path_to_root + 'scripts/php/logic.php',
      data: { 'do' : '1' },
      async: false,
      onComplete: function(response) {

      }
    }).send('function=addtobasket&pid='+$('pid').value);

  }
}

function myLoader(newStatus){
	var myloadergraphic;
	switch(newStatus)
	{
		case 'on':
			// add loader graphic if it doesn't exist
			if(!$('loading')){
				myloadergraphic = new Element('div', {
					'id'	: 'loading',
					'html'	: loader,
					'class'	: 'loader'
				})
				myloadergraphic.inject($('webpage'));
			}
			break;
		case 'off':
			// kill loading graphic if it present
			if($('loading')){
				// destroy
				// added timer to ensure that clock displays in IE
				setTimeout("if($('loading')){$('loading').dispose();}",1000);
			}
			break;
		default:
			// catch any instances where newStatus has not been defined
			if(!$('loading')){
					myloadergraphic = new Element('div', {
					'id'	: 'loading',
					'html'	: loader,
					'class'	: 'loader'
				})
				myloadergraphic.inject($('webpage'));
			}
			else{
				//destroy
				// added timer to ensure that clock displays in IE
				setTimeout("if($('loading')){$('loading').dispose();}",1000);
			}
	}
}

function thingsilove_buy() {
  $$('.til-buy').each(function(el){
    el.addEvents({
    'click': function(e){
      e = new Event(e);
      e.stop();
      // Get product ID
      var pid = this.id

      new Request.HTML({
        method: 'post',
        url: path_to_root + 'scripts/php/logic.php',
        data: { 'do' : '1' },
        async: false,
        update: 'capture',
        onComplete: function(response) {
          if($('popup_form')) {
            $('popup_form').setStyle("top", "30%");
            $('popup_form').setStyle("position", "fixed");
          }
          initiProductDetailJs();
          sizechart();
        }
      }).send('function=buy&pid='+pid);

    }
    })
  });

  $('shop_bag').addEvents({
  'mouseenter': function(e){
    if(tooltipfade_fx){
      tooltipfade_fx.cancel();
    }
    var me = $('thingsILove');
    var meHover = $('thingsILoveHover');
    me.set('styles',{'display':'none'});
    me.set('opacity',0);
    meHover.set('styles',{'display':'block'});
    meHover.set('opacity',1);
  },
  'mouseleave': function(e){
    var me = $('thingsILove');
    var meHover = $('thingsILoveHover');
    me.set('styles',{'display':'block'});
    me.set('opacity',1);
    meHover.set('styles',{'display':'none'});
    meHover.set('opacity',0);
  }
  });
}

function initEcomCol(){
  myLoader("on");
  locateObjs();
  $$('#dragContainer a').each(function(el){
    el.addEvent("click",function(e){

      if(clickBlock===true){
        new Event(e).stop();
      }

    })
  })
}

function updateHtml(newHtml, element)
{
	var e = $(element);
	e.set('html', newHtml);
}

function initiProductDetailJs(){
	if(pagetype=='ecomprod'){

		initSlideShow();
		fn_input_placeholders();
		//
		// scan attribute colour opts
		if($$('.att_colours a')) {
			$$('.att_colours a').each(function(el){
				el.addEvents({
					'click': function(e){
						e = new Event(e);
						e.stop();
						var grabquery = this.search.substring(1);
						//myLoader();
						
						var newProductHtml = new Request({
							url: path_to_root + 'scripts/php/logic.php',
							onSuccess: function(responseText, responseXML) {
							
								updateHtml(responseText, 'module_dynamic_placeholder14');
								initiProductDetailJs();
								init_scrolling_thumbs();
								Rescan();
							}
						}).send('function=selectProduct&'+ grabquery);
					}
				})
			})
		}
	}else if(pagetype=='ecomcol' || pagetype=='ecomcat'){

		//
		// scan attribute colour opts
		if($$('.att_colours a')) {
			$$('.att_colours a').each(function(el){
				el.addEvents({
					'click': function(e){
						e = new Event(e);
						e.stop();
						var grabquery = this.search.substring(1);
						/*
						//myLoader();
						var func = 'addtobag';
						
						var newProductHtml = new Request({
							url: path_to_root + 'scripts/php/logic.php',
							onSuccess: function(responseText, responseXML) {
							
								updateHtml(responseText, 'capture');
								if($('popup_form')) {
									sizechart();
									$('popup_form').setStyle("top", "30%");
									$('popup_form').setStyle("position", "fixed");
								}
								initiProductDetailJs();
							}
						}).send('function='+ func +'&'+ grabquery);
						*/
						changeVariation(el);
					}
				})
			})
		}
	}else{

		fn_input_placeholders();
		// scan attribute colour opts
		if($$('.att_colours a')) {
			$$('.att_colours a').each(function(el) {
			el.addEvents({
			'click': function(e){
				e = new Event(e);
				e.stop();
				
				var grabquery = this.search.substring(1);
				var func = 'addtobag';
				if($('function') && $('function').value == 'add_to_basket'){
					//			func = $('function').value;
					func = 'buy';
				}
								
				new Request.HTML({
					url: path_to_root + 'scripts/php/logic.php',
					update: 'capture',
					onComplete: function(productObj) {
						if($('popup_form')) {
							sizechart();
							$('popup_form').setStyle("top", "30%");
							$('popup_form').setStyle("position", "fixed");
						}
						initiProductDetailJs();
						//myLoader();
					}
				}).send('function='+func+'&'+ grabquery);
		
			}
        })
      })
    }
  }
}




function changeVariation(element){

  if(pagetype=='ecomprod'){

    //
    // Check attribute.
    // 1. reload images
    // 2. reload price
    // 3. reload related products panel
    myLoader("on");
    var atts = $$('.att select');
    var additionaparams = '';
    //if(atts.length <= 2){
    // instant reload. only one option
    additionaparams = '&pid='+ element.value;
    //}

    if(element.name == 'att_Colour'){
      additionaparams += '&requestimage=yes';
    }

    new Request.HTML({
      url: path_to_root + 'scripts/php/logic.php',
      update: 'module_dynamic_placeholder14',
      onComplete: function(productObj) {
		initiProductDetailJs();
		init_scrolling_thumbs();
		myLoader("off");
		stButtons.locateElements();
		stButtons.makeButtons();
		stWidget.init();
		initZoom();

      }
    }).send('function=selectProduct&'+element.name+'='+ element.value + additionaparams);


  }else{
    //
    // Check attribute.
    myLoader("on");
    var atts = $$('.att select');
    var additionaparams = '';
    var func = 'addtobag_step';
	
	if(element.href)
	{
		// this is from the colour selections when dragging from ecomcat or ecomcol
		var urlarray = element.href.split('?');
		additionaparams = '&'+urlarray[1];
	} else
	{
    	// this is from a size select field
		additionaparams = '&pid='+ element.value;
	}

    if(element.name == 'att_Colour'){
      additionaparams += '&requestimage=yes';
    }
    if($('function') && $('function').value == 'add_to_basket'){
      //			func = $('function').value;
      func = 'buy';
    }


    new Request.HTML({
      url: path_to_root + 'scripts/php/logic.php',
      update: 'capture',
      onComplete: function(productObj) {

		if($('popup_form')) {
			sizechart();
			$('popup_form').setStyle("top", "30%");
			$('popup_form').setStyle("position", "fixed");
		}
        initiProductDetailJs();
        myLoader("off");

      }
    }).send('function='+func+'&stepNo=2&'+element.name+'='+ element.value + additionaparams);

  }

}

function callForShopMenu(criteriaEle,criteriaVal){
  //var filterList_tmp = $(storedM);
  //filterList_tmp.get('slide').hide()

  // Hidden product images are showing for a split second, call the initSlideShow() function
  // here to stop that happening
  initSlideShow();

  myLoader("on");
  new Request.JSON({
    url: path_to_root + 'scripts/php/logic.php',
    async:false,
    onComplete: function(response) {
      //alert("got shop menu");
      var filters = response.filters;
      var filtercount = filters.length;
      // clear att filters then rebuild
      /*for( var i=0; i<filtercount; i++){
      //						var fName = filters[i]['filterName'].replace('Std_','');
      var fName = filters[i]['filterName'];
      if($('fli_'+fName)){
      $('fli_'+fName).getFirst('div').dispose();
      $('fli_'+fName).getFirst('a').getFirst('span').innerHTML='all';
      $('c_'+fName).value='';
      }
      }
      */
      buildFilters(filters);
      initShopMenu();
      myLoader("off");
      sortflag = false;

    }
  }).send('function=genShopMenu&element='+criteriaEle+'&val='+criteriaVal);
}

function openCenter(elementid, fixedpos) {
  //var scrolltop = document.getScrollTop();
  var windowsize = document.getSize();
  $(elementid).style.display = 'block';
  $(elementid).setStyle('z-index','999');
  if (fixedpos===true) {
    $(elementid).setStyle('position','fixed');
  } else {
    $(elementid).setStyle('position','absolute');
  }
  var elementsize = $(elementid).getSize();
  var centerpos = new Object();
  centerpos.y = Math.floor(windowsize.y / 2) - Math.floor(elementsize.y / 2);// + scrolltop;
  centerpos.x = Math.floor(windowsize.x / 2) - Math.floor(elementsize.x / 2);
  $(elementid).setPosition(centerpos);
}

function sendTil(){
  if($$('.til-sendfriend-link')) {
    $$('.til-sendfriend-link').each(function(el){
      el.addEvents({'click': function(e){
        e = new Event(e);
        e.stop();
        new Request.HTML({
          url: path_to_root + 'scripts/php/custom/forms/sendTil.php',
          data: { 'do' : '1' },
          async: false,
          update: 'sendtil-form',
          onComplete: function(response) {
            $('sendtil-form').setStyle("position", "relative");
      			openCenter('sendtil-form',true);
          }
        }).send();
      }
      })
    })
  }
}

function close_sendtil(){
  $('sendtil-form').setStyle('display','none');
  if($('sendtil-form-content')) {
    $('sendtil-form-content').dispose();
  }
}

function sizechart(){
  if($$('.size_guide')) {
    $$('.size_guide').each(function(el){
      el.addEvents({'click': function(e){
        e = new Event(e);
        e.stop();
        // open the size chart
        new Request.HTML({
          url: path_to_root + 'scripts/php/custom/forms/sizeChart.php',
          data: { 'do' : '1' },
          async: false,
          update: 'capture_size',
          onComplete: function(response) {
			$('capture').setStyle("position", "relative");
			//var pagescroll = window.getScroll();
			//$('sizechart').setPosition({y:pagescroll.y});
		  }

        }).send('function=size_chart');
      }
      })
    })
  }
}

function close_sizechart(){
  if($('sizechart')) {
    $('sizechart').dispose();
		$('capture').setStyle("position", "absolute");
  }
}

function fn_notnow() {
  if($('popup_form')) {
    $('popup_form').dispose();
  }
}

function print_r (array, return_val) {
  // Prints out or returns information about the specified variable
  //
  // version: 1006.1915
  // discuss at: http://phpjs.org/functions/print_r    // +   original by: Michael White (http://getsprink.com)
  // +   improved by: Ben Bryan
  // +      input by: Brett Zamir (http://brett-zamir.me)
  // +      improved by: Brett Zamir (http://brett-zamir.me)
  // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)    // -    depends on: echo
  // *     example 1: print_r(1, true);
  // *     returns 1: 1

  var output = "", pad_char = " ", pad_val = 4, d = this.window.document;    var getFuncName = function (fn) {
    var name = (/\W*function\s+([\w\$]+)\s*\(/).exec(fn);
    if (!name) {
      return '(Anonymous)';
    }        return name[1];
  };

  var repeat_char = function (len, pad_char) {
    var str = "";        for (var i=0; i < len; i++) {
      str += pad_char;
    }
    return str;
  };
  var formatArray = function (obj, cur_depth, pad_val, pad_char) {
    if (cur_depth > 0) {
      cur_depth++;
    }
    var base_pad = repeat_char(pad_val*cur_depth, pad_char);
    var thick_pad = repeat_char(pad_val*(cur_depth+1), pad_char);
    var str = "";
    if (typeof obj === 'object' && obj !== null && obj.constructor && getFuncName(obj.constructor) !== 'PHPJS_Resource') {
      str += "Array\n" + base_pad + "(\n";
      for (var key in obj) {
        if (obj[key] instanceof Array) {
          str += thick_pad + "["+key+"] => "+formatArray(obj[key], cur_depth+1, pad_val, pad_char);                } else {
            str += thick_pad + "["+key+"] => " + obj[key] + "\n";
          }
      }
      str += base_pad + ")\n";        } else if (obj === null || obj === undefined) {
        str = '';
      } else { // for our "resource" class
        str = obj.toString();
      }
      return str;
  };

  output = formatArray(array, 0, pad_val, pad_char);
  if (return_val !== true) {
    if (d.body) {
      this.echo(output);
    }        else {
      try {
        d = XULDocument; // We're in XUL, so appending as plain text won't work; trigger an error out of XUL
        this.echo('<pre xmlns="http://www.w3.org/1999/xhtml" style="white-space:pre;">'+output+'</pre>');
      }            catch (e) {
        this.echo(output); // Outputting as plain text may work in some plain XML
      }
    }
    return true;    } else {
      return output;
    }
}

function arrayContains(a, obj) {
    var i = a.length;
    while (i--) {
       if (a[i] === obj) {
           return true;
       }
    }
    return false;
}

//The product zoom functionality
function initZoom(){
  if($('detailsScrollContent') && $('scrollbarDetails')&&$('handleDetails')){
    makeScrollbar( $('detailsScrollContent'), $('scrollbarDetails'), $('handleDetails') );
    
  }
  if($('deliveryScrollContent')&& $('scrollbarDelivery')&& $('handleDelivery')){
    //we have to make the block vivisble for the split second so we can get the correct hight of the
    //inner content so the scorll bar works
    $('delivery-and-return').setStyle('display','block');
    makeScrollbar( $('deliveryScrollContent'), $('scrollbarDelivery'), $('handleDelivery') );
    $('delivery-and-return').setStyle('display','none');
  }
  
  
  //if the gallery images exists
  if($('gallery-images')){
    
        
    //The images
    var galleryImages = $('gallery-images').getElements('a')
    
    if(galleryImages.length <= 1){
      $$('.gallery-nav').set('styles',{'display':'none'})
    }
    if(galleryImages.length < 4){
      var liWidth = 0;
      var liImages = $('gallery-nav-thumbs').getElements('li')
      for(var i=0;i<liImages.length;i++){
	liWidth+=liImages[i].getSize().x+20;
      }
      $('gallery-nav-left').set('styles',{'display':'none'});
      $('gallery-nav-right').set('styles',{'display':'none'});
      $('gallery-nav-thumbs').set('styles',{'margin-left':((346-liWidth)/2) + "px"});
    }
    
    
    //height and width of the product detail section
    var size = $('product_detail').getSize();
    var zoomWindowW = size.x;
    var zoomWindowH = $('gallery-images').getSize().y + 42;
    
    //create the zoom holder
    //kill existing zoom holder if exists
    if($('image-zoom')){
    	$('image-zoom').dispose();
    }
    var zoomImage = new Element('div', {
      id: 'image-zoom',
      'class': 'image-zoom loading',
      html: '&nbsp',
      events: {
	click:function(){
	  $(this).setStyle('display','none')
	}
	
      },
      styles: {
	width:zoomWindowW,
	height:zoomWindowH,
	position:'absolute',
	top:'89px',
	right:'0px',
	'z-index':20,
	display:'none'
      }
    });    
    //insert zoom image in #content
    zoomImage.inject($('content'));    
    
    var i =0;
    var zoomHeight = 0;
    var zoomWidth = 0;
    var imageHeight = 0;
    var imageWidth = 0;
    var previewBoxH = 0;
    var previewBoxW = 0;
    var urls=[];
    var loading = false;

    
    while(i<galleryImages.length){
	
	//add events for each image
        galleryImages[i].addEvents({
    
	  mouseover:function(){
	    $('product_detail').set('styles',{
		      "display":"none"
		    })
	  
	    currentA = this;
	    imageUrl = $(this).get('href');
	    currentImage = $(this).getElements('img');
	    currentImage = currentImage[0];
	    
	    //if the image has not already been laoded
	    if(!arrayContains(urls,imageUrl)){
	      loading = true;
	      //add the loading class
	      zoomImage.addClass('loading')	      
	      //remove the current background image so the loading gif will be displayed
		.set('styles',{	"background-image": "","display":"block","background-position": "center center"});
	    
	      //the dimensions of the current image
	      imageHeight = currentImage.height;
	      imageWidth = currentImage.width;
	      
	      //get the image url
	      imageUrl = $(this).get('href');
	      
	      //we need to create a copy in memory so we can determine the width and height of the bigger image
	      var tempImage = new Element('img', {
		src: imageUrl,
		events: {
		  load: function(){
		    loading = false;
		    //when the image is loaded we can determine the height and width and perform the nessasary calculations
		    urls.push(imageUrl);
		    zoomHeight = this.height;
		    zoomWidth = this.width;
		    
		    imageZoom = true;
		    
		    
		    zoomImage
		      .removeClass('loading')
		      .set('styles',{
			"background-image": "url("+imageUrl +")",
			"display":"block"
		      })
		    
		    //We set the size of the preview box by working out the percentage difference between the big image and the zoom window height
		    // (zoomWindowH/zoomHeight)*100 and then making the previewbox the the percentage the small image
		    // so if the small image that the user hovers over is 555px height and the large image is 1200px then
		    // the small image is 46.25% the size of the big image so the preview box will be 256.6875px height(46.25% of 555)
		    previewBoxH = (imageHeight/100)*(zoomWindowH/zoomHeight)*100;
		    previewBoxW = (imageWidth/100)*(zoomWindowW/zoomWidth)*100;
		    
		    //set the preview box dimensions
		    $(currentA).getElement('div').set('styles',{
		      'width':(previewBoxW)+'px',
		      'height':(previewBoxH)+'px'
		    })
		  }
		}
	      });
	    }else{
	      //the image is already loaded so change the image and it will work fine
	      zoomImage
		.removeClass('loading')
		.set('styles',{
		  "background-image": "url("+imageUrl +")",
		  "display":"block"
		})
	      
	    }
	    //set the image opacity to 0.7 so we can see the preview box behind it
	    currentImage.set('styles',{'cursor':'move','opacity':0.7});
	    
	    
	    
	  },
	  mouseout:function(){
	    $('product_detail').set('styles',{
		      "display":"block"
		    })
	    //hide the zoom image
	    zoomImage
		    .set('styles',{
		      "display":"none"
		    })
	    currentImage.set('styles',{'opacity':1});
	  },
	  mousemove:function(e){
	    if(!loading){
	    //on mouse move we to get the position of the mouse inside the small image so we can
	    //change the zoom images backgorund movement based on this
	    
	    //below gets the x and y co-ordinates of the mouse and then subtracts the position of the
	    //image which gives us the x y co-ordinates inside the image
            var x = Math.round(e.page.x - $(this).getPosition().x),
            y = Math.round(e.page.y - $(this).getPosition().y),
	    //this gets the pixel difference between the little and big images
            wDiff = zoomWidth - zoomWindowW,
            hDiff = zoomHeight - zoomWindowH
	    //we get the percentage of where the mouse is in the small image
            wPercent = x/(imageWidth)*100,
            hPercent = y/(imageHeight)*100;
	    //this then allows to set exactly where the big image should display
            zoomLeft = ((wDiff/100)*(wPercent)),
            zoomTop = ((hDiff/100)*(hPercent)),
            zoomBox = $('image-zoom')
            ;
            
            zoomBox.set('styles',{
                'background-position':'-'+zoomLeft+'px -'+zoomTop+'px'
            })
	    
	    
            var previewBox = $(this).getElement('div');
            wPDiff = currentImage.width - previewBox.getSize().x,
            HPDiff = currentImage.height - previewBox.getSize().y,
            wPercent = x/(imageWidth)*100,
            hPercent = y/(imageHeight)*100;
            zoomLeft = ((wPDiff/100)*(wPercent)),
            zoomTop = ((HPDiff/100)*(hPercent))
	    
	    
            
            
            previewBox.set('styles',{
                'left':(zoomLeft)+'px',
                'top':zoomTop+'px'
            })
	    }

	    
	  },
	  click:function(){
	    return false;
	  }	  
	})
	
	
	
        i++;
    }
  }
}

window.addEvent('domready', initZoom);
