﻿/// <reference path="JsLib.js" />
var Catalog={};

/* Utilities funtions */
Catalog.Utils={
	FormatUrl:function(url){
		return document.location.protocol+"//"+document.location.host+"/"+url;
	},
	QueryString:function(parameter){ 
		  var loc=location.search.substring(1,location.search.length);
		  var param_value=false;
		  var params=loc.split("&");
		  for (i=0;i<params.length;i++){
			  param_name=params[i].substring(0,params[i].indexOf('='));
			  if(param_name==parameter)
				  param_value=params[i].substring(params[i].indexOf('=')+1)
		  }
		  if(param_value)
			  return param_value;
		  else
			  return "";
	},
    ReplaceQueryString:function(url, param, value) {
        var re = new RegExp("([?|&])" + param + "=.*?(&|$)", "i");
        if (url.match(re))
            return url.replace(re, '$1' + param + "=" + value + '$2');
        else
            return url + '&' + param + "=" + value;
    }

};

/* Inventory*/
Catalog.Inventory = {
    skus: new Array(),
    AddControlToArray: function(sku) {
        Catalog.Inventory.skus.push(sku);
    },
    RefreshControls: function(CheckStoreAvailability) {
        if (Catalog.Inventory.skus.length > 0) {
            if ((readCookieName("Recognized") == null && readCookieName("SelectedStores") == null) || CheckStoreAvailability==false) {
                var url = "/Catalog/ButtonControlContent.aspx?PopulateISA=false&AllowSecure=True&lang=" + document.documentElement.lang;
            }
            else {
                var url = "/Catalog/ButtonControlContent.aspx?PopulateISA=true&AllowSecure=True&lang=" + document.documentElement.lang;
            }
            JsLib.UI.InjectHTMLMultiple(url, Catalog.Inventory.skus.join("&"), Catalog.Inventory.skus);
        }
    }
};

/* TABS */
Catalog.Tabs={
	currentTab: '',
	ActivateById: function(objid) {
		url = location.href;
		if (Catalog.Utils.QueryString('ActiveTab') == '') {
			url += '&ActiveTab=' + objid;
		}
		else {
			url = url.replace('ActiveTab=' + Catalog.Utils.QueryString('ActiveTab'), 'ActiveTab=' + objid);
		}

		$redirect(url);
	},
	OnMouseOver: function(obj)
	{
	   $get(obj.id).className += " pdptab-hover";
	},
	OnMouseOut: function(obj)
	{
	   $get(obj.id).className = $get(obj.id).className.replace("pdptab-hover", "");
	},
	Initialize:function(){
		currentTab="";
		var a=Catalog.Tabs.Initialize.arguments; 
		for(i=1; i<a.length; i++){
			($get(a[i])).onmouseover=function(){
					Catalog.Tabs.OnMouseOver(this);return false;
				};
			($get(a[i])).onmouseout=function(){
					Catalog.Tabs.OnMouseOut(this);return false;
				};	
			($get(a[0])).className="pdptab roll";
		}
	}
};

/* TABS */
Catalog.Divs=
{
	ShowHide:function(obj)
	{
		// args[0] is a reference to the +/- image 
		// args[1] is the state (1=expanded, 0=collapsed)
		// args[2] is the client id for the text div (See more See less)
		// args[3] is the resourced "See More" text
		// args[4] is the resourced "See Less" text
		// Remaining arguments are the divs themselves
		var args = Catalog.Divs.ShowHide.arguments; 
		
		if(!args[0].state)
		{
			args[0].state = args[1];
		}
		if(args[0].state == "1")
		{
			/*($get(args[2])).innerHTML = args[3];*/
			for(i=6; i<args.length; i++)
				($get(args[i])).style.display="none";
			args[0].state = "0";
			args[0].src = '/images/common/backgrounds/plus-sign.gif';
		}
		else
		{
			/*($get(args[2])).innerHTML = args[4];*/
			for(i=6; i<args.length; i++)
				($get(args[i])).style.display="block";
			args[0].state = "1";
			args[0].src = '/images/common/backgrounds/minus-sign.gif';
		}
	},
	Initialize:function(obj)
	{
		var args= Catalog.Divs.Initialize.arguments; 
		if($get(args[0])!=null)
		{
			if(args[1]=="0")
			{
				/*($get(args[2])).innerHTML = args[3];*/
				$get(args[0]).state = "0";
				$get(args[0]).src = "/images/common/backgrounds/plus-sign.gif";
				for(i=6; i<args.length; i++)
					($get(args[i])).style.display="none";
			}
			else
			{
				/*($get(args[2])).innerHTML = args[4];*/
				$get(args[0]).state = "1";
				$get(args[0]).src = "/images/common/backgrounds/minus-sign.gif";
				for(i=6; i<args.length; i++)
					($get(args[i])).style.display="block";
			}
		}
	}
};

