//ACCORDIAN SCRIPT START


var ddaccordion={
	ajaxloadingmsg: '<br />Loading Content...', //customize HTML to output while Ajax content is being fetched (if applicable)

	headergroup: {}, //object to store corresponding header group based on headerclass value
	contentgroup: {}, //object to store corresponding content group based on headerclass value

	preloadimages:function($images){
		$images.each(function(){
			var preloadimage=new Image()
			preloadimage.src=this.src
		})
	},

	expandone:function(headerclass, selected){ //PUBLIC function to expand a particular header
		this.toggleone(headerclass, selected, "expand")
	},

	collapseone:function(headerclass, selected){ //PUBLIC function to collapse a particular header
		this.toggleone(headerclass, selected, "collapse")
	},

	expandall:function(headerclass){ //PUBLIC function to expand all headers based on their shared CSS classname
		var $headers=this.headergroup[headerclass]
		this.contentgroup[headerclass].filter(':hidden').each(function(){
			$headers.eq(parseInt($(this).attr('contentindex'))).trigger("evt_accordion")
		})
	},

	collapseall:function(headerclass){ //PUBLIC function to collapse all headers based on their shared CSS classname
		var $headers=this.headergroup[headerclass]
		this.contentgroup[headerclass].filter(':visible').each(function(){
			$headers.eq(parseInt($(this).attr('contentindex'))).trigger("evt_accordion")
		})
	},

	toggleone:function(headerclass, selected, optstate){ //PUBLIC function to expand/ collapse a particular header
		var $targetHeader=this.headergroup[headerclass].eq(selected)
		var $subcontent=this.contentgroup[headerclass].eq(selected)
		if (typeof optstate=="undefined" || optstate=="expand" && $subcontent.is(":hidden") || optstate=="collapse" && $subcontent.is(":visible"))
			$targetHeader.trigger("evt_accordion")
	},

	ajaxloadcontent:function($targetHeader, $targetContent, config, callback){
		var ajaxinfo=$targetHeader.data('ajaxinfo')

		function handlecontent(content){ //nested function
			if (content){ //if ajax content has loaded
				ajaxinfo.cacheddata=content //remember ajax content 
				ajaxinfo.status="cached" //set ajax status to cached
				if ($targetContent.queue("fx").length==0){ //if this content isn't currently expanding or collapsing
					$targetContent.hide().html(content) //hide loading message, then set sub content's HTML to ajax content
					ajaxinfo.status="complete" //set ajax status to complete
					callback() //execute callback function- expand this sub content
				}
			}
			if (ajaxinfo.status!="complete"){
				setTimeout(function(){handlecontent(ajaxinfo.cacheddata)}, 100) //call handlecontent() again until ajax content has loaded (ajaxinfo.cacheddata contains data)
			}
		} //end nested function

		if (ajaxinfo.status=="none"){ //ajax data hasn't been fetched yet
			$targetContent.html(this.ajaxloadingmsg)
			$targetContent.slideDown(config.animatespeed)
			ajaxinfo.status="loading" //set ajax status to "loading"
			$.ajax({
				url: ajaxinfo.url, //path to external menu file
				error:function(ajaxrequest){
					handlecontent('Error fetching content. Server Response: '+ajaxrequest.responseText)
				},
				success:function(content){
					content=(content=="")? " " : content //if returned content is empty, set it to "space" is content no longer returns false/empty (hasn't loaded yet)
					handlecontent(content)
				}
			})
		}
		else if (ajaxinfo.status=="loading")
			handlecontent(ajaxinfo.cacheddata)
	},

	expandit:function($targetHeader, $targetContent, config, useractivated, directclick, skipanimation){
		var ajaxinfo=$targetHeader.data('ajaxinfo')
		if (ajaxinfo){ //if this content should be fetched via Ajax
			if (ajaxinfo.status=="none" || ajaxinfo.status=="loading")
				this.ajaxloadcontent($targetHeader, $targetContent, config, function(){ddaccordion.expandit($targetHeader, $targetContent, config, useractivated, directclick)})
			else if (ajaxinfo.status=="cached"){
				$targetContent.html(ajaxinfo.cacheddata)
				ajaxinfo.cacheddata=null
				ajaxinfo.status="complete"
			}
		}
		this.transformHeader($targetHeader, config, "expand")
		$targetContent.slideDown(skipanimation? 0 : config.animatespeed, function(){
			config.onopenclose($targetHeader.get(0), parseInt($targetHeader.attr('headerindex')), $targetContent.css('display'), useractivated)
			if (config.postreveal=="gotourl" && directclick){ //if revealtype is "Go to Header URL upon click", and this is a direct click on the header
				var targetLink=($targetHeader.is("a"))? $targetHeader.get(0) : $targetHeader.find('a:eq(0)').get(0)
				if (targetLink) //if this header is a link
					setTimeout(function(){location=targetLink.href}, 200) //ignore link target, as window.open(targetLink, targetLink.target) doesn't work in FF if popup blocker enabled
			}
		})
	},

	collapseit:function($targetHeader, $targetContent, config, isuseractivated){
		this.transformHeader($targetHeader, config, "collapse")
		$targetContent.slideUp(config.animatespeed, function(){config.onopenclose($targetHeader.get(0), parseInt($targetHeader.attr('headerindex')), $targetContent.css('display'), isuseractivated)})
	},

	transformHeader:function($targetHeader, config, state){
		$targetHeader.addClass((state=="expand")? config.cssclass.expand : config.cssclass.collapse) //alternate btw "expand" and "collapse" CSS classes
		.removeClass((state=="expand")? config.cssclass.collapse : config.cssclass.expand)
		if (config.htmlsetting.location=='src'){ //Change header image (assuming header is an image)?
			$targetHeader=($targetHeader.is("img"))? $targetHeader : $targetHeader.find('img').eq(0) //Set target to either header itself, or first image within header
			$targetHeader.attr('src', (state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse) //change header image
		}
		else if (config.htmlsetting.location=="prefix") //if change "prefix" HTML, locate dynamically added ".accordprefix" span tag and change it
			$targetHeader.find('.accordprefix').html((state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse)
		else if (config.htmlsetting.location=="suffix")
			$targetHeader.find('.accordsuffix').html((state=="expand")? config.htmlsetting.expand : config.htmlsetting.collapse)
	},

	urlparamselect:function(headerclass){
		var result=window.location.search.match(new RegExp(headerclass+"=((\\d+)(,(\\d+))*)", "i")) //check for "?headerclass=2,3,4" in URL
		if (result!=null)
			result=RegExp.$1.split(',')
		return result //returns null, [index], or [index1,index2,etc], where index are the desired selected header indices
	},

	getCookie:function(Name){ 
		var re=new RegExp(Name+"=[^;]+", "i") //construct RE to search for target name/value pair
		if (document.cookie.match(re)) //if cookie found
			return document.cookie.match(re)[0].split("=")[1] //return its value
		return null
	},

	setCookie:function(name, value){
		document.cookie = name + "=" + value + "; path=/"
	},

	init:function(config){
	document.write('<style type="text/css">\n')
	document.write('.'+config.contentclass+'{display: none}\n') //generate CSS to hide contents
	document.write('a.hiddenajaxlink{display: none}\n') //CSS class to hide ajax link
	document.write('<\/style>')
	jQuery(document).ready(function($){
		ddaccordion.urlparamselect(config.headerclass)
		var persistedheaders=ddaccordion.getCookie(config.headerclass)
		ddaccordion.headergroup[config.headerclass]=$('.'+config.headerclass) //remember header group for this accordion
		ddaccordion.contentgroup[config.headerclass]=$('.'+config.contentclass) //remember content group for this accordion
		var $headers=ddaccordion.headergroup[config.headerclass]
		var $subcontents=ddaccordion.contentgroup[config.headerclass]
		config.cssclass={collapse: config.toggleclass[0], expand: config.toggleclass[1]} //store expand and contract CSS classes as object properties
		config.revealtype=config.revealtype || "click"
		config.revealtype=config.revealtype.replace(/mouseover/i, "mouseenter")
		if (config.revealtype=="clickgo"){
			config.postreveal="gotourl" //remember added action
			config.revealtype="click" //overwrite revealtype to "click" keyword
		}
		if (typeof config.togglehtml=="undefined")
			config.htmlsetting={location: "none"}
		else
			config.htmlsetting={location: config.togglehtml[0], collapse: config.togglehtml[1], expand: config.togglehtml[2]} //store HTML settings as object properties
		config.oninit=(typeof config.oninit=="undefined")? function(){} : config.oninit //attach custom "oninit" event handler
		config.onopenclose=(typeof config.onopenclose=="undefined")? function(){} : config.onopenclose //attach custom "onopenclose" event handler
		var lastexpanded={} //object to hold reference to last expanded header and content (jquery objects)
		var expandedindices=ddaccordion.urlparamselect(config.headerclass) || ((config.persiststate && persistedheaders!=null)? persistedheaders : config.defaultexpanded)
		if (typeof expandedindices=='string') //test for string value (exception is config.defaultexpanded, which is an array)
			expandedindices=expandedindices.replace(/c/ig, '').split(',') //transform string value to an array (ie: "c1,c2,c3" becomes [1,2,3]
		if (expandedindices.length==1 && expandedindices[0]=="-1") //check for expandedindices value of [-1], indicating persistence is on and no content expanded
			expandedindices=[]
		if (config["collapseprev"] && expandedindices.length>1) //only allow one content open?
			expandedindices=[expandedindices.pop()] //return last array element as an array (for sake of jQuery.inArray())
		if (config["onemustopen"] && expandedindices.length==0) //if at least one content should be open at all times and none are, open 1st header
			expandedindices=[0]
		$headers.each(function(index){ //loop through all headers
			var $header=$(this)
			if (/(prefix)|(suffix)/i.test(config.htmlsetting.location) && $header.html()!=""){ //add a SPAN element to header depending on user setting and if header is a container tag
				//$('<span class="accordprefix"></span>').prependTo(this)
				//$('<span class="accordsuffix"></span>').appendTo(this)
			}
			$header.attr('headerindex', index+'h') //store position of this header relative to its peers
			$subcontents.eq(index).attr('contentindex', index+'c') //store position of this content relative to its peers
			var $subcontent=$subcontents.eq(index)
			var $hiddenajaxlink=$subcontent.find('a.hiddenajaxlink:eq(0)') //see if this content should be loaded via ajax
			if ($hiddenajaxlink.length==1){
				$header.data('ajaxinfo', {url:$hiddenajaxlink.attr('href'), cacheddata:null, status:'none'}) //store info about this ajax content inside header
			}
			var needle=(typeof expandedindices[0]=="number")? index : index+'' //check for data type within expandedindices array- index should match that type
			if (jQuery.inArray(needle, expandedindices)!=-1){ //check for headers that should be expanded automatically (convert index to string first)
				ddaccordion.expandit($header, $subcontent, config, false, false, !config.animatedefault) //3rd last param sets 'isuseractivated' parameter, 2nd last sets isdirectclick, last sets skipanimation param
				lastexpanded={$header:$header, $content:$subcontent}
			}  //end check
			else{
				$subcontent.hide()
				config.onopenclose($header.get(0), parseInt($header.attr('headerindex')), $subcontent.css('display'), false) //Last Boolean value sets 'isuseractivated' parameter
				ddaccordion.transformHeader($header, config, "collapse")
			}
		})
		$headers.bind("evt_accordion", function(e, isdirectclick){ //assign CUSTOM event handler that expands/ contacts a header
				var $subcontent=$subcontents.eq(parseInt($(this).attr('headerindex'))) //get subcontent that should be expanded/collapsed
				if ($subcontent.css('display')=="none"){
					ddaccordion.expandit($(this), $subcontent, config, true, isdirectclick) //2nd last param sets 'isuseractivated' parameter
					if (config["collapseprev"] && lastexpanded.$header && $(this).get(0)!=lastexpanded.$header.get(0)){ //collapse previous content?
						ddaccordion.collapseit(lastexpanded.$header, lastexpanded.$content, config, true) //Last Boolean value sets 'isuseractivated' parameter
					}
					lastexpanded={$header:$(this), $content:$subcontent}
				}
				else if (!config["onemustopen"] || config["onemustopen"] && lastexpanded.$header && $(this).get(0)!=lastexpanded.$header.get(0)){
					ddaccordion.collapseit($(this), $subcontent, config, true) //Last Boolean value sets 'isuseractivated' parameter
				}
 		})
		$headers.bind(config.revealtype, function(){
			if (config.revealtype=="mouseenter"){
				clearTimeout(config.revealdelay)
				var headerindex=parseInt($(this).attr("headerindex"))
				config.revealdelay=setTimeout(function(){ddaccordion.expandone(config["headerclass"], headerindex)}, config.mouseoverdelay || 0)
			}
			else{
				$(this).trigger("evt_accordion", [true]) //last parameter indicates this is a direct click on the header
				return false //cancel default click behavior
			}
		})
		$headers.bind("mouseleave", function(){
			clearTimeout(config.revealdelay)
		})
		config.oninit($headers.get(), expandedindices)
		$(window).bind('unload', function(){ //clean up and persist on page unload
			$headers.unbind()
			var expandedindices=[]
			$subcontents.filter(':visible').each(function(index){ //get indices of expanded headers
				expandedindices.push($(this).attr('contentindex'))
			})
			if (config.persiststate==true && $headers.length>0){ //persist state?
				expandedindices=(expandedindices.length==0)? '-1c' : expandedindices //No contents expanded, indicate that with dummy '-1c' value?
				ddaccordion.setCookie(config.headerclass, expandedindices)
			}
		})
	})
	}
}

//preload any images defined inside ajaxloadingmsg variable
ddaccordion.preloadimages(jQuery(ddaccordion.ajaxloadingmsg).filter('img'))
//ACCORDIAN SCRIPT END


//nav js start
function gotoZoom(book, page, image, height, width) {
	var thispage = window.location.href.substr(window.location.href.toLowerCase().indexOf('.co.uk/') + 7);
	var win = window.open('izoom/zoom.htm?b=' + book + '&p=' + page + '&i=' + image + '&h=' + height + '&w=' + width + '&l=' + thispage, 'shotzoom', 'height=540,width=720,scrollbars=yes');
	win.focus();
}

function gotoPage(book, page, occurance, page_type, shot_lnk)
{
	if(!page_type) page_type='spread';
	if(!shot_lnk) shot_lnk='0';
	top.location.href = '/page.asp?b=' + book + '&p=' + page + '&o=' + occurance + '&t=' + page_type + '&s=' + shot_lnk;
}

function gotoMoviePage(book, page, occurance, page_type, shot_lnk, movie)
{
	if(!page_type) page_type='spread';
	if(!shot_lnk) shot_lnk='0';
	top.location.href = '/page.asp?b=' + book + '&p=' + page + '&o=' + occurance + '&t=' + page_type + '&s=' + shot_lnk + '&movie=' + movie;
}

function setLastLocation() {
	//top.addCookie('lastlocation', location.href);
	top.lastLocation = location.href;
}

function getLastLocation() {
	//return(top.getCookie('lastlocation'));
	return(top.lastLocation);
}

function OpenClearanceProduct(url) {
    var leftVal = (screen.width - 1000) / 2;
    var topVal = (screen.height - 380) / 2;
    var newWindow = window.open(url, 'productpopup', 'menubar=0,resizable=0,scrollbars=1,width=825,height=400,left=' + leftVal + ',top=' + topVal);
    newWindow.focus();
}

function OpenDealofTheDayProduct(url) {
    var leftVal = (screen.width - 1000) / 2;
    var topVal = (screen.height - 380) / 2;
    var newWindow = window.open(url, 'productpopup', 'menubar=0,resizable=0,scrollbars=1,width=825,height=400,left=' + leftVal + ',top=' + topVal);
    newWindow.focus();
}


function openShot(book, page, occurance, shot, status_code) {
	gotoPage(book, page, occurance, 'spread', shot);
}

//function openShotPopup(s0, book, page, occurance, shot, status_code, upsell, referrer) {
//	if(!status_code) status_code='';
//	status_code='';
//	if(!referrer) referrer =  location.href;

//	referrer = referrer.replace(/&(ic|iq|status_code)=[^&]*/gi, '');
//	referrer = escape(referrer);

//	var popupWindow = window.open('/iteminfo.htm?s0=' + s0 + '&b=' + book + '&p=' + page + '&o=' + occurance + '&s=' + shot + '&status_code=' + status_code + '&u=' + upsell + '&r=' + referrer, 'shotview', 'height=500,width=580,scrollbars=no');
//}

function openShotPopup(s0, title, id) {
//	if(!status_code) status_code='';
//	status_code='';
//	if(!referrer) referrer =  location.href;

//	referrer = referrer.replace(/&(ic|iq|status_code)=[^&]*/gi, '');
//	referrer = escape(referrer);

    var popW = 580, popH = 500;
	var leftPos = (screen.width/2)-(popW/2);
	var topPos = (screen.height/2)-(popH/2);
	
	title = cleanText(title);
	//window.open ("prod_details.aspx?id="+id+"&s0="+s0, "shotview", "location=0,status=1,scrollbars=1,width=" + popW + ",height=" + popH + ",resizable=0,top=" + topPos + ",left="+ leftPos);
	window.open ("/product/entertainment/for-the-home/dvds/"+title+"/"+id, "shotview", "location=0,status=1,scrollbars=1,width=" + popW + ",height=" + popH + ",resizable=0,top=" + topPos + ",left="+ leftPos);

	//var popupWindow = window.open('/iteminfo.htm?s0=' + s0 + '&b=' + book + '&p=' + page + '&o=' + occurance + '&s=' + shot + '&status_code=' + status_code + '&u=' + upsell + '&r=' + referrer, 'shotview', 'height=500,width=580,scrollbars=no');
}

function cleanText(text) {
    var cleaned = text.toLowerCase();
    cleaned = cleaned.replace(/[^a-z0-9 ]/gi, '');
    cleaned = cleaned.replace(/ +/gi, '-');
    return(cleaned);
}

function openMovie(site, book, page, occurance, shot, status_code, movie) {
	if(!status_code) status_code='';
	//var popupWindow = window.open('/iteminfo.htm?b=' + book + '&p=' + page + '&o=' + occurance + '&s=' + shot + '&status_code=' + status_code + '&movie=' + movie, 'shotview', 'height=500,width=580,scrollbars=no');
	var popupWindow = window.open('/iteminfo.htm?s0=' + site + '&b=' + book + '&p=' + page + '&o=' + occurance + '&s=' + shot + '&status_code=' + status_code + '&movie=' + movie, 'shotview', 'height=500,width=580,scrollbars=no');

}

function moreInfo(book, page, occurance, article) {
	var url = '/moreinfo.asp?b=' + book + '&p=' + page + '&o=' + occurance + '&a=' + article;
	top.location = url;
}

function openShotPopupOLD(book, page, occurance, shot, status_code) {
	if(!status_code) status_code='';

	var popupWindow = window.open('/iteminfo.htm?b=' + book + '&p=' + page + '&o=' + occurance + '&s=' + shot + '&status_code=' + status_code, 'shotview', 'height=500,width=580,scrollbars=no');
}

function gotoShot(book, page, occurance, shot, status_code) {
	var referrerURL = '';

	if(!status_code) status_code='';

	if(document.forms['mainform'])
		if(document.forms['mainform'].elements['refererURL'])
			referrerURL = escape(document.forms['mainform'].elements['refererURL'].value);

	window.location.href = '/shot.asp?b=' + book + '&p=' + page + '&s=' + shot + '&status_code=' + status_code + '&r=' + referrerURL;
}

function gotoMovie(book, page, occurance, shot, status_code, movie) {
	var referrerURL = '';

	if(!status_code) status_code='';

	if(document.forms['mainform'])
		if(document.forms['mainform'].elements['refererURL'])
			referrerURL = escape(document.forms['mainform'].elements['refererURL'].value);

	window.location.href = '/shot.asp?b=' + book + '&p=' + page + '&s=' + shot + '&status_code=' + status_code + '&r=' + referrerURL + '&movie=' + movie;
}

function gotoAccessoryShot(s0, book, page, occurance, shot, status_code, movie, movie_book, movie_page, movie_occurance, movie_shot) {
	var referrerURL = '';

	if(!status_code) status_code='';

	if(document.forms['mainform'])
		if(document.forms['mainform'].elements['sourceURL'])
			referrerURL = escape(document.forms['mainform'].elements['sourceURL'].value);

	window.location.href = '/shot.asp?s0=' + s0 + '&b=' + book + '&p=' + page + '&s=' + shot + '&status_code=' + status_code + '&r=' + referrerURL + '&frommovie=' + movie+ '&movie_book=' + movie_book + '&movie_page=' + movie_page + '&movie_occurance=' + movie_occurance + '&movie_shot=' + movie_shot;
}

function gotoLocation(locationLink) {
	top.location.href = locationLink;
}

function shopMore() {
	if(getLastLocation())
		location.href = getLastLocation();
	else
		gotoHome();
}

function findPage()
{
	var page = document.forms['pagesearch'].elements['pagesrch'].value.toUpperCase();
	var book = document.forms['pagesearch'].elements['book'].value;

	page = page.replace(/[^0-9]/g, '');

	if(page.length > 0) {
		top.location.href = '/search.asp?t=page&p=' + escape(page) + '&b=' + escape(book) + '&l=' + escape(top.location.href);
	} else {
		document.forms['pagesearch'].elements['pagesrch'].value = '';
		document.forms['pagesearch'].elements['pagesrch'].focus();
		alert('Please enter a page to search for.');
	}
}

function findItem() {
	var code = document.forms['itemsearch'].elements['code01'].value.toUpperCase() +
		document.forms['itemsearch'].elements['code02'].value.toUpperCase() +
		document.forms['itemsearch'].elements['code03'].value.substr(0,2).toUpperCase();

	code = code.replace(/[^0-9]/g, '');

	if(code.length > 0) {

		while(code.length < 8)
			code = '0' + code;

		top.location.href = '/search.asp?t=item&c=' + escape(code) + '&l=' + escape(top.location.href);
	} else {
		document.forms['itemsearch'].elements['code01'].value = '';
		document.forms['itemsearch'].elements['code02'].value = '';
		document.forms['itemsearch'].elements['code03'].value = '';
		document.forms['itemsearch'].elements['code01'].focus();
		alert('Please enter an item reference to search for.');
	}
}

function gotoProduct(book, page, occurance, shot) {
	//openShot(book, page, shot);
	gotoPage(book, page, occurance, 'spread', shot);
}

function gotoHome() {
	gotoLocation('home.asp');
}

function moveNext(inputBox) {
	if(document.forms['itemsearch'].elements['code0' + inputBox].value.length > 2)
		document.forms['itemsearch'].elements['code0' + (inputBox + 1)].focus();
}

function gotoHelp() {
	window.open('/help.htm', 'help', 'height=400,width=580,scrollbars=yes');
}

//nav js end


// homepage js start

function getTopSearch(content) {
    $("#homepage_topsearch").empty();
    $newcontent = $(content).find("table#hometopsearch_table");
    $("#homepage_topsearch").append($newcontent);
}

function getUpsell(content) {

    $("#homepage_upsell").empty();
    $newcontent = $(content).find("table#homeupsell_table");
    $("#homepage_upsell").append($newcontent);
    $("#FiveDivs").show();
}

$(document).ready(function() {
    //only required on homepage
    if (location.pathname == '/' || location.pathname.indexOf('/homepage.aspx') != -1)    
        $('#ajaxFrame').attr('src', document.ajaxsource);
        
});

// homepage js end

//mousewheel start

// using bind
$('#my_elem').bind('mousewheel', function(event, delta) {
    console.log(delta);
});

// using the event helper
//$('#my_elem').mousewheel(function(event, delta) {
//    console.log(delta);
//});
//// using bind
$('#my_elem').bind('mousewheel', function(event, delta) {
    console.log(delta);
});

// using the event helper
//$('#my_elem').mousewheel(function(event, delta) {
//    console.log(delta);
//});

//mounsewheel end

// jquery tinty tips start

/***********************************************************/
/*                    tinyTips Plugin                      */
/*                      Version: 1.0                       */
/*                      Mike Merritt                       */
/*                 Updated: Feb 4th, 2010                  */
/***********************************************************/
(function(a){a.fn.tinyTips=function(b){var c='<div class="tinyTip"><div class="header"></div><div class="content"></div><div class="bottom">&nbsp;</div></div>';var d=300;var e;var f;a(this).hover(function(){a("body").append(c);e=a("div.tinyTip");e.hide();if(b==="title"){var g=a(this).attr("title")}else{if(b!=="title"){var g=b}}a(".tinyTip .content").html(g);f=a(this).attr("title");a(this).attr("title","");var j=e.height()+17;var h=(((e.width()-10)/2))-(a(this).width()/2);var k=a(this).offset();var i=k;i.top=k.top-j;i.left=k.left-h;e.css("position","absolute").css("z-index","1000");e.css(i).fadeIn(d)},function(){a(this).attr("title",f);a("div.tinyTip").fadeOut(d,function(){a(this).remove()})})}})(jQuery);

// jquery tinytips end

//thickbox js start

/*
 * Thickbox 3.1 - One Box To Rule Them All.
 * By Cody Lindley (http://www.codylindley.com)
 * Copyright (c) 2007 cody lindley
 * Licensed under the MIT License: http://www.opensource.org/licenses/mit-license.php
*/
		  
var tb_pathToImage = "/ss/images/common/loadingAnimation.gif";

/*!!!!!!!!!!!!!!!!! edit below this line at your own risk !!!!!!!!!!!!!!!!!!!!!!!*/

//on page load call tb_init
$(document).ready(function(){   
	tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
	imgLoader = new Image();// preload image
	imgLoader.src = tb_pathToImage;
});

//add thickbox to href & area elements that have a class of .thickbox
function tb_init(domChunk){
	$(domChunk).click(function(){
	var t = this.title || this.name || null;
	var a = this.href || this.alt;
	var g = this.rel || false;
	tb_show(t,a,g);
	this.blur();
	return false;
	});
}

function tb_show(caption, url, imageGroup) {//function called when the user clicks on a thickbox link

	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			$("body","html").css({height: "100%", width: "100%"});
			$("html").css("overflow","hidden");
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
				$("body").append("<iframe id='TB_HideSelect'></iframe><div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}else{//all others
			if(document.getElementById("TB_overlay") === null){
				$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
				$("#TB_overlay").click(tb_remove);
			}
		}
		
		if(tb_detectMacXFF()){
			$("#TB_overlay").addClass("TB_overlayMacFFBGHack");//use png overlay so hide flash
		}else{
			$("#TB_overlay").addClass("TB_overlayBG");//use background and opacity
		}
		
		if(caption===null){caption="";}
		$("body").append("<div id='TB_load'><img src='"+imgLoader.src+"' /></div>");//add loader to the page
		$('#TB_load').show();//show loader
		
		var baseURL;
	   if(url.indexOf("?")!==-1){ //ff there is a query string involved
			baseURL = url.substr(0, url.indexOf("?"));
	   }else{ 
	   		baseURL = url;
	   }
	   
	   var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
	   var urlType = baseURL.toLowerCase().match(urlString);

		if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){//code to show images
				
			TB_PrevCaption = "";
			TB_PrevURL = "";
			TB_PrevHTML = "";
			TB_NextCaption = "";
			TB_NextURL = "";
			TB_NextHTML = "";
			TB_imageCount = "";
			TB_FoundURL = false;
			if(imageGroup){
				TB_TempArray = $("a[@rel="+imageGroup+"]").get();
				for (TB_Counter = 0; ((TB_Counter < TB_TempArray.length) && (TB_NextHTML === "")); TB_Counter++) {
					var urlTypeTemp = TB_TempArray[TB_Counter].href.toLowerCase().match(urlString);
						if (!(TB_TempArray[TB_Counter].href == url)) {						
							if (TB_FoundURL) {
								TB_NextCaption = TB_TempArray[TB_Counter].title;
								TB_NextURL = TB_TempArray[TB_Counter].href;
								TB_NextHTML = "<span id='TB_next'>&nbsp;&nbsp;<a href='#'>Next &gt;</a></span>";
							} else {
								TB_PrevCaption = TB_TempArray[TB_Counter].title;
								TB_PrevURL = TB_TempArray[TB_Counter].href;
								TB_PrevHTML = "<span id='TB_prev'>&nbsp;&nbsp;<a href='#'>&lt; Prev</a></span>";
							}
						} else {
							TB_FoundURL = true;
							TB_imageCount = "Image " + (TB_Counter + 1) +" of "+ (TB_TempArray.length);											
						}
				}
			}

			imgPreloader = new Image();
			imgPreloader.onload = function(){		
			imgPreloader.onload = null;
				
			// Resizing large images - orginal by Christian Montoya edited by me.
			var pagesize = tb_getPageSize();
			var x = pagesize[0] - 150;
			var y = pagesize[1] - 150;
			var imageWidth = imgPreloader.width;
			var imageHeight = imgPreloader.height;
			if (imageWidth > x) {
				imageHeight = imageHeight * (x / imageWidth); 
				imageWidth = x; 
				if (imageHeight > y) { 
					imageWidth = imageWidth * (y / imageHeight); 
					imageHeight = y; 
				}
			} else if (imageHeight > y) { 
				imageWidth = imageWidth * (y / imageHeight); 
				imageHeight = y; 
				if (imageWidth > x) { 
					imageHeight = imageHeight * (x / imageWidth); 
					imageWidth = x;
				}
			}
			// End Resizing
			
			TB_WIDTH = imageWidth + 30;
			TB_HEIGHT = imageHeight + 60;
			$("#TB_window").append("<a href='' id='TB_ImageOff' title='Close'><img id='TB_Image' src='"+url+"' width='"+imageWidth+"' height='"+imageHeight+"' alt='"+caption+"'/></a>" + "<div id='TB_caption'>"+caption+"<div id='TB_secondLine'>" + TB_imageCount + TB_PrevHTML + TB_NextHTML + "</div></div><div id='TB_closeWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div>"); 		
			
			$("#TB_closeWindowButton").click(tb_remove);
			
			if (!(TB_PrevHTML === "")) {
				function goPrev(){
					if($(document).unbind("click",goPrev)){$(document).unbind("click",goPrev);}
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_PrevCaption, TB_PrevURL, imageGroup);
					return false;	
				}
				$("#TB_prev").click(goPrev);
			}
			
			if (!(TB_NextHTML === "")) {		
				function goNext(){
					$("#TB_window").remove();
					$("body").append("<div id='TB_window'></div>");
					tb_show(TB_NextCaption, TB_NextURL, imageGroup);				
					return false;	
				}
				$("#TB_next").click(goNext);
				
			}

			document.onkeydown = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				} else if(keycode == 190){ // display previous image
					if(!(TB_NextHTML == "")){
						document.onkeydown = "";
						goNext();
					}
				} else if(keycode == 188){ // display next image
					if(!(TB_PrevHTML == "")){
						document.onkeydown = "";
						goPrev();
					}
				}	
			};
			
			tb_position();
			$("#TB_load").remove();
			$("#TB_ImageOff").click(tb_remove);
			$("#TB_window").css({display:"block"}); //for safari using css instead of show
			};
			
			imgPreloader.src = url;
		}else{//code to show html
			
			var queryString = url.replace(/^[^\?]+\??/,'');
			var params = tb_parseQuery( queryString );

			TB_WIDTH = (params['width']*1) + 30 || 630; //defaults to 630 if no paramaters were added to URL
			TB_HEIGHT = (params['height']*1) + 40 || 440; //defaults to 440 if no paramaters were added to URL
			ajaxContentW = TB_WIDTH - 30;
			ajaxContentH = TB_HEIGHT - 45;
			
			if(url.indexOf('TB_iframe') != -1){// either iframe or ajax window		
					urlNoQuery = url.split('TB_');
					$("#TB_iframeContent").remove();
					if(params['modal'] != "true"){//iframe no modal
					//$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>close</a> or Esc Key</div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton' title='Close'>Close window&nbsp;&nbsp;&nbsp;<img src='/Images/TemplateImages/closewindow.gif' align='absbottom' /></a></div></div><iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;' > </iframe>");
					
					}else{//iframe modal
					$("#TB_overlay").unbind();
						$("#TB_window").append("<iframe frameborder='0' hspace='0' src='"+urlNoQuery[0]+"' id='TB_iframeContent' name='TB_iframeContent"+Math.round(Math.random()*1000)+"' onload='tb_showIframe()' style='width:"+(ajaxContentW + 29)+"px;height:"+(ajaxContentH + 17)+"px;'> </iframe>");
					}
			}else{// not an iframe, ajax
					if($("#TB_window").css("display") != "block"){
						if(params['modal'] != "true"){//ajax no modal
						$("#TB_window").append("<div id='TB_title'><div id='TB_ajaxWindowTitle'>"+caption+"</div><div id='TB_closeAjaxWindow'><a href='#' id='TB_closeWindowButton'>close</a> or Esc Key</div></div><div id='TB_ajaxContent' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px'></div>");
						}else{//ajax modal
						$("#TB_overlay").unbind();
						$("#TB_window").append("<div id='TB_ajaxContent' class='TB_modal' style='width:"+ajaxContentW+"px;height:"+ajaxContentH+"px;'></div>");	
						}
					}else{//this means the window is already up, we are just loading new content via ajax
						$("#TB_ajaxContent")[0].style.width = ajaxContentW +"px";
						$("#TB_ajaxContent")[0].style.height = ajaxContentH +"px";
						$("#TB_ajaxContent")[0].scrollTop = 0;
						$("#TB_ajaxWindowTitle").html(caption);
					}
			}
					
			$("#TB_closeWindowButton").click(tb_remove);
			
				if(url.indexOf('TB_inline') != -1){	
					$("#TB_ajaxContent").append($('#' + params['inlineId']).children());
					$("#TB_window").unload(function () {
						$('#' + params['inlineId']).append( $("#TB_ajaxContent").children() ); // move elements back when you're finished
					});
					tb_position();
					$("#TB_load").remove();
					$("#TB_window").css({display:"block"}); 
				}else if(url.indexOf('TB_iframe') != -1){
					tb_position();
					if($.browser.safari){//safari needs help because it will not fire iframe onload
						$("#TB_load").remove();
						$("#TB_window").css({display:"block"});
					}
				}else{
					$("#TB_ajaxContent").load(url += "&random=" + (new Date().getTime()),function(){//to do a post change this load method
						tb_position();
						$("#TB_load").remove();
						tb_init("#TB_ajaxContent a.thickbox");
						$("#TB_window").css({display:"block"});
					});
				}
			
		}

		if(!params['modal']){
			document.onkeyup = function(e){ 	
				if (e == null) { // ie
					keycode = event.keyCode;
				} else { // mozilla
					keycode = e.which;
				}
				if(keycode == 27){ // close
					tb_remove();
				}	
			};
		}
		
	} catch(e) {
		//nothing here
	}
}

