	$(document).ready(function(){
		// new accordion
		$.global.Accordion = new $.Accordion();
		// new tabs
		initTabs();
	});

	$.Accordion = function(){
		var elements = [];
		var ah  = $("h3.pr-selected");
		var aho = $("h3.pr-selected-open");	// For Magazine always open state
		var ab  = $("#product-related .on");

		$("h3.pr-selected a").add("h3.pr-selected-open a").click(function (event) {
			event.preventDefault();
		});

		if((ah.length == 0) && (aho.length == 0)) {
			$("#product-related")[0].style.display = "none";
		}

		if((ah.length == ab.length) && ah.length > 0) {
			for(var i=0; i<ah.length; i++) {
				elements.push([ah[i], ab[i]]);

     /* As we iterate through, we set inactive modules to have the 'off' styling.
      * Generally we want all the modules to begin in a closed state.
      * However if there is a certain module that we want to default to open, we can simply add logic such that this block is skipped for that module.
      *
      * The easiest way to do that is simply to assign a 'special' class (accord-default-open) to the module that should default open.
      **/

		   if((i != 0) || (i === 0 && (! (/accord-default-open/).test(elements[i][0].className)))) {
					elements[i][0].className = "h_off";
					elements[i][1].className = "wrap9a off";
				}

				elements[i][0].onclick = function(e) {

					for(var k=0; k<elements.length; k++) {
						elements[k][0].className = "h_off";
						elements[k][1].className = "wrap9a off";
					}

					for (var j = 0; j < elements.length; j++) {
				  	if (this === elements[j][0]) {
				  		elements[j][0].className = "pr-selected";
				  		elements[j][1].className = "wrap9a on";
				  		break;
				  	}
				  }

					return false;
				};
			}

    /*
     * Fire the onclick handler of the first module, as soon as possible.
     * I believe the purpose of this block was to ensure that service calls fire.
     * However, currently we *never* want to fire service calls upon dom ready.
     * so I have commented this out.

			if(ab[0].getElementsByTagName("img")) {
				var test = ah[0].getElementsByTagName("a")[0].getAttribute("onclick") + "";
				test = test.replace("function anonymous()", "");
				eval(test);
			}
     */

		}

		$("a.hasService").click(function(e) {
			var headerLink = $(e.target);
			if(headerLink.data("loaded") == null) {
				headerLink.data("loaded", 1);
				var tabContent = $(headerLink.parents('div')[0]).next('div');
				var params = headerLink.parents("h3").find("span").html();
				while(params.search("&amp;") != -1) {
					params = params.replace("&amp;", "&")
				}
				ui.request({
					baseURL: $.hosts.commServices,
					parameters: '?' + params,
					handleResponse: function (response) {
						tabContent.html(response.output != 'NoItemsThere' ? response.output : 'There are no related EssentiaLists at this time.');
					}
				});
			}
		})
		this.callback = function(response) {
			if (response.output != 'NoItemsThere') {
				$("#product-related .on").html(response.output);
			}
			else {
				$("#product-related .on").html("There are no related EssentiaLists at this time.");
			}
		}
	}

	function initTabs() {

		$("#product-overview-content").delegate("mouseover", {
			"img.preview": function(e) {
				ProductPreview.triggerMouseOver($(e.target).parents("a").get(0));
			}
		});
		$("#product-overview-content").delegate("mouseout", {
			"img.preview": function(e) {
				ProductPreview.triggerMouseOut()
			}
		});

		var urlvalue = false;
		var displayonly = false;
		/* PARSE URL VALUES */
		 var objURL = new Object();
		 window.location.search.replace(
		 new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),

		 function( $0, $1, $2, $3 ){
		 	objURL[ $1 ] = $3;
		 }
		 );

		 for (var strKey in objURL){
		 	 if(strKey == "tabname") {
			 	urlvalue = objURL[strKey];
			 }
			 if(strKey == "displayonly") {
			 	displayonly = objURL[strKey];
			 }
		}
		if(displayonly != false) {
			switch(displayonly) {
				case "CRV":
			 	 	urlvalue = "custreview";
					break;
				case "REV":
			 	 	urlvalue = "edreviews";
					break;
				default:
			 	 	urlvalue = "features";
			}
		}

		if(urlvalue && $("#tab-" + urlvalue)) {

			$("#product-overview-tabs li a img").each(function(inc, node) {
				if(node.src.search("tab_off_" + urlvalue) != -1) {
					node.src = node.src.replace("_off", "_roll");
					node.id = "product-tab-on";
				} else {
					node.src = node.src.replace("_roll", "_off");
					node.id = "";
				}
			});

			$(".ds-as-box").each(function(inc, node) {
				node.style.display = "none";
			})

			if($("#tab-" + urlvalue).find(".loader").length > 0) {
					var eanData = $("#tab-" + urlvalue + " .loader").get(0).id;
					var ean = eanData.split("_")[1];
					var pt = eanData.split("_")[0];

					ui.request({
						baseURL: $.hosts.commServices,
						parameters: "?uiAction=CustomerReviewsPageCallback&bnOutput=1&page=ReviewsCallback&sort=0&ean="+ean + "&pt="+pt,
						callback: {name: "cbf", value: "CallbackCustomerReviews"}
					});

				}

			$("#tab-" + urlvalue).get(0).style.display = "block";



			if(window.location.hash && window.location.hash.length > 0) {
				window.location = window.location.hash;
			}
		}

		var tabs = $("#product-overview-tabs li a");
		for(var i=0; i<tabs.length; i++) {
			tabs[i].onclick = function(e) {


				var target = getElement(e);
				if(target.src == null) {
					target = target.getElementsByTagName("img")[0];
				}
				var tab_on = $("#product-tab-on")[0];

				tab_on.src = tab_on.src.replace("_roll", "_off");
				var tabtohide = tab_on.src.split("_off_")[1];
				tabtohide = tabtohide.split(".")[0];

				$("#tab-" + tabtohide)[0].style.display = "none";

				$("#product-tab-on")[0].id = " ";

				target.src = target.src.replace("_off", "_roll");
				target.id = "product-tab-on";

				var tabtoshow = target.src.split("_roll_")[1];
				tabtoshow = tabtoshow.split(".")[0];

				if($("#tab-" + tabtoshow).find(".loader").length > 0) {

					var eanData = $("#tab-" + tabtoshow + " .loader").get(0).id;
					var ean = eanData.split("_")[1];
					var pt = eanData.split("_")[0];

					ui.request({
						baseURL: $.hosts.commServices,
						parameters: "?uiAction=CustomerReviewsPageCallback&bnOutput=1&page=ReviewsCallback&sort=0&ean="+ean + "&pt="+pt,
						callback: {name: "cbf", value: "CallbackCustomerReviews"}
					});
				}

				$("#tab-" + tabtoshow)[0].style.display = "block";

				return false;
			};
		}
	}

	function CallbackCustomerReviews(req) {
		var tabReview = $("#tab-custreview");
		tabReview.get(0).innerHTML = req.output;

        var nextLink = $('a.custRevTabPaginate');
        nextLink.each( function(i) {
            $(this).click(function(e) { getReviews(e); cmBNSendTagPaginateCustomerReviews(e); });
        });

		//alert('testing CoreMetrics 2');

		if (typeof cmCreatePageElementTag !== "undefined") {



			var reviewedProductEAN = "";
			var reviewedProductTitle = "";

			if ($('.reviewedProductEAN').exists() && $('.reviewedProductEAN').text() != "") {
				reviewedProductEAN = $('.reviewedProductEAN').text();
			}

			if ($('.reviewedProductTitle').exists() && $('.reviewedProductTitle').text() != "") {
				reviewedProductTitle = $('.reviewedProductTitle').text();
			}
			//alert('testing: calling cmCreatePageElementTag: ' + (reviewedProductEAN + " " + reviewedProductTitle).substr(0,49));
			cmCreatePageElementTag ((reviewedProductEAN + " " + reviewedProductTitle).substr(0,49), "Product Page - Customer Reviews");
			//alert('testing - sent')

		}



	}

    function CallbackCustomerReviewsPostback(req) {
		var tabReview = $("#reviewBox");
		tabReview.html(req.output);

	    var nextLink = $('a.custRevTabPaginate');
        nextLink.each( function(i) {

            $(this).click(function(e) { getReviews(e); cmBNSendTagPaginateCustomerReviews(e); });
        });
	}

	function cmBNGetPageinationChangeLabel (pageChangeLabel) {

		var currentPageIndexDataSource = "";
		var currentPageNumber = 0;
		var outputString = "";
		var pageChangeString ="";

		if ($('.currentPageIndexDataSource').exists() && $('.currentPageIndexDataSource').text() != "") {
			currentPageIndexDataSource = $('.currentPageIndexDataSource').text();
		}

		currentPageNumber = Number (currentPageIndexDataSource) + 1; // convert from a zero base index

		if (pageChangeLabel) { // if pageChangeLabel exisits, make it a number and add it to the currentPageNumber to make the out label
			pageChangeString = " to " + (currentPageNumber + Number (pageChangeLabel));
		}
		outputString = "[pg " + currentPageNumber + pageChangeString + "]"; // ie: Next [pg 3 to 4]
		[]
		return outputString;
	}

	function cmBNSendTagPaginateCustomerReviews (e) {

		if (String(e.target.id).indexOf('Next') != -1) {
			cmBNSendTagNextCustomerReviews();
		}
		else if (String(e.target.id).indexOf('Prev') != -1) {
			cmBNSendTagPrevCustomerReviews();
		}
	}

	function truncateElementBy(pagLabel) {
		var elementLength = pagLabel.length;
		return 49 - elementLength;
	}

	function cmBNSendTagNextCustomerReviews() {

		if (typeof cmCreatePageElementTag !== "undefined") {

			var pagiCharLength = truncateElementBy(cmBNGetPageinationChangeLabel(1));

			//alert('testing: calling cmCreatePageElementTag: ' + (cmBNGetProductDetails()).substr(0, pagiCharLength) + cmBNGetPageinationChangeLabel(1));
			cmCreatePageElementTag ((cmBNGetProductDetails()).substr(0, pagiCharLength) + cmBNGetPageinationChangeLabel(1), "Product Page - Customer Reviews");
		//alert('testing - sent');

		}



	}

	function cmBNSendTagPrevCustomerReviews() {

		if (typeof cmCreatePageElementTag !== "undefined") {

			var pagiCharLength = truncateElementBy(cmBNGetPageinationChangeLabel(-1));

			//alert('testing: calling cmCreatePageElementTag: ' + (cmBNGetProductDetails()).substr(0, pagiCharLength) + cmBNGetPageinationChangeLabel(1));
		 	cmCreatePageElementTag ((cmBNGetProductDetails()).substr(0, pagiCharLength) + cmBNGetPageinationChangeLabel(-1), "Product Page - Customer Reviews");

			//alert('testing - sent');

		}

	}


	function cmBNGetProductDetails () {

		var reviewedProductEAN = "";
		var reviewedProductTitle = "";

		if ($('.reviewedProductEAN').exists() && $('.reviewedProductEAN').text() != "") {
			reviewedProductEAN = $('.reviewedProductEAN').text();
		}

		if ($('.reviewedProductTitle').exists() && $('.reviewedProductTitle').text() != "") {
			reviewedProductTitle = $('.reviewedProductTitle').text();
		}

		return reviewedProductEAN + " " + reviewedProductTitle;

	}


    function getReviews(e) {
        e.preventDefault(e);

        var ele =  $("#" + e.target.id);
        var params = ele.attr('name');

        ui.request({
		    baseURL: $.hosts.commServices,
		    parameters: params,
            callback: {name: "cbf", value: "CallbackCustomerReviewsPostback"}
	    });

        $("#reviewData").html("<div class='wrap20'><p><br /><img src='" + $.hosts.resources + "/presources/images/ajax-loader.gif' /> Loading...<br /><br /></p></div>");
    }

	function getElement(e) {
		if(window.event && window.event.srcElement) {
			return window.event.srcElement;
		} else {
			return e.target;
		}
	}

	function openTab(val) {
		if(val && $("#tab-" + val)[0]) {
			$("#product-overview-tabs li a img").each(function(inc, node) {
				if(node.src.search("tab_roll_" + val) != -1) { return; }

				if(node.src.search("tab_off_" + val) != -1) {
					node.src = node.src.replace("_off", "_roll");
					node.id = "product-tab-on";
				} else {
					node.src = node.src.replace("_roll", "_off");
					node.id = "";
				}
			});

			$(".ds-as-box").each(function(inc, node) {
				node.style.display = "none";
			})
			$("#tab-" + val)[0].style.display = "block";

			if($("#tab-" + val).find(".loader").length > 0) {

					// This block along with the request below should be made into there own functions,
					// as we do this three times in this file.
					var eanData = $("#tab-" + val + " .loader").get(0).id;
					var ean = eanData.split("_")[1];
					var pt = eanData.split("_")[0];


					ui.request({
						baseURL: $.hosts.commServices,
						parameters: "?uiAction=CustomerReviewsPageCallback&bnOutput=1&page=ReviewsCallback&startpage=1&sort=0&ean="+ean+"&pt="+pt,
						callback: {name: "cbf", value: "CallbackCustomerReviews"}
					});
				}
		}
	}

	var wasCalled = 0;

	function loadAndShow(e) {
		$.global.EmailAFriend.compatible($("#tellafriendLink"));
		return false;
	}

	function friendCallback() {
		showWindow();
		wasCalled = 1;
	}

	var genericStyleSheet = function(data) {
		var output = "<ul>";
		var products = data.xml.getElementsByTagName('Product');
		var j = 0;
		var url = "";
		for(var i=0; i<products.length; i++) {
			if(j < 5 && products[i].getElementsByTagName("EAN")[0].firstChild.nodeValue != data.ean) {
				if(data.isBTOB == "true") {
					url = products[i].getElementsByTagName("URL")[0].firstChild.nodeValue.replace("http://search", "http://btobsearch");
					url = url.replace("http://video", "http://btobvideo");
					url = url.replace("http://music", "http://btobmusic");
					url += "&btob=y";
				} else {
					url = products[i].getElementsByTagName("URL")[0].firstChild.nodeValue;
				}
				output += "<li><strong><a onmouseover='ProductPreview.triggerMouseOver(this)' onmouseout='ProductPreview.triggerMouseOut()' href='"+url+"'>"+products[i].getElementsByTagName("Title")[0].firstChild.nodeValue +"</a></strong></li>";
				j++;
			}
		}
		output += "</ul>";
		if(this.moreLink != false && this.hideMainMore == true && j > 4) {
			if(this.isBTOB == "true") {
				this.moreLink = this.moreLink.replace("http://search", "http://btobsearch");
				this.moreLink = this.moreLink.replace("http://video", "http://btobvideo");
				this.moreLink = this.moreLink.replace("http://music", "http://btobmusic");
				this.moreLink += "&btob=y";
				output += "<div class='right'><a class='left-arrow-small' href='"+this.moreLink+"'>More</a></div>";
			} else {
				output += "<div class='right'><a class='left-arrow-small' href='"+this.moreLink+"'>More</a></div>";
			}
		}
		if(this.errorMsg != false && j == 0) {
			output = this.errorMsg;
		}

		if (j == 0 && this.outputNode.id == 'mbtd') {
			output = "No more by this Director";
			this.moreLink = false;
		}
		return output;
	}

	function loadScript(url, id){
	    var script = document.getElementById(id);

	    if (script) {
		    script.parentNode.removeChild(script);
	    }

	    script = document.createElement("script");
	    script.type = "text/javascript";
	    script.id = id;
	    script.src = url;
	    document.getElementsByTagName("head")[0].appendChild(script);
    }