/* DetailsTab */
Catalog.DetailsTab={
	SelectTabSpecWithPagination:function(productId,tabId,catalogName,pageNumber,itemsPerPage,sortOption){
		if(catalogName==""||catalogName==null)
			url='Catalog/DetailsTabs.aspx?Sku='+encodeURIComponent(productId)+'&ActiveTab='+encodeURIComponent(tabId)+'&Page='+encodeURIComponent(pageNumber-1)+'&PageSize='+encodeURIComponent(itemsPerPage)+'&SortOption='+encodeURIComponent(sortOption );
		else
			url='Catalog/DetailsTabs.aspx?Sku='+encodeURIComponent(productId)+'&ActiveTab='+encodeURIComponent(tabId)+'&pcname='+encodeURIComponent(catalogName)+'&SortOption='+encodeURIComponent(sortOption);
		var pageContent=$httpRequest.loadText(Catalog.Utils.FormatUrl(url));
		pageContent=pageContent.substring(pageContent.indexOf("<div id=\"tableId\""));
		pageContent=pageContent.substring(0,pageContent.indexOf("</form>"));
		$get('div'+ tabId).innerHTML=pageContent;
		$get('div'+ tabId).style.display='block';
	},
	OpenGlossaryTermPopup: function(GlossaryId, GlossaryAlternateSource) {
	var popupUrl = "../ResearchCentre/GlossaryTermDescription.aspx?GlossaryId=" + encodeURIComponent(GlossaryId) + "&GlossaryAlternateSource=" + encodeURIComponent( GlossaryAlternateSource );

	window.open(popupUrl, '', 'location=0,menubar=0,scrollbars=1,status=0,toolbar=0');
	},
	  SelectTabSpecWithPaginationExtended: function(productId, tabId, catalogName, pageNumber, itemsPerPage, sortOption, IncludeParentProducts) {
		if (catalogName == "" || catalogName == null)
			url = 'Catalog/DetailsTabs.aspx?Sku=' + encodeURIComponent(productId) + '&ActiveTab=' + encodeURIComponent(tabId) + '&Page=' + encodeURIComponent(pageNumber - 1) + '&PageSize=' + encodeURIComponent(itemsPerPage) + '&SortOption=' + encodeURIComponent(sortOption) + '&IncludeParents=' + encodeURIComponent(IncludeParentProducts);
		else
			url = 'Catalog/DetailsTabs.aspx?Sku=' + encodeURIComponent(productId) + '&ActiveTab=' + encodeURIComponent(tabId) + '&pcname=' + encodeURIComponent(catalogName) + '&SortOption=' + encodeURIComponent(sortOption) + '&IncludeParents=' + encodeURIComponent(IncludeParentProducts);
		var pageContent = $httpRequest.loadText(Catalog.Utils.FormatUrl(url));
		pageContent = pageContent.substring(pageContent.indexOf("<div id=\"tableId\""));
		pageContent = pageContent.substring(0, pageContent.indexOf("</form>"));
		$get('div' + tabId).innerHTML = pageContent;
		$get('div' + tabId).style.display = 'block';
	},
	GetBundleDetails:function(productId, srcdiv, targetdiv){
		var url='/Catalog/BundleTabDetailsContent.aspx?Sku='+encodeURIComponent(productId);
		JsLib.UI.InjectHTML(url, srcdiv, targetdiv);
	}
};

/* SearchResults*/
Catalog.SearchResults = {
    GetContent: function(url, srcdiv, targetdiv) {
        Catalog.ProductCompare.InitializeFields();
        var selectedproducts = $get(Catalog.ProductCompare.lblSelectedProductIds).value;
        url = Catalog.Utils.ReplaceQueryString(url, "SelectedProductIds", selectedproducts);
        //JsLib.UI.InjectHTML(url, srcdiv, targetdiv);
        $("#"+targetdiv).load(url + " #" + srcdiv, function() {
            $("a[href*=/product/]").each(function() {
                QuickViewInit(this);
            });
        });
        
    },
    GetContentWithPageSize: function(url, srcdiv, targetdiv, dropdown) {
        var dropdownobject = $get(dropdown);
        var itemsperpage = dropdownobject.options[dropdownobject.selectedIndex].value;
        url = Catalog.Utils.ReplaceQueryString(url, "PageSize", itemsperpage);
        Catalog.SearchResults.GetContent(url, srcdiv, targetdiv);
    }

};