//helper functions below
function tb_showIframe(){
	$("#TB_load").remove();
	$("#TB_window").css({display:"block"});
}

function tb_remove() {
 	$("#TB_imageOff").unbind("click");
	$("#TB_closeWindowButton").unbind("click");
	$("#TB_window").fadeOut("fast",function(){$('#TB_window,#TB_overlay,#TB_HideSelect').trigger("unload").unbind().remove();});
	$("#TB_load").remove();
	if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
		$("body","html").css({height: "auto", width: "auto"});
		$("html").css("overflow","");
	}
	document.onkeydown = "";
	document.onkeyup = "";
	return false;
}

function tb_position() {
$("#TB_window").css({marginLeft: '-' + parseInt((TB_WIDTH / 2),10) + 'px', width: TB_WIDTH + 'px'});
	if ( !(jQuery.browser.msie && jQuery.browser.version < 7)) { // take away IE6
		$("#TB_window").css({marginTop: '-' + parseInt((TB_HEIGHT / 2),10) + 'px'});
	}
}

function tb_parseQuery ( query ) {
   var Params = {};
   if ( ! query ) {return Params;}// return empty object
   var Pairs = query.split(/[;&]/);
   for ( var i = 0; i < Pairs.length; i++ ) {
      var KeyVal = Pairs[i].split('=');
      if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
   }
   return Params;
}