/* ProductCompareTab */
Catalog.ProductCompareTab = {
    SelectCompareBrand: function(tabId, productId, brandId, categoryId, catalogName) {
        var sortoption = document.URL.valueOf
        if (catalogName == "" || catalogName == null)
            url = '/Catalog/ProductDetails.aspx?Sku='+encodeURIComponent(productId)+'&ActiveTab='+encodeURIComponent(tabId)+'&CompareBrand='+encodeURIComponent(brandId)+'&CompareCategory='+encodeURIComponent(categoryId)+'&SortOption='+Catalog.Utils.QueryString('SortOption');
        else
            url = '/Catalog/ProductDetails.aspx?Sku='+encodeURIComponent(productId)+'&ActiveTab='+encodeURIComponent(tabId)+'&CompareBrand='+encodeURIComponent(brandId)+'&CompareCategory='+encodeURIComponent(categoryId)+'&pcname='+encodeURIComponent(catalogName)+'&SortOption='+Catalog.Utils.QueryString('SortOption');
        $redirect(url);
    },
    GetContent: function(Sku,
							ItemsPerPageDropDownID,
							CurrentItemIndex,
							CurrentPage,
							CurrentSortOption,
							CurrentCategory,
							IncludeParentProducts,
							srcdiv,
							targetdiv,
							senderid,
							sendertype,
							ParentClass,
							SubClass,
							CurrentItemsPerPage) {
        Catalog.ProductCompare.InitializeFields();
        if (sendertype == "sortoption")
            CurrentSortOption = ($get(senderid).value);
        var selectedproducts = $get(Catalog.ProductCompare.lblSelectedProductIds).value;
        var ItemsPerPage = 15;
        if (CurrentItemsPerPage)
            ItemsPerPage = CurrentItemsPerPage;
        var ItemsPerPageDropDown = $get(ItemsPerPageDropDownID);
        if (ItemsPerPageDropDown != null)
            ItemsPerPage = ItemsPerPageDropDown.options[ItemsPerPageDropDown.selectedIndex].value;
        var url =
			"/Catalog/ProductTabCompareContent.aspx?Sku=" + encodeURIComponent( Sku )
				+ "&ItemsPerPage=" + encodeURIComponent( ItemsPerPage )
				+ "&CurrentItemIndex=" + encodeURIComponent( CurrentItemIndex )
				+ "&CurrentPage=" + encodeURIComponent( CurrentPage )
				+ "&Sort=" + encodeURIComponent( CurrentSortOption )
				+ "&CurrentCategory=" + encodeURIComponent( CurrentCategory )
				+ "&IncludeParents=" + encodeURIComponent( IncludeParentProducts )
				+ "&SelectedProductIds=" + encodeURIComponent( selectedproducts )
				+ "&parentclass=" + encodeURIComponent( ParentClass )
				+ "&subclass=" + encodeURIComponent( SubClass )
        JsLib.UI.InjectHTML(url, srcdiv, targetdiv);
    }
};



/*QuickView*/
Catalog.QuickView = {
	GenerateHideQuickView: function(productSku, bbyQuickViewClientID) {
		var jsScript = "<script type='text/javascript' language='javascript'>\r\nfunction HideQuickView" + productSku.replace(' ', '_') + "()\r\n{\r\n	$get('" + bbyQuickViewClientID + "').PopupControlBehavior.hidePopup();\r\n}</script>";
		document.writeln(jsScript);
	}
};

/*Product Image*/
Catalog.ProductImages={
	ImageUrlIndex:0,
	RotateImage:function(imagesPaths,direction,imgProductClientID,lblImageRotatorClientID){
		var ImageUrlArray=imagesPaths.split(",");
		var TotalImages=ImageUrlArray.length;
		var UrlLocation="";
		if(Catalog.ProductImages.ImageUrlIndex<0||Catalog.ProductImages.ImageUrlIndex>=TotalImages)
			Catalog.ProductImages.ImageUrlIndex=0;
		if(direction.match("right")) {
			if(Catalog.ProductImages.ImageUrlIndex<TotalImages-1) {
				++Catalog.ProductImages.ImageUrlIndex;
				UrlLocation=ImageUrlArray[Catalog.ProductImages.ImageUrlIndex].toString();
				$get(imgProductClientID).src=UrlLocation;
				$get(lblImageRotatorClientID).innerText=" Image "+(Catalog.ProductImages.ImageUrlIndex+1)+" of "+TotalImages;
			}
		}
		if(direction.match("left")) {
			if(Catalog.ProductImages.ImageUrlIndex>0) {
				--Catalog.ProductImages.ImageUrlIndex;
				UrlLocation=ImageUrlArray[Catalog.ProductImages.ImageUrlIndex].toString();
				$get(imgProductClientID).src=UrlLocation;
				$get(lblImageRotatorClientID).innerText=" Image "+(Catalog.ProductImages.ImageUrlIndex+1)+" of "+TotalImages;
			}
		}
	}
};

/* MiniQuickView */
Catalog.MiniQuickView={
	ShowMiniQuickView:function(miniQuickViewId,url){
		var miniQuickView=$get(miniQuickViewId);
		if(!miniQuickView)
			return;
		if(miniQuickView.innerHTML==""){
			var response=$httpRequest.loadText(url);
			response=response.substring(response.indexOf("<script"));
			miniQuickView.innerHTML=response; 
		}
		miniQuickView.style.display='block';
	},
	HideMiniQuickView:function(miniQuickViewId){
		var miniQuickView=$get(miniQuickViewId);
		miniQuickView.style.display='none';
	}
};

/*ProductCompare*/
Catalog.ProductCompare = {
    lblSelectedProductIds: '',
    lblSelectedProductCount: '',
    hidNotEnoughProductsErrorMessage: '',
    hidTooManyProducts: '',
    hidMaxProductsToCompare: '',
    boolInitialized: false,

    InitializeFields: function() {
        if (!Catalog.ProductCompare.boolInitialized) {

            Catalog.ProductCompare.lblSelectedProductIds = $get("hidSelectedProductIds_ID").value.replace('$', '_');
            Catalog.ProductCompare.lblSelectedProductCount = $get("hidSelectedProductCount_ID").value.replace('$', '_');
            Catalog.ProductCompare.hidNotEnoughProductsErrorMessage = $get("hidNotEnoughProductsMessage_ID").value.replace('$', '_');
            Catalog.ProductCompare.hidTooManyProducts = $get("hidTooManyProductsMessage_ID").value.replace('$', '_');
            Catalog.ProductCompare.hidMaxProductsToCompare = $get("hidMaxComparableProducts_ID").value.replace('$', '_');
            Catalog.ProductCompare.boolInitialized = true;
        }
    },
    doCompare: function(returnUrl) {
        Catalog.ProductCompare.InitializeFields();
        var rootdomain = "http://" + window.location.host;
        var checkedList = $get(Catalog.ProductCompare.lblSelectedProductIds).value;
        var selectedProductCount = parseFloat($get(Catalog.ProductCompare.lblSelectedProductCount).value);
        var maxProducts = parseFloat($get(Catalog.ProductCompare.hidMaxProductsToCompare).value);
        if (selectedProductCount > maxProducts) {
            var tooManyProducts = $get(Catalog.ProductCompare.hidTooManyProducts).value;
            tooManyProducts = tooManyProducts.replace("{0}", maxProducts);
            alert(tooManyProducts);
        } else {
            if (selectedProductCount <= 1) {
                var notEnoughProductsMessage = $get(Catalog.ProductCompare.hidNotEnoughProductsErrorMessage).value;
                alert(notEnoughProductsMessage);
            } else {
                var uri;
                checkedList = checkedList.replace("#,", "");
                uri = rootdomain + "/catalog/compare-result.aspx?ProductIds=" + encodeURIComponent(checkedList) + "&returnPath=" + encodeURIComponent('' + returnUrl);
                $redirect(uri);
            }
        }
    },
    initHiddenFields: function(maxComparableProducts, notEnoughProductsText, tooManyProductsSelectedText) {
        //		$get(Catalog.ProductCompare.hidMaxProductsToCompare).value = maxComparableProducts;
        //		$get(Catalog.ProductCompare.hidNotEnoughProductsErrorMessage).value = notEnoughProductsText;
        //		$get(Catalog.ProductCompare.hidTooManyProducts).value = tooManyProductsSelectedText;
    },
    initSelectedProductHiddenFields: function(inlblSelectedProductIds, inlblSelectedProductCount) {
        Catalog.ProductCompare.InitializeFields();
        $get(Catalog.ProductCompare.lblSelectedProductIds.replace('$', '_')).value = inlblSelectedProductIds;
        $get(Catalog.ProductCompare.lblSelectedProductCount).value = inlblSelectedProductCount;
    },
    checkBoxClicked: function(thisCheckBox, thisSku) {
        Catalog.ProductCompare.InitializeFields();
        var checked;
        var checkedList = $get(Catalog.ProductCompare.lblSelectedProductIds.replace('$', '_')).value;
        var selectedProductCount = parseFloat($get(Catalog.ProductCompare.lblSelectedProductCount).value);
        if (thisCheckBox.checked) {
            checkedList = checkedList + ',' + thisSku;
            selectedProductCount = selectedProductCount + 1;
            var maxProducts = parseFloat($get(Catalog.ProductCompare.hidMaxProductsToCompare).value);
            if (selectedProductCount > maxProducts) {
                var maxProducts = parseFloat($get(Catalog.ProductCompare.hidMaxProductsToCompare).value);
                var tooManyProducts = $get(Catalog.ProductCompare.hidTooManyProducts).value;
                tooManyProducts = tooManyProducts.replace("{0}", maxProducts);
                alert(tooManyProducts);
                thisCheckBox.checked = false;
            } else {
                $get(Catalog.ProductCompare.lblSelectedProductIds).value = checkedList;
                $get(Catalog.ProductCompare.lblSelectedProductCount).value = selectedProductCount;
            }
        } else {
            checkedList = checkedList.replace(',' + thisSku, '');
            checkedList = checkedList.replace(thisSku + ',', '');
            checkedList = checkedList.replace(thisSku, '');                
            if (selectedProductCount > 0)
                selectedProductCount = selectedProductCount - 1;
            $get(Catalog.ProductCompare.lblSelectedProductIds).value = checkedList;
            $get(Catalog.ProductCompare.lblSelectedProductCount).value = selectedProductCount;
        }
    },
    Initialize: function(lblSelectedProductIds, lblSelectedProductCount, compareIdMapping) {
        Catalog.ProductCompare.InitializeFields();
        var checkedList = $get(Catalog.ProductCompare.lblSelectedProductIds).value;
        var selectedProductCount = parseFloat($get(Catalog.ProductCompare.lblSelectedProductCount).value);

        if (compareIdMapping != null && selectedProductCount > 0) {
            var productIds = checkedList.split(",");

            for (var i = 0; i < compareIdMapping.length; i += 2) {
                for (var j = 0; j < productIds.length; j++) {
                    if (productIds[j] == compareIdMapping[i]) {
                        var elem = $get(compareIdMapping[i + 1]);

                        if (elem != null)
                            elem.checked = true;
                    }
                }
            }
        }
    }
};