function tb_getPageSize(){
	var de = document.documentElement;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth) || document.body.clientWidth;
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight) || document.body.clientHeight;
	arrayPageSize = [w,h];
	return arrayPageSize;
}

function tb_detectMacXFF() {
  var userAgent = navigator.userAgent.toLowerCase();
  if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox')!=-1) {
    return true;
  }
}


// thickbox js end

//ddaccordian init start 

ddaccordion.init({ //top level headers initialization
	headerclass: "expandable", //Shared CSS class name of headers group that are expandable
	contentclass: "categoryitems", //Shared CSS class name of contents group
	revealtype: "click", //Reveal content when user clicks or onmouseover the header? Valid value: "click", "clickgo", or "mouseover"
	mouseoverdelay: 200, //if revealtype="mouseover", set delay in milliseconds before header expands onMouseover
	collapseprev: true, //Collapse previous content (so only one open at any time)? true/false 

    //need to pass an index here to open depending on that page 
    defaultexpanded: [], //index of content(s) open by default [index1, index2, etc]. [] denotes no content

	onemustopen: false, //Specify whether at least one header should be open always (so never all headers closed)
	animatedefault: false, //Should contents open by default be animated into view?
	persiststate: false, //persist state of opened contents within browser session?
	toggleclass: ["", "openheader"], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
	togglehtml: ["prefix", "", ""], //Additional HTML added to the header when it's collapsed and expanded, respectively  ["position", "html1", "html2"] (see docs)
	animatespeed: "fast", //speed of animation: integer in milliseconds (ie: 200), or keywords "fast", "normal", or "slow"
	oninit:function(headers, expandedindices){ //custom code to run when headers have initalized
		//do nothing
	},
 	onopenclose:function(header, index, state, isuseractivated){ //custom code to run whenever a header is opened or closed
		//do nothing
	}
})