/* ProductDetailsControl.js */
/*
function SelectTab(tabId, productId, catalogName)
{ 
	//need to find out if catalogName is null or empty
	if (catalogName == "" || catalogName == null)
	{   
		$get('hiframe2').setAttribute('src',FormatUrl('Catalog/DetailsTabs.aspx?Sku='+encodeURIComponent( productId )+'&TabName='+encodeURIComponent( tabId ) ));
	}
	else
	{		 
		$get('hiframe2').setAttribute('src',FormatUrl('Catalog/DetailsTabs.aspx?Sku='+encodeURIComponent( productId )+'&TabName='+encodeURIComponent( tabId ) + '&pcname=' + encodeURIComponent( catalogName) ));
	}
}

function SelectTabSpec(productId, tabId, selectedId, catalogName)
{
	if (catalogName == "" || catalogName == null)
	{   
		$get('hiframe2').setAttribute('src',FormatUrl('Catalog/DetailsTabs.aspx?Sku='+encodeURIComponent( productId)+'&TabName='+encodeURIComponent( tabId )+'&SelectedProduct='+encodeURIComponent( selectedId ) ));
	}
	else
	{		 
		$get('hiframe2').setAttribute('src',FormatUrl('Catalog/DetailsTabs.aspx?Sku='+encodeURIComponent( productId )+'&TabName='+encodeURIComponent( tabId )+'&SelectedProduct='+encodeURIComponent( selectedId) + '&pcname=' + encodeURIComponent( catalogName) ));
	}
}

function FormatUrl(url)
{
	return document.location.protocol + "//" + document.location.host + "/" + url;
}

function SelectTabFSAdditionalProductGroup(productId, tabId, selectedGroupId, selectCommand, catalogName)
{
 if (catalogName == "" || catalogName == null)
	{   
		$get('hiframe2').setAttribute('src',FormatUrl('Catalog/DetailsTabs.aspx?Sku='+encodeURIComponent( productId)+'&TabName='+encodeURIComponent( tabId)+'&APG='+encodeURIComponent( selectedGroupId)+'&SelCommand='+encodeURIComponent( selectCommand ) ));
	}
	else
	{		 
		$get('hiframe2').setAttribute('src',FormatUrl('Catalog/DetailsTabs.aspx?Sku='+encodeURIComponent( productId)+'&TabName='+encodeURIComponent( tabId)+'&APG='+selectedGroupId+'&SelCommand='+encodeURIComponent( selectCommand)+ '&pcname=' + encodeURIComponent( catalogName) ));
	}
}
*/

/* WarrantyPicker */
function TermsPopup(nameOfControl, wpUrl, productId)
{ 
	var radioButtons = document.getElementsByName(nameOfControl);

	//Find Selected Option
	for (var indx=0; indx <= radioButtons.length; indx++)
	{  
		if (radioButtons[indx].checked)
		{
			//Open Warranty window		
			var warrantyId = radioButtons[indx].getAttribute("warrantyId");
			if (warrantyId != null && warrantyId != "0")
			{
				$popUp(wpUrl + "&WarrantyId="+encodeURIComponent(warrantyId)+"&Sku="+encodeURIComponent(productId),'',{scrollbars:true,status:false,width:600,height:400});
				break;
			}		 
		}	 
	}
}


/* WarrantyUtil */
/*
function TermsPopup(targetControlId, wpUrl, ProductId)
{ 
	var rowCount = $get(targetControlId).rows.length;

	//Find Selected Option
	for(var Index=0; Index < rowCount; Index++)
	{
		var checkOptionId = targetControlId.concat("_"+Index);
		if ($get(checkOptionId).checked)
		{
			//Open Warranty window
			var WarrantyId=$get(checkOptionId).value; 
			if (WarrantyId != "0")   
			{
				$popUp(wpUrl + "&WarrantyId="+encodeURIComponent(WarrantyId)+"&ProductId="+encodeURIComponent(ProductId),"",{scrollbars:true,status:false});
			}
			break
		}
	}
}*/


function UpdateTermsFrame(RbnControl, productId)
{
	var termsFrame = $get("TermsFrame");

	if (RbnControl != null) {
		var warrantyId = RbnControl.getAttribute("warrantyId");
		//set IFRAME to PSP terms
		if (warrantyId != null && warrantyId != "0")
			termsFrame.src = ("/Catalog/PspTerms.aspx?WarrantyId=" + encodeURIComponent( warrantyId ) + "&Sku=" + encodeURIComponent( productId ) );
		else
			termsFrame.src = "";
	}
	else
		termsFrame.src = "";
}

function WarrantyIsSelected(boxChecked)
{
if (boxChecked)
{
document.WarrantyChecked = true;
}
else
{
document.WarrantyChecked = false;
}
}

function AcceptTermAndConditions(chkBoxTerm)
{
	basket.set_PSPTermAccepted(chkBoxTerm.checked);
}

function AcceptTermAndConditionsFS(chkBoxTerm, btnContinueId, noneOptionsIds)
{		
	btnContinue = $get(btnContinueId);

	if (chkBoxTerm.checked) {
		AcceptTermAndConditionsFSEnable(btnContinue);
	}
	else {
		if((this.window.opener!=undefined) && ( this.window.opener.basket !=undefined ) )
		{
			if (this.window.opener.basket.PSP != "0")
				AcceptTermAndConditionsFSDisable(btnContinue);
		}
		else
		{
			if (this.window.basket.PSP != "0")
				AcceptTermAndConditionsFSDisable(btnContinue);
		}
	}

	if((this.window.opener!=undefined) && ( this.window.opener.basket !=undefined ) )
	{
		this.window.opener.basket.set_PSPTermAccepted(chkBoxTerm.checked);
	}
	else if(this.window.basket!=undefined)
	{
		this.window.basket.set_PSPTermAccepted(chkBoxTerm.checked);
	}
	
}

function AcceptTermAndConditionsFSEnable(elem) {
	elem.parentNode.disabled = false;
	elem.disabled = false;
	elem.src = elem.src.replace(/continue_off.gif/, "continue.gif");	
}

function AcceptTermAndConditionsFSDisable(elem) {
	elem.parentNode.disabled = true;
	elem.disabled = true;
	elem.src = elem.src.replace(/continue.gif/, "continue_off.gif");
}

function PspConstituentSelected(itemCheckedControl, controlId, index)
{
	acceptCheckbox = $get(controlId+"_ChkAcceptTerms");
	parentSpan = acceptCheckbox.parentNode;	

	if (acceptCheckbox && parentSpan)
	{
		acceptCheckbox.parentNode.disabled = false;
		acceptCheckbox.disabled = false;
		acceptCheckbox.checked = false;
		parentSpan.style.visibility = "visible";

		var warrantyId = itemCheckedControl.getAttribute("warrantyId");
		
		if (this.window.opener && this.window.opener.basket) {
			this.window.opener.basket.set_PSPTermAccepted(false);
			this.window.opener.basket.addAtBundlePSP(index, warrantyId);
		}
		else 
		if(this.window.basket)
		{
			this.window.basket.set_PSPTermAccepted(false);
			this.window.basket.addAtBundlePSP(index, warrantyId);   
		}
	}   
}

function EnableTermAcceptStartupScript(itemCheckedControl, controlId, warrantyId)
{
	acceptCheckbox = $get(controlId+"_ChkAcceptTerms");
	parentSpan = acceptCheckbox.parentNode;
	termsLink = $get(controlId+"_HypTerms");

	if (acceptCheckbox && parentSpan)
	{
		acceptCheckbox.parentNode.disabled = false;
		acceptCheckbox.disabled = false;
		parentSpan.style.visibility = "visible";
		termsLink.style.visibility = "visible";
		basket.set_PSP(warrantyId);
	}
}

function EnableTermAccept(itemCheckedControl, controlId)
{
	acceptCheckbox = $get(controlId+"_ChkAcceptTerms");
	parentSpan = acceptCheckbox.parentNode;
	termsLink = $get(controlId+"_HypTerms");

	if (acceptCheckbox && parentSpan && termsLink)
	{
		acceptCheckbox.parentNode.disabled = false;
		acceptCheckbox.disabled = false;
		parentSpan.style.visibility = "visible";
		termsLink.style.visibility = "visible";
		var warrantyId = itemCheckedControl.getAttribute("warrantyId");
		basket.set_PSP(warrantyId);
	}
}

function FSOptionSelected(itemCheckedControl, controlId)
{
	var warrantyId = itemCheckedControl.getAttribute("warrantyId");
	var acceptCheckbox = $get(controlId+"_ChkAcceptTerms");

	acceptCheckbox.checked = false;
	AcceptTermAndConditionsFSDisable(btnFSContinue);
	
	if (warrantyId != "0") {
		this.window.opener.basket.set_PSPTermAccepted(false);
		this.window.opener.basket.set_PSP(warrantyId);
	}
}


function DisableTermAccept(itemChecked, controlId)
{


acceptCheckbox = $get(controlId+"_ChkAcceptTerms");
parentSpan = acceptCheckbox.parentNode;
termsLink = $get(controlId+"_HypTerms");

if (acceptCheckbox && parentSpan && termsLink)
{
acceptCheckbox.checked = false;
parentSpan.style.visibility = "hidden";
termsLink.style.visibility = "hidden";

basket.set_PSP("");
basket.set_PSPTermAccepted(false);

}

}

function FSNonOptionSelected(itemChecked, controlId)
{
	this.window.opener.basket.set_PSP("0");
	UpdateTermsFrame(null, null);

	if (btnFSContinue != null)
		AcceptTermAndConditionsFSEnable(btnFSContinue);
}

function FSNonOptionConstituentSelected(constituentOption, controlId, index) {

	acceptCheckbox = $get(controlId + "_ChkAcceptTerms");
	parentSpan = acceptCheckbox.parentNode;	

	if (acceptCheckbox && parentSpan) {
		acceptCheckbox.parentNode.disabled = false;
		acceptCheckbox.disabled = false;
		acceptCheckbox.checked = false;
		parentSpan.style.visibility = "visible";

		var warrantyId = "";
		this.window.opener.basket.set_PSPTermAccepted(false);
		this.window.opener.basket.addAtBundlePSP(index, warrantyId);

		var allNoneOptionsChecked = true;

		var mySplitResult = this.window.opener.basket.PSP.split(",");

		for (i = 0; i < mySplitResult.length; i++) 
		{
			if (!(mySplitResult[i] == ""  || mySplitResult[i] == "0")) 
			{
				allNoneOptionsChecked = false;
				break;
			}
		}
		if (allNoneOptionsChecked) {
			acceptCheckbox.checked = true;
			
			this.window.opener.basket.set_PSPTermAccepted(true);
		}
	}   

}