ddaccordion.init({ //2nd level headers initialization
	headerclass: "subexpandable", //Shared CSS class name of sub headers group that are expandable
	contentclass: "subcategoryitems", //Shared CSS class name of sub contents group
	revealtype: "click", //Reveal content when user clicks or onmouseover the header? Valid value: "click" or "mouseover
	mouseoverdelay: 200, //if revealtype="mouseover", set delay in milliseconds before header expands onMouseover
	collapseprev: true, //Collapse previous content (so only one open at any time)? true/false 
	defaultexpanded: [], //index of content(s) open by default [index1, index2, etc]. [] denotes no content
	onemustopen: false, //Specify whether at least one header should be open always (so never all headers closed)
	animatedefault: false, //Should contents open by default be animated into view?
	persiststate: false, //persist state of opened contents within browser session?
	toggleclass: ["opensubheader", "closedsubheader"], //Two CSS classes to be applied to the header when it's collapsed and expanded, respectively ["class1", "class2"]
	togglehtml: ["none", "", ""], //Additional HTML added to the header when it's collapsed and expanded, respectively  ["position", "html1", "html2"] (see docs)
	animatespeed: "fast", //speed of animation: integer in milliseconds (ie: 200), or keywords "fast", "normal", or "slow"
	oninit:function(headers, expandedindices){ //custom code to run when headers have initalized
		//do nothing
	},
	onopenclose:function(header, index, state, isuseractivated){ //custom code to run whenever a header is opened or closed
		//do nothing
	}
})