function LoadHelpTopic(availabilityHelpTopicUrl)
{
    $popUp(availabilityHelpTopicUrl, '', { scrollbars: true, status: false, resizable: true });
}

function PrePopulateBundlePSPs(numberOfPSP)
{
	if((this.window.opener!=undefined) && ( this.window.opener.basket !=undefined ) )
		this.window.opener.basket.BundlePSP = new Array(numberOfPSP);
	else if(this.window.basket!=undefined)
	{
		this.window.basket.BundlePSP = new Array(numberOfPSP);
	}
}

function WarrantyIsSelected(boxChecked)
{
	if (boxChecked)
	{
	document.WarrantyChecked = true;
	}
	else
	{
	document.WarrantyChecked = false;
	}
}

function AcceptTermAndConditions(chkBoxTerm) {
    basket.set_PSPTermAccepted(chkBoxTerm.checked);
}

function callBasket(alertMsg, warrantyMsg) {  
	var termStatus;
	if ((this.window.opener != undefined) && (this.window.opener.basket != null) && (this.window.opener.basket != undefined))
	{
		this.window.opener.DisplayTermsNotAcceptedMessage = this.DisplayTermsNotAcceptedMessage;
		this.window.opener.basket.AddSelectedAccessoriesAndWarranty(true, alertMsg, warrantyMsg, "",this.window.opener);
		termStatus = this.window.opener.basket.PSPTermAccepted
	}
	else if(this.window.basket!=undefined)
	{		
		this.window.basket.AddSelectedAccessoriesAndWarranty(true, alertMsg, warrantyMsg,"", this.window.opener);
		termStatus = this.window.basket.PSPTermAccepted
	}
	if ( termStatus )		 
		this.window.close();
	return false;
}
  
function DisplayTermsNotAcceptedMessage(warrantyMsg)
{
	LblErrorMessage = $get("ucFsPspTermSelector_LblErrorMessage");
	ChkAcceptTerms = $get("ucFsPspTermSelector_ChkAcceptTerms");
	LblErrorMessage.style.visibility = "visible";
	LblErrorMessage.innerHTML =  "<SPAN>"+warrantyMsg+"</SPAN>";
}

  function ToggleOnOff(imgControl, targetObj)
	{

		targetControl = $get(targetObj);
		if( targetControl != null && imgControl != null)
		{
			if (targetControl.style.display == "block")
			{
				imgControl.src = "/images/common/buttons/plus.gif";
				targetControl.style.display = "none";
				targetControl.Visible = "false";
			}
			else
			{
			   imgControl.src = "/images/common/buttons/minus.gif";
			   targetControl.style.display = "block";	
			   targetControl.Visible = "true";
			}
		}
	}
	
function PopupWarranty(productUrl) {
	if (document.WarrantyChecked) {
		$popUp(productUrl, "", {scrollbars:true,status:false});
	}
	return false;
}

function PopupWarrantyFS(productUrl) {
	$popUp(productUrl, "", {scrollbars:true,status:false,width:615,height:590});
}

function PopupTermsAndConditions() {
  var termsFrame = $get("TermsFrame");	  
  if((termsFrame)&&(termsFrame.src.trim()!=""))
  {
	path=termsFrame.src+"&Print=T";
	$popUp(path, "", {scrollbars:true,status:false,width:550,height:500});
  }
}

function SetUniqueRadioButton(nameregex, current)
{
   re = new RegExp(nameregex);
   var pId;
   var fldSelected;
	
   for(i = 0; i < document.forms[0].elements.length; i++)
   {
	  elm = document.forms[0].elements[i]
	  if (elm.type == 'radio')
	  {
		 if (re.test(elm.name))
		 {
			elm.checked = false;
		 }
		 if (elm.name == current.name)
		 {//found selcted radio button and now must save the product id
			var span = current.parentNode.outerHTML;
			span = span.replace('<SPAN ProductId=', '');
			var end = span.indexOf('><INPUT'); 
			pId = span.substring(0, end);
		 }
	  }
	  if (elm.type == 'hidden')
	  {
		if (elm.name.indexOf('HdfSelectedProduct') > 0)
		{
			elm.value = pId;
			fldSelected = elm;
		}
	  }
   }
   
   current.checked = true;
   SetSelectedProductSku(fldSelected, pId);
}

function SetSelectedProductSku(fldSelected, productSku)
{
	fldSelected.value = productSku;
}

function GotoTop() 
{
	document.location.hash = "Top"; 
}

function ShowFSToolTip(event, controlId) {
	TargetToolTip = $get(controlId);
	TargetToolTip.style.visibility = "visible";	
	if (event.layerX) {
		TargetToolTip.style.left = event.layerX + 'px';
		TargetToolTip.style.top = event.layerY + 'px';
	}
	else {//IE6
		TargetToolTip.style.left = event.offsetX + 'px';
		TargetToolTip.style.top = event.offsetY + 'px';
	}
	TargetToolTip.style.zIndex = 999;
}