// ddaccordian init end


//product details page - tabbing
function switchTab(elem, type) {

    var headergroup = $(elem).parent();
    headergroup.children("span").addClass("tabinactive");
    headergroup.children("span").removeClass("tabactive");

    $(elem).addClass("tabactive");
    $(elem).removeClass("tabinactive");

    //get index
    var idx = $(elem).parent().attr('id');
    idx = idx.replace('tabheaders', '');
    var contentId = 'tabcontents' + idx;

    $('div#' + contentId).children('div').hide();
    $('div#tabContent' + type + idx).show();
}

function switchTabLink(elem, type) {
    
    var headergroup = $(elem).parent();
    headergroup.children("a").addClass("tabinactive");
    headergroup.children("a").removeClass("tabactive");

    $(elem).addClass("tabactive");
    $(elem).removeClass("tabinactive");

    //get index
    var idx = $(elem).parent().attr('id');
    idx = idx.replace('tabheaders', '');
    var contentId = 'tabcontents' + idx;

    $('div#' + contentId).children('div').hide();
    $('div#tabContent' + type + idx).show();
}


function switchUpsellTab(elemId, type) {

    var elem = $('#' + elemId);
    
    var headergroup = $(elem).parent();
    headergroup.children("a").addClass("tabinactive");
    headergroup.children("a").removeClass("tabactive");

    $(elem).addClass("tabactive");
    $(elem).removeClass("tabinactive");

    //get index
    var idx = $(elem).parent().attr('id');
    idx = idx.replace('tabheaders', '');
    var contentId = 'tabcontents' + idx;

    $('div#' + contentId).children('div').hide();
    $('div#tabContent' + type + idx).show();

}
//END OF product details page - tabbing


//GLOBAL METHODS - USE THROUGHTOUT THE SITE

function MM_openBrWindow(theURL, winName, features) { //v2.0
    window.open(theURL, winName, features);
}

function setLastLocation() {
    top.lastLocation = location.href;
}

//to show number of items in basket on header
function insertBasket(content) {

    $("#headerbasket_dummy").append(content);
    $("#headerbasket_number").empty();
    $("#headerbasket_tools").empty();

    if ($("#headerbasket_dummy").find("div#basketempty").length > 0) {
    
        var zeroitem = "<div id='count'><span id='numbervalue'>00</span>items</div>";
        $("#headerbasket_number").append(zeroitem);
        $("#headerbasket_tools").append($("#headerbasket_dummy").find("div#basketempty"));

    } else {

        if ($("#headerbasket_dummy").find("div#count").length > 0) {

            var amount = $("#headerbasket_dummy").find("div#count").html();
            amount = amount.replace("items", "");
            amount = amount.replace("item", "");
            amount = amount.replace("&nbsp;", "");
            amount = $.trim(amount);

            if (amount.length == 1) {
                amount = "0" + amount;
            }

            var iteminfo;

            if (amount == "01") {
                iteminfo = "<div id='count'><span id='numbervalue'>" + amount + "</span>item</div>";
            } else {
                iteminfo = "<div id='count'><span id='numbervalue'>" + amount + "</span>items</div>";
            }
            $("#headerbasket_number").append(iteminfo);

        }

        if ($("#headerbasket_dummy").find("div#basketlink").length > 0) {
            $("#headerbasket_dummy").find("div#basketlink").html($("#headerbasket_dummy").find("div#basketlink").html());
            $("#headerbasket_tools").append($("#headerbasket_dummy").find("div#basketlink"));
        }

        if ($("#headerbasket_dummy").find("div#viewbasketlink").length > 0) {
            $("#headerbasket_dummy").find("div#viewbasketlink").html($("#headerbasket_dummy").find("div#viewbasketlink").html());
            $("#headerbasket_tools").append($("#headerbasket_dummy").find("div#viewbasketlink"));
        }

        var basketURL = $("#headerbasket_link a").attr('href');

try {
        if (customerHasLogin != undefined && customerHasLogin) {

            if ($("#headerbasket_dummy").find("div#checkoutlink").length > 0) {
                $("#headerbasket_tools").append($("#headerbasket_dummy").find("div#checkoutlink"));
            } else {
                $("#headerbasket_tools").append('<div id="checkoutlink"><a target="_parent" href="' + basketURL + '">Go to Checkout</a></div>');
                //<a target="_parent" href="http://www.24ace.co.uk/ss/order/basket.jsp?refererURL=http://my.egl1024.24ace.co.uk/homeware/by-room/bathroom/accessories/1/3dtoiletseat/5&amp;partnerCode=WMPS">Basket</a>
            }
        }
} catch (dontcare) {}
  
        $("#headerbasket_tools a").attr('href', basketURL);

        // var samplecheckout = "<div id='checkoutlink'><a href='https://www.24studio.co.uk/ss/CheckoutServlet?mode=change_delivery_address&success_url=/CheckoutServlet&src=/CheckoutServlet&error_url=/logon/logon.jsp&amp;ts=1273592037266' target='_parent'>Checkout</a></div>";
        //$("#headerbasket_tools").append(samplecheckout);

    }
}



//END OF GLOBAL METHODS - USE THROUGHTOUT THE SITE