function HideFSToolTip(event, controlId) {
	function delayFSTooltip() {
		TargetToolTip = $get(controlId);
		TargetToolTip.style.visibility = "hidden";	   
		TargetToolTip.style.zIndex = -1;
	}
	setTimeout(delayFSTooltip, 1500);
}

function Cancel() {
	this.window.close();
}

function PopupArtistsWorks(artistUrl) {
    $popUp(artistUrl, "", { scrollbars: true, status: false, width: 800, height: 420, resizable: true });
}

/* Tab stuff */
	function PreloadImages(){
		var browser = navigator.appName;
		var bVersion = navigator.appVersion;
		var version = parseFloat(bVersion);
		if ((browser == "Microsoft Internet Explorer") && (version < 7)){
			var d=document;
			d.execCommand("BackgroundImageCache", false, true);
			if(d.images){
				if(!d.MM_p)
					d.MM_p=new Array();
				var i;
				var j=d.MM_p.length;
				var a=PreloadImages.arguments;
				for(i=0;i<a.length;i++){
					if(a[i].indexOf("#")!=0){
						d.MM_p[j]=new Image;
						d.MM_p[j++].src=a[i];
					}
				}
			}
		}
	}
	function IsIeSix(){
		var browser = navigator.appName;
		var bVersion = navigator.appVersion;
		var version = parseFloat(bVersion);		
		if ((browser == "Microsoft Internet Explorer") && (version < 7))
			return true;
		else	
			return false;   
	}
	
	function tab_hoverIn(x){
	    var c = document.getElementById(x);
		if (IsIeSix()){
		    if (c.className != "selected") {
		        if (c.className == "lastclass") {
		            c.className = "show-lastclass";
		        }
		        else {
		            c.className = "show";
		        }
		    }
		}
	}
	
	function tab_hoverOut(x){
		var c = document.getElementById(x);
		
	    if (c.className != "selected") {
			if ( c.className != "show-lastclass") {
			    if (IsIeSix()) 
			        c.removeAttribute("className", "show");
			    
	        } else {
	            if (IsIeSix())
			        c.className = "lastclass";
			}				
		} 
		
	}
	/* FS warranty */

	function PopulateCheckBoxList() {
	    var inputElements = document.getElementsByTagName("INPUT");
	    var chkRegEx = new RegExp("^.*ucWarrantyPicker.*ChkAcceptTerms$");
	    var checkBoxes = new Array();

	    for (var eIndex = 0; eIndex < inputElements.length; eIndex++) {
	        var someElement = inputElements[eIndex];
	        if (chkRegEx.test(someElement.id)) {	           
	            checkBoxes.push(someElement);
	        }
	    }	    
	    return checkBoxes;
	}

	function ChangeButtonState(eventElement) {
	    var checkBoxes = document.checkBoxes;
	    //localize
	    var locale = "en";
	    var button = $get("ctl00_CC_BtnAddSelectedToCart");
	    var btnImage = button.firstChild;
	    
	    for (indx in checkBoxes) {
	        var chkBox = checkBoxes[indx];
	        	        
	        if ((!chkBox.disabled) && (!chkBox.checked)) {	                      	            
	            var disableImgSrc = "/images/" + locale + "/buttons/buy_selected_item_off.gif";
	            btnImage.src = disableImgSrc;
	            btnImage.onmouseout = null;
	            btnImage.onmouseover = null;
	            break;
	        }
	        else {	                     
	            var btnImage = button.firstChild;
	            var activeImgSrc = "/images/"+locale+"/buttons/buy_selected_item.gif";
	            var hoverImgSrc = "/images/"+locale+"/buttons/buy_selected_item_on.gif";

	            btnImage.src = activeImgSrc;
	            btnImage.onmouseout = new Function ("event", "this.src='" + activeImgSrc + "';");
	            btnImage.onmouseover = new Function ("event", "this.src='" + hoverImgSrc + "';");
	        }
	    }
	}

	function LinkButtonEvents() {	    	    
	    document.checkBoxes = PopulateCheckBoxList();
	    for (var chx = 0; chx < document.checkBoxes.length;  chx++) {
	        var chkBox = document.checkBoxes[chx];
	        $addHandler(chkBox, "click", ChangeButtonState);	       
	    }
	}


	function PopupGlossary(url) {
	    window.open(url, 'glossary', 'location=0,menubar=0,scrollbars=1,status=0,toolbar=0,width=585,height=480');
	}
	
	/*
        is used to toggle the search boxes on the music, movies and games dept pages.
        By default the box is hidden but is forced to open.

    */
	$(document).ready(function() {
	    var musicImg = $get('ctl00_CC_ctl00_MusicSearch1_BtnCollapse');
	    var movieImg = $get('ctl00_CC_ctl00_MovieSearch1_BtnCollapse');
	    if (movieImg)
	    {
	        ToggleOnOff(movieImg, 'adv-search-expand');
	    }
	    else if(musicImg)
	    {
	        ToggleOnOff(musicImg, 'adv-search-expand');
	    }
	});
