/**
 * General.js 
 * Javascript 
 *
 */

function getElement(id) {
	var obj;
	if (document.getElementById) {
		obj = document.getElementById(id);
	}
	else if (document.layers) {
		obj = document.layers.id;
	}
	else if (document.all) {
		obj = document.all.id;
	}

	return obj;
}
function manipulateObjectClass(obj, mode, class1, class2) {
	if (obj != null) {
		switch (mode) {
		case 'check':
			return new RegExp('\\b'+class1+'\\b').test(obj.className)
			break;
		case 'add':
			if(!manipulateObjectClass(obj,'check',class1)){
				obj.className+=obj.className?' '+class1:class1;
			}
			break;
		case 'remove':
			var rep=obj.className.match(' '+class1)?' '+class1:class1;
			obj.className=obj.className.replace(rep,'');
			break;
		case 'swap':
			obj.className=!manipulateObjectClass(obj,'check',class1)?obj.className.replace(class2,class1): obj.className.replace(class1,class2);
			break;
		}
	}
}

function getFormFields(parent, type) {
	var Elements = parent.getElementsByTagName(type);
	return Elements;
}

function showHideByID(id) {
	var obj = getElement(id);
	if (obj != null) {
		if(manipulateObjectClass(obj,'check','hiddenContent')) {
			manipulateObjectClass(obj,'remove','hiddenContent');
		} 
		else {
			manipulateObjectClass(obj,'add','hiddenContent');
		}
	}
}

/*----------*/

function simpleHide(id){
	if(document.getElementById(id)){
		document.getElementById(id).style.display='none';
	}
}

function simpleShow(id){
	if(document.getElementById(id)){
		document.getElementById(id).style.display='block';
	}
}

function hide(id)
{
    var obj;  
    if (document.getElementById)
	{	    
	    obj = document.getElementById(id);		    
	    if (obj != null)    	    
		{
		    obj.style.visibility = 'hidden';
		    obj.style.display ='none';
		}
	}	  
       
    else  if (document.layers)
	{	    
	    obj = document.layers.id;
	    if (obj != null)    	    
		{	    	   
		    obj.visibility = 'hide';
		    obj.display = 'none';
		}
	}
	else if (document.all)
	{	    
	    obj = document.all.id;	 
	    if (obj != null)    	    
		{   
		    obj.style.visibility = 'hidden';
		    obj.style.display = 'none';
		}
	}
}
 
function show(id)
{
    var obj;  
    if (document.getElementById)
	{	    
	    obj = document.getElementById(id);	 
	    if (obj != null)    	    
		{   	    
		    obj.style.visibility = 'visible';
		    obj.style.display ='block';
	    }
	}	  
       
    else  if (document.layers)
	{	    
	    obj = document.layers.id;	
	    if (obj != null)    	    
		{  	       
		    obj.visibility = 'show';
		    obj.display = 'block';
		}
	}
	else if (document.all)
	{	    
	    obj = document.all.id;
	    if (obj != null)    	    
		{      
		    obj.style.visibility = 'visible';
		    obj.style.display = 'block';
		}
	}

}

function showtbl(id)
{    
    var obj;  
    if (document.getElementById)
	{	    
	    obj = document.getElementById(id);	 
	    if (obj != null)    	    
		{   	    
		    obj.style.visibility = 'visible';
		    if (browser == 'Internet Explorer'){obj.style.display ='block';}
		    else {obj.style.display ='table';}
	    }
	}	  
       
    else  if (document.layers)
	{	    
	    obj = document.layers.id;	
	    if (obj != null)    	    
		{  	       
		    obj.visibility = 'show';
            if (browser == 'Internet Explorer'){obj.style.display ='block';}
		    else {obj.style.display ='table';}
		}
	}
	else if (document.all)
	{	    
	    obj = document.all.id;
	    if (obj != null)    	    
		{      
		    obj.style.visibility = 'visible';
            if (browser == 'Internet Explorer'){obj.style.display ='block';}
		    else {obj.style.display ='table';}
		}
	}

}

function enableTable(id, enable, imagePath)
{
    var obj = getElement(id);      
	
	var attribute;
	if ( browser == 'Internet Explorer')
	    attribute = 'className';
	else
	    attribute = 'class';
	    
    
	var FormElements = getFormFields(obj,'input');
	
	for (var i=0;i<FormElements.length;i++)
	{	   	    
	    if (enable)
	    {
	        FormElements[i].disabled = '';
	    }
	    else
        {
            FormElements[i].disabled = 'disabled';
        }
	}	
	

    attribute = 'src';

	FormElements = getFormFields(obj,'img');
	for (var i=0;i<FormElements.length;i++)
	{	   	    	    
	    if (enable)
	    {	   	        
	        FormElements[i].setAttribute(attribute, imagePath + '/mesip/icons/fieldrequired.gif');
	    }
	    else
        {           
            FormElements[i].setAttribute(attribute, imagePath + '/mesip/icons/fieldrequired_disabled.gif');
        }
	}			
}

var active_con, active_option;
function showoptionbox(conid, boxid)
{   
    if (active_con != conid){hide(active_con);}
    
    if (active_option != boxid){hide(active_option);}
         
    if (browser != "Internet Explorer"){hideshow(conid);active_con=conid;}
    
    hideshow(boxid);
    active_option = boxid;
}

function hideinfoboxes()
{
    hide(active_con);
    hide(active_option);    
}

function toggletablerow(id)
{
    if (id!=active_option)
        hideinfoboxes();
    
    active_option = id;
    
    var obj;  
    if (document.getElementById)
	{	    
	    obj = document.getElementById(id);	 
	    if (obj != null)    	    
		{   	    
		    if (obj.style.visibility == 'hidden' || obj.style.visibility =='' )
		    {
		        obj.style.visibility = 'visible';
		        if (browser == 'Internet Explorer'){obj.style.display ='block';}
		        else {obj.style.display ='table-row';}
		    }
		    else
		    {
		        obj.style.visibility = 'hidden';
		        obj.style.display ='none';
		    }
	    }
	}	  
       
    else  if (document.layers)
	{	    
	    obj = document.layers.id;	
	    if (obj != null)    	    
		{  	       
		    if (obj.style.visibility == 'hide'  || obj.style.visibility =='' )
		    {				    
		        obj.visibility = 'show';
		        if (browser == 'Internet Explorer'){obj.style.display ='block';}
		        else {obj.style.display ='table-row';}
		    }
		    else
		    {
		        obj.visibility = 'hide';
		        obj.display = 'none';
		    }
		}
	}
	else if (document.all)
	{	    
	    obj = document.all.id;
	    if (obj != null)    	    
		{      
		    if (obj.style.visibility == 'hidden' || obj.style.visibility =='' )
		    {	
		        obj.style.visibility = 'visible';
		        if (browser == 'Internet Explorer'){obj.style.display ='block';}
		        else {obj.style.display ='table-row';}
		    }
		    else
		    {
		        obj.style.visibility = 'hidden';
		        obj.style.display = 'none';		    
		    }
		}
	}    
}

function hideshow(id)
{
    var obj;  
    if (document.getElementById)
	{	    
	    obj = document.getElementById(id);	 
	    if (obj != null)    	    
		{   	    
		    if (obj.style.visibility == 'hidden' || obj.style.visibility =='' )
		    {
		        obj.style.visibility = 'visible';
		        obj.style.display ='block';
		    }
		    else
		    {
		        obj.style.visibility = 'hidden';
		        obj.style.display ='none';
		    }
	    }
	}	  
       
    else  if (document.layers)
	{	    
	    obj = document.layers.id;	
	    if (obj != null)    	    
		{  	       
		    if (obj.style.visibility == 'hide'  || obj.style.visibility =='' )
		    {				    
		        obj.visibility = 'show';
		        obj.style.display ='block';
		    }
		    else
		    {
		        obj.visibility = 'hide';
		        obj.display = 'none';
		    }
		}
	}
	else if (document.all)
	{	    
	    obj = document.all.id;
	    if (obj != null)    	    
		{      
		    if (obj.style.visibility == 'hidden' || obj.style.visibility =='' )
		    {	
		        obj.style.visibility = 'visible';
		        obj.style.display ='block';		       
		    }
		    else
		    {
		        obj.style.visibility = 'hidden';
		        obj.style.display = 'none';		    
		    }
		}
	}    
}

function switchClass(divId,newClass){
	if(document.getElementById(divId)){
		document.getElementById(divId).className=newClass;
	}
}

function ifIE6(){
	return (navigator.userAgent.toLowerCase().substr(25,6)=="msie 6") ? true : false;
}

function ifIE(){
	var browserName=navigator.appName; 
	if (browserName=="Microsoft Internet Explorer")
	{
		return true;
	}else{
		return false;
	}
}

function ifChrome(){
	var browserName=navigator.userAgent; 
	if (browserName.indexOf("Chrome")!=-1)
	{
		return true;
	}else{
		return false;
	}
}

function ifOpera(){
	var browserName=navigator.appName; 
	if (browserName=="Opera")
	{
		return true;
	}else{
		return false;
	}
}

/******************************
 * Check box
 ******************************/

//changing checkboxes
function changeCheckboxes(checkboxId,hiddenInput) {
	var checkbox=document.getElementById(checkboxId);
	if(checkbox){
		var hiddenInputObj=document.getElementById(hiddenInput);
		if(checkbox.className=="checkboxAreaChecked") {
			checkCheckboxes(checkboxId, false);
			hiddenInputObj.value="";
		}
		else {
			var separator=hiddenInput.indexOf("_");
			var inputValue=hiddenInput.substring((separator+1),hiddenInput.length);
			hiddenInputObj.value=inputValue;
			checkCheckboxes(checkboxId, true);
		} 
	}
}
function changeWishlistCheckboxes(checkboxId,hiddenInput) {
	var checkbox=document.getElementById(checkboxId);
	if(checkbox){
		var hiddenInputObj=document.getElementById(hiddenInput);
		if(checkbox.className=="checkboxAreaChecked") {
			checkCheckboxes(checkboxId, false);
			hiddenInputObj.checked="";
		}
		else {
			var separator=hiddenInput.indexOf("_");
			var inputValue=hiddenInput.substring((separator+1),hiddenInput.length);
			hiddenInputObj.checked="checked";
			checkCheckboxes(checkboxId, true);
		} 
	}
}

function checkCheckboxes(checkboxId, action) {
	var checkbox=document.getElementById(checkboxId);
	if(checkbox){
		if(action == true) {
			checkbox.className = "checkboxAreaChecked";
			checkbox.checked = true;
		}
		if(action == false) {
			checkbox.className = "checkboxArea";
			checkbox.checked = false;
		}
	}
}
function getCompareObjByID(pSKU){
	var campObj = document.getElementById('compareBox_'+pSKU);
	return campObj;
}

/* in RED design the product detailpage has a different design for compare box.
 * the variable ShowCompareMini is initialized in th CC_ShowMiniCompareBasket
 * and the ShowMini is checked in CC_CompareProducts template.
 */

var ShowCompareMini = false;

function addProductToCompare(productRefId){
	pSKU = productRefId.split('@')[0];	
	if(getCompareObjByID(pSKU).className=='checkboxAreaChecked'){
		$("#compareBasket").load(addProductCompareURL,{'ProductRefId':productRefId,'ShowCompareMini':ShowCompareMini});
	}
}

function removeCompare(productRefId){
	pSKU = productRefId.split('@')[0];	
	$("#compareBasket").load(removeProductCompareURL,{'ProductRefId':productRefId,'ShowCompareMini':ShowCompareMini});
	if(getCompareObjByID(pSKU)){
		getCompareObjByID(pSKU).className="checkboxArea";
	}
}
/*******************************************************
 * Comparing products - To check the products category,
 *           maximum comparision of products and so on. 
 * moving from CC_CompareScript.isml *
 *******************************************************/
var NumberOfCompareProducts = 0;
var CompareCategory = '';

function checkFullCompareAndCorrectCategory(productCategory, productRef){
	
	cookie = readCookie("CompareProducts");
	// if the basket already contains the sku, 
	// the checkbox is being UNchecked, so remove it.
	if((cookie != null) && (cookie.search(productRef + "(,|$)") != -1)){		
		removeCompare(productRef);
		return true;
	}
	if (CompareCategory == "") CompareCategory = productCategory;
	if(NumberOfCompareProducts>=3){
		showFullCompareMessage();
		return true;
	}else if(CompareCategory!=productCategory){
		showWrongCategoryToCompareMessage();
		return true;
	}else{
		return false;
	}
}

/* 110517 v1. new init handler for compare checkboxes */
function initCompareCheckboxes(){
	$(".product_list .checkboxArea, #tProduct .checkboxArea").each(function(){
		if ($(this).data("initialized_compare")) {
			// do nothing because checkbox function has alread been added
		} else {
			$(this).data("initialized_compare", true);
			$(this).click(function(e){
					var params = (this.getAttribute('rel')).split(";"); // required (MDTemplateRef;ProductRef)
					sku = params[1].split("@")[0];
					params.push( (this.id).slice((this.id).indexOf("_")+1) );
					if(!checkFullCompareAndCorrectCategory( params[0], params[1])) {
						changeCheckboxes('compareBox_'+sku,'compareProduct_'+sku);
						addProductToCompare(params[1]);
					}
			});
		}
	});
}
function initCheckboxes(){
	$(".chkbox").click(function(e){
		var thisBox = $(this);
		var inpObj  = $('input[type="hidden"]', thisBox);  
		eval("var params = " + this.getAttribute("rel"));
		if( thisBox.hasClass( params.selectc ) ){
			thisBox.removeClass( params.selectc );
			inpObj.val("");
		}
		else {
			thisBox.addClass( params.selectc );
			inpObj.val("checked");
		}
	});
}

/* default text in inputfields handler */
function initDefaultInputTextSwitcher(){
	window.dtfields = true;
	$("#WFSimpleSearch_NameOrID, #LoginForm_Login, #LoginForm_Password").each(function(){
		var inputObj = $(this);
		var formObj  = inputObj.closest("form");
		if(formObj.data("dtfield")) {
			var arr = formObj.data("dtfield");
			if($.inArray(this, arr) == -1){
				arr.push(this);
				formObj.data("dtfield", arr);
			}
		} else { formObj.data("dtfield", [this]); }

		this.defaultText = inputObj.attr("title");
		inputObj.focus(hideDefaultText);
		inputObj.blur(showDefaultText);
		
		if (this.addEventListener){
			this.addEventListener ("dragenter", hideDefaultText, false);
			this.addEventListener ("dragleave", showDefaultText, false);
			this.addEventListener ("dragexit", function(){ self = this; setTimeout(showDefaultText, 500)}, false);
		} else {
			this.ondrop  = hideDefaultText;
		}
		function hideDefaultText(){ if(this.value == this.defaultText){ this.value = ""; }}
		function showDefaultText(){
			var triggerOBj = (this == window) ? self:this;  
			if(triggerOBj.value == "") triggerOBj.value = triggerOBj.defaultText;
		}
	});
}
function initSubmitTriggers(){
	if ( window.dtfields != true) return;
	$("#SimSearch .submit, #LoginForm .submit").each(function(){
		var formObj = $(this).closest("form");
		if($("input[type=submit]", formObj).length == 0) {
			$('input', formObj).bind("keypress", {submitObj: this}, function(e){
				if(e.which == 13) { $(e.data.submitObj).click()	}
			});
		}
		formObj.submit(checkTextAndSubmit);
		$(this).click( function(){ formObj.submit()});
	});
	function checkTextAndSubmit(){
		var formObj = $(this);
		if(formObj.data("dtfield")){
			var arr = formObj.data("dtfield");
			for(var i = 0; i < arr.length; i++ ){
				if(arr[i].value == arr[i].defaultText){ arr[i].value = "" }
			}
		}
		return true;
	}
}
	
/* Remove the default text from the input field (user name, password, your e-mail, and etc.) */
function removeText(obj, dText){
	if(dText == obj.value){
		obj.value='';
		obj.focus();
	}	
}
function defaultTextPopup(obj, dText){
	if('' == obj.value){
		obj.value=dText;
	}		
}
function showPopup(popUpId){
	var _popup=document.getElementById(popUpId);
	var _height, _width;

	if (window.innerHeight){  _height = window.innerHeight; } else { _height = document.documentElement.clientHeight; }
	if (window.innerWidth){ _width = window.innerWidth; } else { _width = document.documentElement.clientWidth; }

	_popup.style.position = "absolute";
	var top=(document.documentElement.scrollTop + (_height - _popup.clientHeight) / 2);
	_popup.style.top=top+'px';
	var width=(_width - _popup.clientWidth)/2;
	_popup.style.left=width+'px';
	_popup.style.zIndex=1000;
	_popup.style.display="block";
}

function showFullCompareMessage(){
	var msgText=document.getElementById('maximumCompareProductsMSG').innerHTML;
	document.getElementById("messageText").innerHTML=msgText;
	showPopup('messagePopUp');
}

function showWrongCategoryToCompareMessage(){
	var msgText=document.getElementById('wrongCategoryCompareMSG').innerHTML;
	document.getElementById("messageText").innerHTML=msgText;
	showPopup('messagePopUp');
}
function buyInsurance(){

	document.getElementById('addInsuranceForm').submit();
}
/* Installation */
function chooseOption(obj,combineFormID){
	if(obj!=null&&obj.value!=''){
		var elementForm = document.getElementById(combineFormID);
		if(elementForm.ProductRefID!=null&&elementForm.ProductRefID!=undefined && elementForm.ProductRefID.value!=undefined)
			elementForm.ProductRefID.value=obj.value;
		elementForm.submit();
	}
}
/* Insurance */
function chooseInsuranceOption(obj,combineFormID){
	var day = document.getElementById('InsuranceConfirm_Day');
	var month = document.getElementById('InsuranceConfirm_Month');
	var year = document.getElementById('InsuranceConfirm_Year');
	// Advanced validation
	if (day != null && month != null && year != null) {
		if (day.value == 0 || month.value == 0 || year.value == 0) {
			document.getElementById('InsuranceConfirmation_ErrorMessage').innerHTML = document.getElementById('InsuranceConfirmation_ErrorMissingDate').innerHTML;
			document.getElementById('InsuranceConfirmation_ErrorMessageHolder').style.visibility = "visible";
			return false;
		}
		// validate age
		var birthDate = new Date();
		birthDate.setFullYear(year.value,month.value-1,day.value);
		var ageLimitBirthDate = new Date();
		ageLimitBirthDate.setYear(ageLimitBirthDate.getYear()-18);
		if (birthDate>ageLimitBirthDate) {
			document.getElementById('InsuranceConfirmation_ErrorMessage').innerHTML = document.getElementById('InsuranceConfirmation_ErrorUnderAged').innerHTML;
			document.getElementById('InsuranceConfirmation_ErrorMessageHolder').style.visibility = "visible";
			return false;
		}
		// validate terms & conditions checkbox
		if (!document.getElementById('InsuranceConfirm_Accept').checked) {
			document.getElementById('InsuranceConfirmation_ErrorMessage').innerHTML = document.getElementById('InsuranceConfirmation_ErrorNotAccepted').innerHTML;
			document.getElementById('InsuranceConfirmation_ErrorMessageHolder').style.visibility = "visible";
			return false;
		}
	}
	if(obj!=null&&obj.value!=''){
		var elementForm = document.getElementById(combineFormID);
		if(elementForm.InsuranceInfoID!=null&&elementForm.InsuranceInfoID!=undefined && elementForm.InsuranceInfoID.value!=undefined)
			elementForm.InsuranceInfoID.value=obj.value;
		elementForm.submit();
	}
}
/* Popup Message */
function closeMessagePopup(){
	simpleHide('messagePopUp');
}
/* Checkout button */
function submitCheckoutForm(formId,buttonName){
	var sForm = document.getElementById(formId);
	if(sForm!=null){
		if(buttonName!=null&&buttonName.length>0){
			var input = document.createElement("input");
			input.setAttribute("type", "hidden");
			input.setAttribute("name", buttonName);
			input.setAttribute("value", buttonName);
			input.setAttribute("class", "inputhidden");
			sForm.appendChild(input);
		}
		sForm.submit();
	}
}
function textLimitationById(id,maxNo){
	var obj = document.getElementById(id);
	if(obj!=null&&obj.innerHTML!=undefined){
		var contentStr = obj.innerHTML;
		if(parseInt(contentStr.length) > parseInt(maxNo)){
			document.getElementById(id).innerHTML = contentStr.substring(0,parseInt(maxNo))+'...';
		}
	}
}

/* Checkout functions */
function initDeliveryButtons(){
	$("#tCheckoutShipping .deliveryMethods input").click(function(e){
		var deliveryUUID = $(this).attr("value");
		var targetURL = $("#ajaxDeliveryURL").val();
		var currentSM = $("#PreviouslySelected").val();
		
		$.ajax({ url: targetURL,data: "DeliveryUUID="+deliveryUUID+"&CurrentShippingMethod="+currentSM,
			success: function(html){
				document.getElementById('deliveryDetails').innerHTML = html;
				initDeliveryCalendar();
				changeShippingMethod(deliveryUUID);
			}
		});
	});
}

/* Suggested Product Box
   Product Detail Page: Accessory, Alternative and Package Boxes
   Article (Guide) Page: Related Product Box
*/
function prev(boxName,iMaxNo){
	var objId = boxName+"SelectedNo";
	var validatedNo = parseInt(document.getElementById(objId).value)-1;
	if(checkAvailable(boxName+'No'+validatedNo)){
		document.getElementById(objId).value = parseInt(document.getElementById(objId).value)-1;
		selectNo(boxName,iMaxNo);
	}
}
function next(boxName,iMaxNo){
	var objId = boxName+"SelectedNo";
	var validatedNo = parseInt(document.getElementById(objId).value)+parseInt(iMaxNo);
	if(checkAvailable(boxName+'No'+validatedNo)){
		document.getElementById(objId).value = parseInt(document.getElementById(objId).value)+1;
		selectNo(boxName,iMaxNo);
	}
}

function selectNo(boxName,iMaxNo){
	//alert('boxName: '+boxName);
	var total = document.getElementById(boxName+"TotalNo").value;
	var selectedNo = document.getElementById(boxName+"SelectedNo").value;
	var prevNo = parseInt(selectedNo)-1;
	var nextNo = parseInt(selectedNo)+parseInt(iMaxNo);
	iMaxNo = parseInt(iMaxNo);
	
	//hide a previous item
	if(checkAvailable(boxName+"No"+prevNo)){
		setStyleDisplay(boxName+"No"+prevNo,'none');
	}
	//show a selected item			
	if(checkAvailable(boxName+"No"+selectedNo)){
		setStyleDisplay(boxName+"No"+selectedNo,'block');
	}
	
	//hide a next item
	if(checkAvailable(boxName+"No"+nextNo)){
		setStyleDisplay(boxName+"No"+nextNo,'none');
	}
	
	//showing the remaining items
	var index = parseInt(iMaxNo);
	while(--index>0){	
		if(checkAvailable(boxName+"No"+(parseInt(selectedNo)+index))){
			setStyleDisplay(boxName+"No"+(parseInt(selectedNo)+index),'block');
		}			
	}
	
	//manage prev|next buttons
	document.getElementById(boxName+"Prev").className = "btn-nav-prev";
	if( (parseInt(selectedNo)-1) < 0){
		document.getElementById(boxName+"Prev").className += " btn-nav-prev-disabled";
	}
	document.getElementById(boxName+"Next").className = "btn-nav-next";
	if( (parseInt(selectedNo)+iMaxNo) >= total){
		document.getElementById(boxName+"Next").className += " btn-nav-next-disabled";
	}	
}
function disablingDivByBoxKey(boxKey){
	if(boxKey!=''){
		for(var i=0;;i++){
			var boxObj = document.getElementById(boxKey+"No"+i);
			if(boxObj!=undefined){
				boxObj.style.display = "none";
			}else{
				break;
			}
		}
	}
	
}
function navOnMouseOver(defaultClassName,obj){
	obj.className = defaultClassName+" highlight-navigator";
}
function navOnMouseOut(defaultClassName,obj){
	obj.className = defaultClassName;
}
function setStyleDisplay(idName,displayValue){
	document.getElementById(idName).style.display=displayValue;
}
function checkAvailable(idName){
	//alert('id='+idName+', value='+document.getElementById(idName));
	var retFlg = true;
	if( (document.getElementById(idName)== null) || (document.getElementById(idName) == undefined)){
		retFlg = false;
	}
	return retFlg;
}
/***** Article (Guide) ****/
function addGuideTabsById(id){
	var tabsObj = document.getElementById("guideTabs");
	var obj = document.getElementById('title_'+id);
	if(tabsObj!=null&&tabsObj.innerHTML!=undefined){
		tabsObj.innerHTML = tabsObj.innerHTML+obj.innerHTML;
		obj.innerHTML = '';
		var defaultObj = document.getElementById("defaultGuideTab");
		if(defaultObj!=null&&defaultObj.innerHTML!=undefined&&defaultObj.value==''){
			visibleArticleTab(id);
			defaultObj.value="unavailable";
		}
	}
}
function visibleArticleTab(id){
	var contentObj = document.getElementById('content_'+id);
	var titleObj = document.getElementById('title_'+id);
	var spanObj = document.getElementById('span_'+id);
	var currentActiveId = document.getElementById('currentTabID').value;
	if(currentActiveId!=null&&currentActiveId!=''){
		var currentContentObj = document.getElementById('content_'+currentActiveId);
		var currentSpanObj = document.getElementById('span_'+currentActiveId);
		currentContentObj.style.display = 'none';
		currentSpanObj.className = '';
	}
	
	contentObj.style.display='block';
	spanObj.className='active';
	document.getElementById('currentTabID').value=id;
}
function addToImageNavigator(id,parentId){
	var mainNavObj = document.getElementById('imageNavigatorTmp_'+parentId);
	var navObj = document.getElementById('smallImage_'+id);

	var defaultObj = document.getElementById("defaultImageGallery_"+parentId);
	if(defaultObj!=null&&defaultObj.innerHTML!=undefined&&defaultObj.value==''){
		activeGalleryImage(id,parentId);
		defaultObj.value="unavailable";
	}
	mainNavObj.innerHTML += navObj.innerHTML;
	navObj.innerHTML = '';
}
function initNavigator(pageletId){
	var tmpObj = document.getElementById("imageNavigatorTmp_"+pageletId);
	var navObj = document.getElementById("navigator_"+pageletId);
	if(tmpObj!=null&&tmpObj.innerHTML!=undefined&&tmpObj.innerHTML!=''){
		navObj.style.display = 'block';
		navObj.innerHTML = tmpObj.innerHTML;
		tmpObj.innerHTML="";
	}
}
function activeGalleryImage(id,parentId){	
	var activeGalleryObj = document.getElementById('activeImageGallery_'+parentId);
	var currentActive = activeGalleryObj.value;
	//hiding the current one
	if(currentActive!=null&&currentActive!=''){
		document.getElementById('imageGuide_'+currentActive).style.display = 'none';
		document.getElementById('bg_'+currentActive).className = 'image-nav';
	}
	//showing the active one
	document.getElementById('imageGuide_'+id).style.display = 'block';
	document.getElementById('bg_'+id).className = 'image-nav image-active';
	//noting the current one
	activeGalleryObj.value=id;
}
function goNextGallery(parentId){
	var activeGalleryObj = document.getElementById('activeImageGallery_'+parentId);
	var currentActive = activeGalleryObj.value;
	
	var gForm = document.getElementById('galleryForm_'+parentId);
	if(gForm.hiddenImgKeys.length>1){
		for(var i=0;i<gForm.hiddenImgKeys.length;i++){
			var key = gForm.hiddenImgKeys[i].value;
			//finding an order of the current key and check the next item.
			if(key==currentActive){
				//if the currentActive is not the last step, then move to the next step
				if((i+1)<gForm.hiddenImgKeys.length){
					activeKey = gForm.hiddenImgKeys[i+1].value;
					activeGalleryImage(activeKey,parentId)
					break;
				}
			}
		}
	}
}
/*** Changing bg-color or img ***/
function setBackground(bgColor,bgImage){
	var theObj = document.getElementById("cPage");
	if(bgImage!=''){
		theObj.style.backgroundImage = 'url('+bgImage+')';
	}
	if(bgColor!=''){
		theObj.style.backgroundColor = bgColor;		
	}
}
/*** user login ****/

function continueLogin(){
	document.LoginForm.submit();
}
function go2URL(url){
	window.location = url;
}
function checkPressedKey(myfield,e,text)
{
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;

    if (keycode == 13)
    {
    	removeLoginDefaultText();
    	continueLogin();
    }
}

function loginUserLightbox(loginContext){
	// loginContext drives the JumpTarget at the end of the login process
	var url = document.getElementById('loginUserLightbox').innerHTML + "?" + loginContext + '=' + loginContext ;
	
	// Hide errors
	simpleHide("errorMsg");
	simpleHide("missinginformation");
	simpleHide("LoginWithoutLogin");
	simpleHide("LoginWithoutPassword");
	simpleHide("IncorrectPassword");
	simpleHide("UnableToFindMembershipData");
	simpleHide("UserNotLoggedIn");
	simpleHide("AccountTemporarilyLocked");
		
	// Call login through ajax
	$.ajax({url: url,
			async: false,
			type: 'POST',
			data: "LoginForm_Login=" + $('#LoginForm_Login').val() + "&LoginForm_Password=" +  $('#LoginForm_Password').val() + "&rememberMeId=" + $('#rememberMeId').val(),
			dataType: "json",
			success: function(data){
				///alert(data);
				if (data.JumpTarget) {
					//alert(data.JumpTarget);
					// We have a JumpTarget --> login is successful
					
					//window.location = data.JumpTarget;
					parent.location = data.JumpTarget;
				} else {
					// We do not have a target --> login is not successful
					//alert(data.ERROR_User);
					
					// Display Errors					
					document.getElementById('Login').className += ' login-error'

					if(data.ERROR_User == 'LoginWithoutLogin' || data.ERROR_User == 'LoginWithoutPassword')
						$("#missinginformation").css("display","inline");
					
					if(data.ERROR_User == 'LoginWithoutLogin')
						$("#LoginWithoutLogin").css("display","inline");
					
					if(data.ERROR_User == 'LoginWithoutPassword')
						$("#LoginWithoutPassword").css("display","inline");				
					
					if(data.ERROR_User == 'IncorrectPassword')
						$("#IncorrectPassword").css("display","inline");

					if(data.ERROR_User == 'UnableToFindMembershipData')
						$("#UnableToFindMembershipData").css("display","inline");

					if(data.ERROR_User == 'UserNotLoggedIn')
						$("#UserNotLoggedIn").css("display","inline");

					if(data.ERROR_User == 'AccountTemporarilyLocked')
						$("#AccountTemporarilyLocked").css("display","inline");
					
					simpleShow("errorMsg");
				}
			}
	});
	return false;
}


/*** Social login lightbox ***/
function closeLoginLightbox(){
	//alert(parent);
	//alert(parent.document.getElementById('light'));
	
	if(parent.document.getElementById(lightBoxContentId)!=undefined)
		parent.document.getElementById(lightBoxContentId).innerHTML = '';	
	setParentObjDisplay(lightBoxId,'none');
	setParentObjDisplay(bgAreaId,'none');
	setParentObjDisplay(closeButtonId,'none');
}

function viewLoginLightbox(loginContext){
	// loginContext drives the JumpTarget at the end of the login process
	var url = document.getElementById('viewLoginLightbox').innerHTML;
	document.getElementById('light').innerHTML='<iframe src="' + url + '?' + loginContext + '=' + loginContext + '" frameborder="0" width="880px" height="600px" scrolling="no" style="border-radius: 25px" ><p>Your browser does not support iframes.</p></iframe>';		
	setLightBoxSize('900px','auto');
	visibleLightBox();		
	initCheckboxes();
	initDefaultInputTextSwitcher();
}

/*** Product Details: product tabs ****/
var pDetailTabs = new Array("Packages","Specifications","Features","RatingBV","RatingBEnfinity","MoreInfo","StoreLocator");
var pSuggestedTabs = new Array("Alternatives","Packages","Accessories");
var reqContentTabs = new Array("Installation","Return","Accessories");
var categoryLevel1Tabs = new Array("Featured","TopRated","TopSeller");
var googleMapTabs = new Array("Address","Store");

function enableTab(id,tabGroup){		
	var activeTabs = pDetailTabs;
	if(tabGroup!=''){
		if(tabGroup=='ReqTabs'){
			activeTabs = reqContentTabs;
		}else{
			if(tabGroup=='CategoryLevel1Tabs'){
				activeTabs = categoryLevel1Tabs;
			}else if(tabGroup=='map'){
				activeTabs = googleMapTabs;
			}else{
				activeTabs = pSuggestedTabs;
			}
		}
	}
	var theTab=document.getElementById(id+"Tab");
	if(activeTabs.length >0&&theTab!=undefined){
		//disabling all tabs and their info		
		for(var i=0;i<activeTabs.length;i++){
			var tabId = activeTabs[i];
			displayTab(tabId,'x');
		}			
		displayTab(id,'y');
		if(tabGroup==''){
			updatingActiveTab(id+"Tab");
		}
	}
}
function updatingActiveTab(id){
	var tabIdObj = document.getElementById("tabActiveId");
	if(tabIdObj){
		tabIdObj.value = id;
	}
}
function scrollingToObj(id){

	var posX = 0;
	var posY = 0;
	var focusTab=document.getElementById(id);
	if( typeof( focusTab.offsetParent ) != 'undefined' ) {
		for( var posX = 0, posY = 0; focusTab; focusTab = focusTab.offsetParent ) {
			posX += focusTab.offsetLeft;
			posY += focusTab.offsetTop;
		}
	}

	window.scrollTo(posX,posY);

}
function displayTab(id,xyFlag){
	var theTab=document.getElementById(id+"Tab");
	var theInfo=document.getElementById(id+"Info");	
	if(theTab!=undefined&&theInfo!=undefined){
		if(xyFlag=='x'){
			theTab.className="";
			theInfo.style.display="none";
		}else if(xyFlag=='y'){
			theTab.className="active";
			theInfo.style.display="block";
		}
	}
}
/*** executing functions after the script has done with shortening text ***/
var loadFunc = ['blank'];
function addLoadFunc(funcName){
	if(loadFunc.length != undefined){
		loadFunc[loadFunc.length]=funcName;
	}
}
function exeFunc(){
	if(loadFunc.length>1){
		for(var i=1;i<loadFunc.length;i++){
			eval(loadFunc[i])();
		}
	}
}
/*** checkout selection ***/

var active_select = null;
var _selectHeight = 27;
function hideSelectOptions(e)
{
	if(active_select)
	{
		if(!e) e = window.event;
		var _target = (e.target || e.srcElement);
		if(isElementBefore(_target,'selectArea') == 0 && isElementBefore(_target,'optionsDiv') == 0)
		{
			active_select.className = active_select.className.replace('optionsDivVisible', '');
			active_select.className = active_select.className.replace('optionsDivInvisible', '');
			active_select.className += " optionsDivInvisible";
			active_select = false;

			if(document.documentElement)
			{
				document.documentElement.onclick = function(){};
			}
			else
			{
				window.onclick = null;
			}
		}
	}
}

function isElementBefore(_el,_class)
{
	var _parent = _el;	
	do
	{
		_parent = _parent.parentNode;
	}
	while(_parent && _parent.className != null && _parent.className.indexOf(_class) == -1)
	
	if(_parent.className && _parent.className.indexOf(_class) != -1)
	{
		return 1;
	}
	else
	{
		return 0;
	}
	
}
function findPosY(obj) {
	var posTop = 0;
	posTop += obj.offsetTop;
	obj = obj.offsetParent;
	if(obj.offsetParent)
		posTop += obj.offsetTop;
	return posTop;
}

function findPosX(obj) {

	var posLeft = 0;
	posLeft += obj.offsetLeft;
	obj = obj.offsetParent;
	if(obj.offsetParent)
		posLeft += obj.offsetLeft;
	return posLeft;
}

function showOptionsCheckout(g,flag) {
	_elem = document.getElementById("optionsDiv"+g);
	var divArea = document.getElementById("sarea"+g);
	if (active_select && active_select != _elem) {
		active_select.className = active_select.className.replace('optionsDivVisible',' optionsDivInvisible');
		if(flag!='noAutoHeight'){
			active_select.style.height = "auto";
		}
	}
	if(_elem.className.indexOf("optionsDivInvisible") != -1) {
		_elem.style.left = "-9999px";
		_elem.className = _elem.className.replace('optionsDivInvisible','');
		_elem.className += " optionsDivVisible";
		if(flag=='item'){
			_elem.style.top = divArea.offsetTop + _selectHeight + 'px';
			_elem.style.left = divArea.offsetLeft + 'px';
		}else{
			_elem.style.top = (parseInt(findPosY(divArea)) + (parseInt(_selectHeight))) + 'px';
			_elem.style.left = findPosX(divArea) + 'px';
		}
		active_select = _elem;

		if(document.documentElement)
		{
			document.documentElement.onclick = hideSelectOptions;
		}
		else
		{
			window.onclick = hideSelectOptions;
		}
	}
	else if(_elem.className.indexOf("optionsDivVisible") != -1) {
		if(flag!='noAutoHeight'){
			_elem.style.height = "auto";
		}
		_elem.className = _elem.className.replace('optionsDivVisible','');
		_elem.className += " optionsDivInvisible";
	}
}
//selecting me
function selectValue(selectFieldId,linkNo,selectNo,checkOnChangeValue) {
	var selectedValue = '';
	selectField = document.getElementById("selectOptions"+selectNo);

	for(var k = 0; k < selectField.options.length; k++) {
		if(k==linkNo) {
			selectField.options[k].selected = "selected";
			selectedValue = selectField.options[k].value;
			break;
		}
		else {
			selectField.options[k].selected = "";
		}
	}	
	//show selected option
	textVar = document.getElementById("mySelectText"+selectNo);
	var newText;
	var optionSpan;
	if (selectField.options[linkNo].title.indexOf('image') != -1) {
		newText = document.createElement('img');
		newText.src = selectField.options[linkNo].title;
		optionSpan = document.createElement('span');
		optionSpan = document.createTextNode(selectField.options[linkNo].text);
	} else {
		newText = document.createTextNode(selectField.options[linkNo].text);
	}
	if (selectField.options[linkNo].title.indexOf('image') != -1) {
		if (textVar.childNodes.length > 1) textVar.removeChild(textVar.childNodes[0]);
		textVar.replaceChild(newText, textVar.childNodes[0]);	
		textVar.appendChild(optionSpan);	
	} else {
		if (textVar.childNodes.length > 1) textVar.removeChild(textVar.childNodes[0]);
		textVar.replaceChild(newText, textVar.childNodes[0]);	
	}
	
	var checkOnChange = false;
	if(selectedValue!=checkOnChangeValue){
		checkOnChange = true;
	}
	if (selectField.onchange&&checkOnChange)
	{
		eval(selectField.onchange());
	}
}

function addPageTitleInBreadcrumb(pageTitle){
	document.getElementById("breadCrumbLinks").innerHTML+=("<li><span><a title='"+pageTitle+"' style='text-decoration:none;'>"+pageTitle+"</a></span></li>");
}
function addPageTitleAndLinkInBreadcrumb(link, pageTitle){
	document.getElementById("breadCrumbLinks").innerHTML+=("<li><span><a title='"+pageTitle+"' href='"+link+"' style='text-decoration:none;'>"+pageTitle+"</a></span></li>");
}

// Newsletter e-mail box cookie
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) {			
			value=c.substring(nameEQ.length,c.length);
            // Enfinity sets cookies surrounded by quotes, like name="myname" (?) but sometimes (???) it doesn't!! name=myname
			// Always remove quotes if present
			if ((value.charAt(0) == "\"") && (value.charAt(value.length -1) == "\"")) {
				value=value.substr(1,value.length - 2);
			}
			return value;
		}
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}	

/*---------------------------------------------
 * 
 * former cart.js section
 * Dependencies
 *  - jQuery 
 */

/* new add to basket, eventually replacing addToBasket function */
function initAddToCartButtons(){
	$(".addToCartAction").each(function(){
		if ($(this).data("initialized_addToCart")) {
			// do nothing because addToBasket click function has alread been added
		} else {
			$(this).data("initialized_addToCart", true);
			
			$(this).click(function(e){
				var container   = $(this).closest('li');
				var productName = $("h2 a", container).attr("title")
				productName     = productName != "" ? productName:$("h2 a", container).html();
				$(this).data("productName", productName);
				
				$.ajax({ url: $(this).attr("href"),	triggerObj: $(this),
					success: function(html){
						document.getElementById('miniCart').innerHTML = html;
						s.events = 'scAdd';
						s.products = ";" + this.triggerObj.data("productName") + " (SKU "+ this.triggerObj.attr("rel") +")";
						void(s.t());
						reloadECCPanel();
						initBasketLoginPanel();
					}
				});
				return false;
			});
		} // end if already initialized
	});
}

function addToBasket(ProductID, Quantity, ProductSKU, ProductName){
	var url=document.getElementById('addToBasketURL').innerHTML;
	$.ajax({url: url,data: "ProductID="+ProductID+"&Quantity="+Quantity,success: function(html){
		document.getElementById('miniCart').innerHTML=html;
		s.events = 'scAdd';
		s.products = ";" + ProductName + " (SKU " + ProductSKU + ")";
		void(s.t());
		reloadECCPanel();
		initBasketLoginPanel();
	}});
	
}

function reloadECCPanel(){
	// See CC_ECCFrameset template for explanation
	if (parent.eccframe !== undefined) {
		parent.document.getElementById("eccframe").onload = function() { parent.bindOnloadEvents() };
		parent.document.getElementById("eccframe").src = ReloadECCURL;
	}	
}


function closeMiniWindow(){
	document.getElementById("miniBasket").style.display = "none";
}

/*---------------------------------------------
 * former detectbrowser.js section
 */

var detect = navigator.userAgent.toLowerCase();
var OS,browser,total,thestring;
var version = 0;

if (checkIt('konqueror'))
{
	browser = "Konqueror";
	OS = "Linux";
}
else if (checkIt('firefox')) browser = "FireFox"
else if (checkIt('safari')) browser = "Safari"
else if (checkIt('omniweb')) browser = "OmniWeb"
else if (checkIt('opera')) browser = "Opera"
else if (checkIt('webtv')) browser = "WebTV";
else if (checkIt('icab')) browser = "iCab"
else if (checkIt('msie')) browser = "Internet Explorer"
else if (!checkIt('compatible'))
{
	browser = "Netscape Navigator"
	version = detect.charAt(8);
}
else browser = "An unknown browser";

if (!version) version = detect.charAt(place + thestring.length);

if (!OS)
{
	if (checkIt('linux')) OS = "Linux";
	else if (checkIt('x11')) OS = "Unix";
	else if (checkIt('mac')) OS = "Mac"
	else if (checkIt('win')) OS = "Windows"
	else OS = "an unknown operating system";
}

function checkIt(string)
{
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}



/*---------------------------------------------
 * former productNotification.js section
 * Dependencies
 *  - jQuery
 * 
 */
function createAlert(Action, ProductUUID, NotificationMailAddress, SubscribeToNewsletter){
	$.get(Action, {
		'ProductUUID':ProductUUID, 
		'AlertForm_NotificationMailAddress':NotificationMailAddress,
		'webform-id':'AlertForm',
		'Alert_Type':'InStockNotification',
		'SubscribeToNewsletter':SubscribeToNewsletter});
}
function loadAlert(returnID,Action, ProductUUID, NotificationMailAddress, SubscribeToNewsletter){ 
	$('#'+returnID).load(Action,{
		'ProductUUID':ProductUUID, 
		'AlertForm_NotificationMailAddress':NotificationMailAddress,
		'webform-id':'AlertForm',
		'Alert_Type':'InStockNotification',
		'returnID':returnID,
		'SubscribeToNewsletter':SubscribeToNewsletter});
}
var sendNotification = function(e,elm){
		var checked = (elm.siblings(".newsletter-wrapper").find("input:checked").length > 0);
		var email = elm.siblings(".text-wrapper").find("input").val();		
		var product_uuid = elm.attr("rel");
		var returnID = elm.attr("rev");
		if(returnID=='')
			returnID = 'notify-popup';
		else
			returnID = returnID;
		loadAlert(returnID,elm.attr("name"),product_uuid,email,checked);
		if(e!=undefined)
			e.stopPropagation();
		return false;
	}
function submitNotification(link){
	var elm =$('.notify-form a.link-button'); 
	
	sendNotification(window.event,elm);	
}
/*---------------------------------------------
 * Former lightbox.js file
 * Dependencies
 *  - jQuery
 * 
 */

var lightBoxId = "light";
var bgAreaId = "fade";

var lightBoxHeaderId = "lbHeader";
var lightBoxContentId = "lbContent";
var closeButtonId = "defaultLightBoxCloseButton";
var friendlyPrintingTmp = "";

function closeLightBox(){
	if(document.getElementById(lightBoxContentId)!=undefined)
		document.getElementById(lightBoxContentId).innerHTML = '';	
	setObjDisplay(lightBoxId,'none');
	setObjDisplay(bgAreaId,'none');
	setObjDisplay(closeButtonId,'none');
}
function turnOnCloseButton(){
	setObjDisplay(closeButtonId,'block');
	document.getElementById(lightBoxContentId).style.height='';
}
function visibleLightBox(){	
	var objOverlay = document.getElementById(bgAreaId);
	var objLightBox = document.getElementById(lightBoxId);
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	
	objOverlay.style.height = (arrayPageSize[1] + 'px');
	setObjDisplay(lightBoxId,'block');
	setObjDisplay(bgAreaId,'block');
	
	//light box is in the center
	var posY = (arrayPageScroll[1] + ((arrayPageSize[3] - 45 - objLightBox.offsetHeight) / 2));
	if(posY>0)
		objLightBox.style.top =  posY+ 'px';
	else
		objLightBox.style.top =  '5px';
	
	objLightBox.style.left = (((arrayPageSize[0] - 20 - objLightBox.offsetWidth) / 2) + 'px');	
}
function setParentObjDisplay(objId,displayValue){
	if(parent.document.getElementById(objId)!=undefined)
		parent.document.getElementById(objId).style.display = displayValue;
}
function setObjDisplay(objId,displayValue){
	if(document.getElementById(objId)!=undefined)
		document.getElementById(objId).style.display = displayValue;
}
function  showLightBox(header,contentHTML){	
	document.getElementById(lightBoxHeaderId).innerHTML = "<strong>"+header+"</strong>";
	if(contentHTML!='')
		document.getElementById(lightBoxContentId).innerHTML = "<p>"+contentHTML+"</p>";
	visibleLightBox();
}
function  setLightBoxContent(contentHTML){	
	document.getElementById(lightBoxContentId).innerHTML = "<p>"+contentHTML+"</p>";
}
var heightTmp = '';
function printingProductPage(){ window.print(); }
var refreshFlag = false;
var printLabelHeader = "";
function prepareProductForPrinting(printLabel){
	
	/** reset the action **/
	document.body.onmousemove = "";
	window.onfocus = "";
	if(heightTmp!=''){
		heightTmp='';
		document.getElementById(lightBoxId).style.height=heightTmp;
	}
	
	/*** Friendly Printing: the content on the pop-up should be printed only ****/
	printLabelHeader = printLabel;
	
	/* applies the friendly-printing-lib class to the whole page, so that it will not show in the print.
	 * the lightbox with our "print preview" content has a CSS marked as !important that will override the "invisibility".
	 */
	if (document.getElementById("AppFrame") != null) { 
		document.getElementById("AppFrame").className = "friendly-printing-lb" 
	} 
	
	var appHeader = document.getElementById("header");
	appHeader.className = "friendly-printing-lb";
	var footer = document.getElementById("footer");
	footer.className = "friendly-printing-lb";
	
	var prodContent = document.getElementById("cContent").innerHTML;	
	var chLogo = document.getElementById("chLogo");
	var chLogoHTML = chLogo.innerHTML;	
	var tmpChLogo = document.createElement("div");
	tmpChLogo.innerHTML = chLogoHTML;
	
	if(tmpChLogo!=null){
		var input = document.createElement("div");
		input.setAttribute("style", "float:right");
		input.innerHTML = '<a id="idPrint" class="print" href="#" style="float:right" onfocus="this.blur();" onclick="printingProductPage()" >'+printLabel+'</a>';
		tmpChLogo.appendChild(input);
	}
	chLogoHTML = tmpChLogo.innerHTML;	
	prodContent = chLogoHTML+prodContent;
	prodContent=prodContent.replace("chLogo","chLogoFriendlyPrinting");
	//prodContent.replace("chLogo","chLogoFriendlyPrinting");
	setLightBoxContent(prodContent);
	var topBanner = (document.getElementById("FriendlyPrintingTopBanner")!=undefined)?true:false;
	
	var S7Image=document.getElementById("S7FriendlyPrinting");
	if(document.getElementById("S7FriendlyPrinting")!=undefined){
		S7Image.innerHTML = document.getElementById("S7MainProductImage").innerHTML
	};
	
	
	$("#pdProductBoxes").remove();
	$("#idAsideBar").remove();
	$("#friendlyPrintingSpecLink").remove();
	if(topBanner) {
		$("#FriendlyPrintingTopBanner").remove();
	}
	$("#EnergyLabelInfo").remove();
	
	var activeTabName = "#" + $("#tabActiveId").val();
	$("#productDetailTabs").html('<li class="first last"><a href="#"><span class="active">'+ $(activeTabName).html() +'</span></a></li>');
	
	/*
	// remove the 'id' element because this id is assigned value in css and there is background set in it in Lefdal .
	var objPageContent = document.getElementById("cContent");
	objPageContent.id = '';
	objPageContent.style.paddingLeft = "10px";// For store font
	*/
	
	turnOnCloseButton();
	setLightBoxSize('760px','800px');
	//showLightBox(printLabel,'');
	showLightBox('','');
}
function  showLightBoxByContentId(header,contentId){	
	document.getElementById(lightBoxHeaderId).innerHTML = "<strong>"+header+"</strong>";
	document.getElementById(lightBoxContentId).innerHTML = "<p>"+document.getElementById(contentId).innerHTML+"</p>";
	visibleLightBox();
}
function  showLightBoxByURL(header,url){	
	document.getElementById(lightBoxHeaderId).innerHTML = "<strong>"+header+"</strong>";
	document.getElementById(lightBoxContentId).innerHTML = '';
	visibleLightBox();
	callURL(url);
	visibleLightBox();
}
function callURL(url){
	if(url!=''){
		$("#" + lightBoxContentId).load(url);
	}
}
function setLightBoxSize(lbWidth,lbHeight){
	if(lbWidth!=''){
		document.getElementById(lightBoxId).style.width=lbWidth;
	}else
		document.getElementById(lightBoxId).style.width='';
	if(lbHeight!=''){
		document.getElementById(lightBoxId).style.height=lbHeight;
	}else
		document.getElementById(lightBoxId).style.height='';
}
function divisionValue(value,div){
	var number='';
	var measurement = '';
	var anum=/(^\d+$)|(^\d+\.\d+$)/;
	var returnValue = '';
		
	if(value!=''&&value!=undefined){
		for(var index=0;index<value.length;index++){
			var x = value.substr(index,index+1);
			if (!anum.test(x)){
				measurement = value.substr(index+1);
				number = value.substr(0,index+1);
				break;
			}else{
				number+=(''+x);
			}
		}
		returnValue= (parseInt(number)/parseInt(div))+measurement;
		
	}
	return returnValue;
}
function setLightBoxAutoSize(){
	setLightBoxSize('','');
}


/*
Lightbox JS: Fullsize Image Overlays 
by Lokesh Dhakar - http://www.huddletogether.com

For more information on this script, visit:
http://huddletogether.com/projects/lightbox/

Licensed under the Creative Commons Attribution 2.5 License - http://creativecommons.org/licenses/by/2.5/
(basically, do anything you want, just leave my name and link)

Table of Contents
-----------------
Configuration

Functions
- getPageScroll()
- getPageSize()
- pause()
- getKey()
- listenKey()
- showLightbox()
- hideLightbox()
- initLightbox()
- addLoadEvent()

Function Calls
- addLoadEvent(initLightbox)

*/


//
//Configuration
//

//If you would like to use a custom loading image or close button reference them in the next two lines.
var loadingImage = 'loading.gif';		
var closeButton = 'close.gif';	
var webRoot = '';


//
//getPageScroll()
//Returns array with x,y page scroll values.
//Core code from - quirksmode.org
//
function getPageScroll(){

	var yScroll;
	
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
	}
	
	arrayPageScroll = new Array('',yScroll) 
	return arrayPageScroll;
}



//
//getPageSize()
//Returns array with page width, height and window width, height
//Core code from - quirksmode.org
//Edit for Firefox by pHaez
//
function getPageSize(){

	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = document.body.scrollWidth;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	if (self.innerHeight) {	// all except Explorer
		windowWidth = self.innerWidth;
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}
	
	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = windowWidth;
	} else {
		pageWidth = xScroll;
	}
	
	
	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}


//
//pause(numberMillis)
//Pauses code execution for specified time. Uses busy code, not good.
//Code from http://www.faqts.com/knowledge_base/view.phtml/aid/1602
//
function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime)
			return;
	}
}

//
//getKey(key)
//Gets keycode. If 'x' is pressed then it hides the lightbox.
//

function getKey(e){
	if (e == null) { // ie
		keycode = event.keyCode;
	} else { // mozilla
		keycode = e.which;
	}
	key = String.fromCharCode(keycode).toLowerCase();
	
	if(key == 'x'){ hideLightbox(); }
}


//
//listenKey()
//
function listenKey () {	document.onkeypress = getKey; }


//
//showLightbox()
//Preloads images. Pleaces new image in lightbox then centers and displays.
//
function showLightbox(objLink)
{
	// prep objects
	var objOverlay = document.getElementById('overlay');
	var objLightbox = document.getElementById('lightbox');
	var objCaption = document.getElementById('lightboxCaption');
	var objImage = document.getElementById('lightboxImage');
	var objLoadingImage = document.getElementById('loadingImage');
	var objLightboxDetails = document.getElementById('lightboxDetails');
	
	
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	
	// center loadingImage if it exists
	if (objLoadingImage) {
		objLoadingImage.style.top = (arrayPageScroll[1] + ((arrayPageSize[3] - 35 - objLoadingImage.height) / 2) + 'px');
		objLoadingImage.style.left = (((arrayPageSize[0] - 20 - objLoadingImage.width) / 2) + 'px');
		objLoadingImage.style.display = 'block';
	}
	
	// set height of Overlay to take up whole page and show
	objOverlay.style.height = (arrayPageSize[1] + 'px');
	objOverlay.style.display = 'block';
	
	// preload image
	imgPreload = new Image();
	
	imgPreload.onload=function(){
		objImage.src = objLink.href;
	
		// center lightbox and make sure that the top and left values are not negative
		// and the image placed outside the viewport
		var lightboxTop = arrayPageScroll[1] + ((arrayPageSize[3] - 35 - imgPreload.height) / 2);
		var lightboxLeft = ((arrayPageSize[0] - 20 - imgPreload.width) / 2);
		
		objLightbox.style.top = (lightboxTop < 0) ? "0px" : lightboxTop + "px";
		objLightbox.style.left = (lightboxLeft < 0) ? "0px" : lightboxLeft + "px";
	
	
		objLightboxDetails.style.width = imgPreload.width + 'px';
		
		if(objLink.getAttribute('title')){
			objCaption.style.display = 'block';
			//objCaption.style.width = imgPreload.width + 'px';
			objCaption.innerHTML = objLink.getAttribute('title');
		} else {
			objCaption.style.display = 'none';
		}
		
		// A small pause between the image loading and displaying is required with IE,
		// this prevents the previous image displaying for a short burst causing flicker.
		if (navigator.appVersion.indexOf("MSIE")!=-1){
			pause(250);
		} 
	
		if (objLoadingImage) {	objLoadingImage.style.display = 'none'; }
	
		// Hide select boxes as they will 'peek' through the image in IE
		selects = document.getElementsByTagName("select");
	    for (i = 0; i != selects.length; i++) {
	            selects[i].style.visibility = "hidden";
	    }
	
	
		objLightbox.style.display = 'block';
	
		// After image is loaded, update the overlay height as the new image might have
		// increased the overall page height.
		arrayPageSize = getPageSize();
		objOverlay.style.height = (arrayPageSize[1] + 'px');
		
		// Check for 'x' keypress
		listenKey();
	
		return false;
	}
	
	imgPreload.src = objLink.href;

}


//
//hideLightbox()
//
function hideLightbox()
{
	// get objects
	objOverlay = document.getElementById('overlay');
	objLightbox = document.getElementById('lightbox');
	
	// hide lightbox and overlay
	objOverlay.style.display = 'none';
	objLightbox.style.display = 'none';
	
	// make select boxes visible
	selects = document.getElementsByTagName("select");
	for (i = 0; i != selects.length; i++) {
		selects[i].style.visibility = "visible";
	}
	
	// disable keypress listener
	document.onkeypress = '';
}


//
//initLightbox()
//Function runs on window load, going through link tags looking for rel="lightbox".
//These links receive onclick events that enable the lightbox display for their targets.
//The function also inserts html markup at the top of the page which will be used as a
//container for the overlay pattern and the inline image.
//
function initLightbox()
	{
	
	if (!document.getElementsByTagName){ return; }
	var anchors = document.getElementsByTagName("a");
	
	// loop through all anchor tags
	for (var i=0; i<anchors.length; i++){
		var anchor = anchors[i];
	
		if (anchor.getAttribute("href") && (anchor.getAttribute("rel") == "lightbox")){
			anchor.onclick = function () {showLightbox(this); return false;}
		}
	}
	
	var objBody = document.getElementsByTagName("body").item(0);
	
	// create overlay div and hardcode some functional styles (aesthetic styles are in CSS file)
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','overlay');
	objOverlay.onclick = function () {hideLightbox(); return false;}
	objOverlay.style.display = 'none';
	objOverlay.style.position = 'absolute';
	objOverlay.style.top = '0';
	objOverlay.style.left = '0';
	objOverlay.style.zIndex = '90';
		objOverlay.style.width = '100%';
	objBody.insertBefore(objOverlay, objBody.firstChild);
	
	var arrayPageSize = getPageSize();
	var arrayPageScroll = getPageScroll();
	
	// preload and create loader image
	var imgPreloader = new Image();
	
	// if loader image found, create link to hide lightbox and create loadingimage
	imgPreloader.onload=function(){
	
		var objLoadingImageLink = document.createElement("a");
		objLoadingImageLink.setAttribute('href','#');
		objLoadingImageLink.onclick = function () {hideLightbox(); return false;}
		objOverlay.appendChild(objLoadingImageLink);
		
		var objLoadingImage = document.createElement("img");
		objLoadingImage.src = loadingImage;
		objLoadingImage.setAttribute('id','loadingImage');
		objLoadingImage.style.position = 'absolute';
		objLoadingImage.style.zIndex = '150';
		objLoadingImageLink.appendChild(objLoadingImage);
	
		imgPreloader.onload=function(){};	//	clear onLoad, as IE will flip out w/animated gifs
	
		return false;
	}
	
	imgPreloader.src = loadingImage;
	
	// create lightbox div, same note about styles as above
	var objLightbox = document.createElement("div");
	objLightbox.setAttribute('id','lightbox');
	objLightbox.style.display = 'none';
	objLightbox.style.position = 'absolute';
	objLightbox.style.zIndex = '100';	
	objBody.insertBefore(objLightbox, objOverlay.nextSibling);
	
	// create link
	var objLink = document.createElement("a");
	objLink.setAttribute('href','#');
	objLink.setAttribute('title','Click to close');
	objLink.onclick = function () {hideLightbox(); return false;}
	objLightbox.appendChild(objLink);
	
	// preload and create close button image
	var imgPreloadCloseButton = new Image();
	
	// if close button image found, 
	imgPreloadCloseButton.onload=function(){
	
		var objCloseButton = document.createElement("img");
		objCloseButton.src = closeButton;
		objCloseButton.setAttribute('id','closeButton');
		objCloseButton.style.position = 'absolute';
		objCloseButton.style.zIndex = '200';
		objLink.appendChild(objCloseButton);
	
		return false;
	}
	
	imgPreloadCloseButton.src = closeButton;
	
	// create image
	var objImage = document.createElement("img");
	objImage.setAttribute('id','lightboxImage');
	objLink.appendChild(objImage);
	
	// create details div, a container for the caption and keyboard message
	var objLightboxDetails = document.createElement("div");
	objLightboxDetails.setAttribute('id','lightboxDetails');
	objLightbox.appendChild(objLightboxDetails);
	
	// create caption
	var objCaption = document.createElement("div");
	objCaption.setAttribute('id','lightboxCaption');
	objCaption.style.display = 'none';
	objLightboxDetails.appendChild(objCaption);
	
	// create keyboard message
	var objKeyboardMsg = document.createElement("div");
	objKeyboardMsg.setAttribute('id','keyboardMsg');
	objKeyboardMsg.innerHTML = 'press <a href="#" onclick="hideLightbox(); return false;"><kbd>x</kbd></a> to close';
	objLightboxDetails.appendChild(objKeyboardMsg);


}

//
//addLoadEvent()
//Adds event to window.onload without overwriting currently assigned onload functions.
//Function found at Simon Willison's weblog - http://simon.incutio.com/
//
function addLoadEvent(func)
{	
	var oldonload = window.onload;
	if (typeof window.onload != 'function'){
		window.onload = func;
	} else {
		window.onload = function(){
		oldonload();
		func();
		}
	}

}
function setWebRoot(root){
	webRoot = root;
	loadingImage = webRoot+"/"+loadingImage;
	closeButton = webRoot+"/"+closeButton;
}


/*---------------------------------------------
 * former winnowing.js section
 * 
 */
var win1, win2, win3, win4;

var isholdingCTRL =false;
var winnowingChanged = false;
var stopSubmit = false;

window.onload = init;

document.onkeydown = function(e) 
{              
      
    if (!e) { e = window.event; }   
    //alert("e.keyCode: " + e.keyCode);  
    var k = e.keyCode;                  
    if ( k == 17 ) 
    {                     
        isholdingCTRL = true;
        //alert(isholdingCTRL);
        return false;                 
    }  
    else if ( k == 16 ) 
    {                     
        isholdingCTRL = true;
        return false;                 
    }        
      
}
    
document.onkeyup = function(e) 
{                     
    if (!e) { e = window.event; }                   
    var k = e.keyCode;                 
    if ( k == 17 ) 
    {          
        isholdingCTRL = false; 
        
        if (winnowingChanged)
        {
            winnowingChanged = false;           
            doSubmit();                            
        }
        
        return false;                 
    }     
    else if ( k == 16 )    
    {          
        isholdingCTRL = false;         
        if (winnowingChanged)
        {
            winnowingChanged = false;           
            doSubmit();                            
        }
        
        return false;                 
    }     
              
}
    

function addEventHandler(obj)
{       
  if (obj != null)
  {
      if( obj.addEventListener ) 
      {     
        //alert('obj.addEventListener');
        obj.addEventListener('click',OnClick,false);
      } 
      else if ( obj.attachEvent ) 
      {       
        //alert('obj.attachEvent');     
        obj.attachEvent("onclick", OnClick);
      }
      else 
      {   
        //alert('else...');      
        obj.onclick = OnClick;
      }
  }
}

function init() {      
	var winForm = getElement("winnowingForm");
	if (winForm != null)
	{
	    var FormElements = getFormFields(winForm,'select');
    	
    	if (FormElements != null)
    	{
	        for (var i=0;i<FormElements.length;i++)
	        {	   	    
	            //addEventHandler(FormElements[i]);
	        }
	    }
	}	
}

function OnClick(e) { 
  if (isholdingCTRL)
  {    
    window.status='CTRL is pressed. We halt submitting...';
    winnowingChanged = true;      
  } 
  else
  { 
    window.status='We submit...'; 
    
    if (winnowingChanged)
    {
        winnowingChanged = false;        
    }

  }
  return false;  
}

function doSubmit() {   

    if (!isholdingCTRL && !stopSubmit)
    {
        stopSubmit = true;
        document.getElementById('winnowingForm').submit();
    }
    return false;   
}

/*---------------------------------------------
 * former swfobject.js section
 * 
 *	SWFObject v2.2 <http://code.google.com/p/swfobject/> 
 *  is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r)try{n.a
ddRule(ac,Y)}catch(e){}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();
      
/*---------------------------------------------
 * former searchresult.js section
 */
  
/**
 * Apply a custom range filter to the search result.
 */
function customRangeFilter(anAnchor, groupId){

	//alert("groupId:" + groupId);
	var condition = document.getElementById('group_' + groupId + '_condition').value;
	var filterURL = document.getElementById('group_' + groupId + '_filterURL').value;
	var numberFrom = document.getElementById('numberFrom_group_' + groupId).value;
	var numberTo = document.getElementById('numberTo_group_' + groupId).value;
	
	//alert("filterURL:" + filterURL);	
	
	var selectedValue = "";
	if(numberFrom && numberTo){
		if(numberFrom == numberTo)
			selectedValue = numberFrom;
		else
			selectedValue = numberFrom + ' - ' + numberTo;
	}
	else if(numberFrom)
		selectedValue = '> ' + numberFrom;
	else if(numberTo)
		selectedValue = '< ' + numberTo;
	
	//alert("selectedValue:" + selectedValue);
	
	var newCondition = encodeURIComponent("&") + escape(encodeURIComponent(groupId)) + encodeURIComponent("=");
	
	//alert('condition.lenght :' + condition.length);
	
	if(condition.length > 0)
		newCondition += encodeURIComponent(condition + "_or_" + selectedValue);
	else
		newCondition += encodeURIComponent(selectedValue); 
			
	//alert('newCondition:' + newCondition);
	
	var href = filterURL + newCondition;
	
	//alert("href:" + href);	
	
	anAnchor.href = href;
}


function makeSearchResultSorting(orderBy){
	document.getElementById("SortingAttribute").value=orderBy;
	document.getElementById('SearchForm').submit();
}


/*--------------------------------------------- 
 * former sld_pmc/uitl.js section
 *
 * Used for suggestion box
 */
//helper to leverage the browser-differences of the behaviour
//(concerning the fired events) of an iframe
function setOnLoadWrapper(frame, func) {
this.ieIframeLoadWrapper = function(frame,func){
 if(frame.readyState == "complete"){
   func();
 }
}
if (isIe()==true)
 // ie fires onreadystatechange of the iframe
 // if it's source is changed programtically
 // the wrapper is necessary to correctly handle
 // the iframe's readyState attribute during loading
 frame.onreadystatechange=new ContextFixer(
   this.ieIframeLoadWrapper,this,frame,func).execute;
else
 // moz saimply fires onload...
 frame.onload=func;
}

//removed the stuff set by setOnLoadWrapper()
function removeOnLoadWrapper(frame){
if (isIe()){
 frame.onreadystatechange=null;
}else{
 frame.onload=null;
}
}

//get the function set by setOnloadWrapper
function getOnLoadWrapper(frame) {
if (isIe()){
 return frame.onreadystatechange;
}else{
return frame.onload;
}
	
}

//helper to determine whether the browser is ie
function isIe( ){
return (document.getElementById && document.all && document.styleSheets) ? 1:0;
}

//determines IE version (http://msdn2.microsoft.com/en-us/library/ms537509.aspx)
//Returns the version of Internet Explorer or a -1 (indicating the use of another browser).
function getIeVersion(){
var result = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer') {
 var ua = navigator.userAgent;
 var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
 if (re.exec(ua) != null)
   result = parseFloat( RegExp.$1 );
}
return result;
}

//helper to determine whether the browser is nn
function isNn() {
return (document.getElementById && !document.all) ? 1:0;
}

//get the elements computed/current style value (see limitations: http://erik.eae.net/archives/2007/07/27/18.54.15/)
function getStyle(el, prop) {
	  if (document.defaultView && document.defaultView.getComputedStyle) {
	    return document.defaultView.getComputedStyle(el, null)[prop];
	  } else if (el.currentStyle) {
	    return el.currentStyle[prop];
	  } else {
	    return el.style[prop];
	  }
	}

//helper to get an XMLHttpRequest instance
getXmlHttpRequest = function(){
if (window.XMLHttpRequest && window.DOMParser &&
     document.implementation && document.implementation.createDocument) {
         this.request = new XMLHttpRequest();
         return this.request;
 }
 try {
     this.request = new ActiveXObject("MSXML2.XmlHttp");
     return this.request;
 } catch (e) {}
 try {
     this.request = new ActiveXObject("Microsoft.XmlHttp");
     return this.request;
 } catch (e) {}
 try {
     this.request = new ActiveXObject("MSXML.XmlHttp");
     return this.request;
 } catch (e) {}
 try {
     this.request = new ActiveXObject("MSXML3.XmlHttp");
     return this.request;
 } catch (e) {}
}

//wrapper class for eventhandlers, ensures that "this" points
//to the instance the handler is a member of and not to "window
function ContextFixer(func, context) {
 /* Make sure 'this' inside a method points to its class */
 this.func = func;
 this.context = context;
 this.args = arguments;
 var self = this;
 this.execute = function() {
     /* execute the method */
     var args = new Array();
     // the first arguments will be the extra ones of the class
     for (var i=0; i < self.args.length - 2; i++)
         args.push(self.args[i + 2]);
     // the last are the ones passed on to the execute method
     for (var i=0; i < arguments.length; i++) 
         args.push(arguments[i]);
     self.func.apply(self.context, args);
 };
}


function UrlParameters(urlString)
{
	this.parameters = new Object();

	if (!urlString || urlString == '')
	{
		return;
	}

	var urlValue = decodeURI(urlString);
	var queryValue = "";
	
	if (urlValue.indexOf("?") >= 0)
	{
		queryValue = urlValue.substring(urlValue.indexOf("?") + 1, urlValue.length);
	}
		
	var keyValuePairs = queryValue.split("&");
	
	for (var i = 0; i < keyValuePairs.length; ++i)
	{
		var ar = keyValuePairs[i].split("=");
		this.parameters[ar[0]] = ar[1];
	}
	
	this.toString = function()
	{
		var tmp = new Array();
		
		for (var key in this.parameters)
		{
			tmp.push(key + "=" + this.parameters[key]);
		}	
		
		return "?" + encodeURI(tmp.join("&"));
	}
	
	this.get = function(parameterName)
	{
		return this.parameters[parameterName];
	}
	
	this.contains = function(parameterName)
	{
		return this.parameters[parameterName] != null;
	}
	
	this.put = function(parameterName, parameterValue)
	{
		this.parameters[parameterName] = parameterValue;
	}
}


/*
 * Search Suggest Box
 *
 * a box that 
 * assumes a XML http request that returns a xml document
<root>
 <headerText>Suggestions for your search...</headerText>  
 <query type="brand" typeName="Manufacturer" >Suggest Query Term 1</query>
 <query type="name" typeName="Product Name" >Suggest Query Term 2</query>
</root>
 *
 * uses the util.js from bc_pmc for getXMLHttpRequest
 */
var rowCounter=0;

function SuggestBox() {
    var pRequest; // xml http request
    var pDiv; //the div for suggestbox layer
    var pDivIFrame; //an additional div for iframe trick (to be layed before IE input elements ) 
    var pDebug = false; 
    var pInstanceName = ""; //instance name of this object
    var pSearchURL = ""; // the url to retrieve suggests, including query parameter name
    var pQueryParamName = ""; // the query parameter for the query term
    var pFormname = ""; //form name to submit a query
    var pDivName = ""; //the divs layer id
    var pQueryInput; //the user entered query term
    var pSuggest = new Array; //contains suggest query and type for submitting the result 
    var pLastQuery; //remember the last query term from the input
    var pCurrentSelection = -1; // suggest query term selection
    var pCloseWindowMsg = "";
    var pDivLogo = "";//the x coordination will be correspondent to the Logo 'x' coordination

    var submitted = false;

	//holds html code built from httprequest response
	var responseTextStart  = ''; 
    var responseTextHeader = '';  
    var responseTextRow    = '';
    var responseTextEnd    = '';
    
    this.init = function (searchURL, formname, queryParamName, divName, instanceName, closeMsg, divLogo, debugMode) {

    	pSearchURL = searchURL;
    	pFormname = formname;
    	pQueryParamName = queryParamName;
    	pDivName = divName;
    	pDiv = document.getElementById(divName);
    	pDivIFrame =  document.getElementById(divName + "IFrame"); 
    	pInstanceName = instanceName;
    	pDebug = false;
    	pQueryInput = document[pFormname][pQueryParamName];
    	pCloseWindowMsg = closeMsg;
    	pDivLogo=divLogo;
    	
    	if (pSearchURL == "") {
    		if (pDebug) {alert("no searchurl defined");} return null;
    	} 
    	else if (pInstanceName == "") {
    		if (pDebug) {alert("no instancename defined");}	return null;
    	} 
    	else if (pFormname == "") {
    		if (pDebug) { alert("no formname defined"); }return null;
    	} 
    	else if (pQueryParamName == "") {
    		if (pDebug) {alert("no queryparamname defined");} return null;
    	}
    	else if (pDiv == null) {
    		if (pDebug) {alert("need a div for output");}
    	}

	    //initalize the html used to display inside the suggestBox div
	    //contains placeholders replaced from handleResponse()
    	//onMouseDown="' + pInstanceName + '.handleClick();"
    	responseTextStart = '<div class="level2Menu level2Menu-top suggestMenu" onMouseDown="' + pInstanceName + '.handleClick();">';
    	responseTextStart +=	'<div class="level2Menu-bottom"></div>';
    	responseTextStart +=	'<div class="level2Menu-content">';
    	responseTextStart +=		'<div class="level2Menu-left">';
    	responseTextStart +=			'<div class="level2Menu-top-left"></div>';
    	responseTextStart +=			'<div class="level2Menu-bottom-left"></div>';
    	responseTextStart +=		'</div>';
    	responseTextStart +=		'<div class="level2Menu-right">';
    	responseTextStart +=			'<div class="level2Menu-top-right"></div>';
    	responseTextStart +=			'<div class="level2Menu-bottom-right"></div>';
    	responseTextStart +=		'</div>';
    	responseTextStart +=		'<div class="level2Menu-innerContent">';
				
    	responseTextEnd =			'</div>';
    	responseTextEnd +=		'</div>';
    	responseTextEnd += '</div>';
    	
        /* #2841 hidden exact hit count
	    responseTextRow = '<div class="suggestRow @borderClass@" id="suggestBox_@count@" onMouseOver="' + pInstanceName + '.handleMouseOver(@count@);" onMouseOut="' + pInstanceName + '.handleMouseOut(@count@);"><table width="100%" border="0" cellpadding="0" cellspacing="0" ><tr><td class="image"><img class="image" src="@SuggestImage@"></td><td class="suggest"><span class="suggest"><span class="suggestRowSpace">@SuggestQuery@</span></span></td><td class="suggestCount"><span class="suggestType"><span class="suggestRowSpace">@SuggestType@</span></span></td><td class="suggestCount"><span class="suggestType suggestCount"><span class="suggestRowSpace">@SuggestCountText@</span></span></td></tr></table></div>';
        */
        responseTextRow = '<div class="suggestRow @borderClass@" id="suggestBox_@count@" onMouseOver="' + pInstanceName + '.handleMouseOver(@count@);" onMouseOut="' + pInstanceName + '.handleMouseOut(@count@);"><table width="100%" border="0" cellpadding="0" cellspacing="0" ><tr><td class="image"><img class="image" src="@SuggestImage@"></td><td class="suggest"><span class="suggest"><span class="suggestRowSpace">@SuggestQuery@</span></span></td><td class="suggestCount"><span class="suggestType"><span class="suggestRowSpace">@SuggestType@</span></span></td></tr></table></div>';
         
        //responseTextEnd    = '<td class="level2Menu-right"></td></div></td></tr><tr><td class="level2Menu-bottom-left"></td><td class="level2Menu-bottom" align="center"><span class="allResults"><a id="searchAllLink" href="#">'+pCloseWindowMsg+'</a></span></td><td class="level2Menu-bottom-right"></td></tr></table>' 
        	
    	//get query input field and set handlers
    	pQueryInput.onkeyup = handleKeyPress;
    	pQueryInput.onfocus = showLayer;
    	pQueryInput.onchange = hideLayer;
    	pQueryInput.setAttribute('autocomplete', 'off');
    	document[pFormname].onsubmit = handleSubmit;
    	
    };
    
    this.handleClick = function () {
        //todo handle the types like brand
    		
    	if (pSuggest[pCurrentSelection]) {
    		setSearchTermFromSelection(pSuggest[pCurrentSelection]); 
    	}
    	if (pSuggest[pCurrentSelection]||pQueryInput.value) {
    		var myform = document.getElementById(pFormname);
    		myform.submit();
    	}
    };

    this.handleMouseOver = function (pos) {
    	var selEl = getRow(pos);
    	deselect();
    	if (selEl != null) {
    		highlight(selEl);
    		pCurrentSelection = pos;
    	}
    };

    this.handleMouseOut = function (pos) {
    	var selEl = getRow(pos);
    	if (selEl != null) {
    		deselect(selEl);
    		pCurrentSelection = -1;
    	}
    };
    
    function handleSubmit() {
        submitted = true;
        //todo handle the types like brand
        if (pSuggest[pCurrentSelection] != undefined) {
        	setSearchTermFromSelection(pSuggest[pCurrentSelection]); 
        }
    }; 
    
    function setSearchTermFromSelection(currentSelection) {
    	var suggestType = currentSelection[1];
    		document.getElementById(pQueryParamName).value = currentSelection[0];
    }

    function handleKeyPress(evt) {
        evt = evt ? evt : event ? event : null;
        var keyCode = evt.keyCode;
        if (keyCode == 38) {
            moveSelection("up");
        } else if (keyCode == 27) {
            hideLayer();
        } else if (keyCode == 40) {
            moveSelection("down");
        } else {
            var query = pQueryInput.value
            if (pQueryInput.value == "") 
            {
                hideLayer();
                return null;
            }
            if (pLastQuery != query) 
            {
                startAjaxRequest(query);
            }
            pLastQuery = query;
        }
    }; 

    function moveSelection(direction) {
        var pos = pCurrentSelection;
        if (direction == "up") {
            pos--;
        } else {
            pos += 1;
        }
        if (pos < 0) {
            deselect();
            pQueryInput.focus();
            pCurrentSelection = -1;
        } else {
            var selEl = getRow(pos);
            if (selEl != null) {
                deselect();
                highlight(selEl);
                pCurrentSelection = pos;
            }
        }
        var query = pQueryInput.value;
        pQueryInput.value = "";
        pQueryInput.focus();
        pQueryInput.value = query;
    };

    function startAjaxRequest(query) {
        
        var requestURL = pSearchURL + encodeURIComponent(query);
        
      	pRequest = getXmlHttpRequest();
        pRequest.open("GET", requestURL, true);
        pRequest.onreadystatechange = callbackAjaxRequest;
        pRequest.send(null);
        
    };
    
    this.hideLayerOutsideCall = function () {
        hideLayer();
    };

    function hideLayer() {
        if (pDiv != null) {pDiv.style.display = "none"; }
        if(pDivIFrame != null)
        {
        	pDivIFrame.style.left = "-2000px";
        }
    };

    function showLayer() {
        if (pDiv != null && pSuggest != null && pSuggest.length >= 1) {
        	var pos = $('.frame').position();
	     	pDiv.style.display = "block";
	     	$("#suggestBox").css("top", pos.top);
	     	$("#suggestBox").css("left", pos.left);
	     	$("#suggestBox .level2Menu").css({"top": "0", "margin-top":"0","left":"0"});
	     	$("#suggestBox .level2Menu").show();
        }
    };

    function callbackAjaxRequest() {
        if (submitted == false) {
            if (pRequest.readyState == 4) {
                if ((pRequest.status != 200) || (pRequest.responseXML == null)) {
                    hideLayer();
                    if (pDebug) {
                        alert("Error (" + pRequest.status + "): " + pRequest.statusText + " response: " + pRequest.responseText);
                    }
                } else {
                    handleResponseXML(pRequest.responseXML);
                }
            }
        }
    };

    function fireSuggestCompleted(suggestBoxIsVisible) {
        if (typeof onSuggestCompleted == "function") {
            onSuggestCompleted(suggestBoxIsVisible);
        }
    };
    
    function handleResponseXML(responseDocument) {
        pCurrentSelection = -1;
         
        var i = 0;
        var element;

        var responseText = responseTextStart;  
        var headerTextNode = responseDocument.getElementsByTagName("headerText")[0];
        if(headerTextNode != null && headerTextNode.firstChild != null && headerTextNode.firstChild.data)
        {
        	responseText += responseTextHeader.replace("@HeaderText@", headerTextNode.firstChild.data); 
        }
        
        //get the query parts
        var queries = responseDocument.getElementsByTagName("query");
        pSuggest = new Array;
        var rowCounter=0;        
        
        for(i=0;i<queries.length; i++)
        {
        	pSuggestParts = new Array;
        	suggestQuery = queries[i].firstChild.data;
        	if(suggestQuery != null)
        	{
	        	pSuggestParts[0] = suggestQuery;
	        		        	
    	    	var typeName = translateType(queries[i].getAttribute("type"));
    	    	pSuggestParts[1] = typeName;
    	    	pSuggest[i] = pSuggestParts;
    	    	    	    	
    	    	var highlightedQueryTerm=suggestQuery;
    	    	highlightedQueryTerm = highlightedQueryTerm.replace(new RegExp("(" + pQueryInput.value + ")", "ig"), '<span class="suggestContent">$1</span>');
    	    	var responseTextRowReplaced = responseTextRow.replace(/@count@/g, i);
    	    	responseTextRowReplaced = responseTextRowReplaced.replace("@SuggestQuery@", highlightedQueryTerm); 
    	    	responseTextRowReplaced = responseTextRowReplaced.replace("@SuggestType@", typeName);

    	    	rowCounter++;
    	    	if(rowCounter>1){
    	    		responseTextRowReplaced = responseTextRowReplaced.replace("@borderClass@", 'rowBorder');
    	    	}
    	    	
    	    	var countText = queries[i].getAttribute("countText");
    	    	if(countText != null)
    	    	{
        	    	responseTextRowReplaced = responseTextRowReplaced.replace("@SuggestCountText@", "("+countText+")");
    	    	}
    	    	else
    	    	{
        	    	responseTextRowReplaced = responseTextRowReplaced.replace("@SuggestCountText@", "");
    	    	}
    	    	var imageURL = queries[i].getAttribute("imageURL");   	    	
    	    	if(imageURL != null && imageURL != "")
    	    	{
        	        responseTextRowReplaced = responseTextRowReplaced.replace("@SuggestImage@", imageURL);
    	    	}
    	    	else
    	    	{
        	        responseTextRowReplaced = responseTextRowReplaced.replace("@SuggestImage@", "");
    	    	}

    	    	
    	    	responseText += responseTextRowReplaced; 
        	}
        }
        responseText += responseTextEnd;
          
        if (pSuggest.length >= 1) {
        	//setXPosition();
            pDiv.innerHTML = responseText;
            showLayer();
            fireSuggestCompleted(true);
        } else {
            hideLayer();
            pDiv.innerHTML = "";
            fireSuggestCompleted(false);
        }
                
    };

    function highlight(selEl) {
    	var rowClassName=selEl.className;
    	if(rowClassName.indexOf("rowBorder")==-1){
    		selEl.className="suggestRow suggestHighlight";
    	}
    	else{
    		selEl.className="suggestRow suggestHighlight rowBorder";
    	}
    };

    /* deselects an element
       or all if null element is passed  
    */
    function deselect(selEl) {
    	var rowClassName="";
    	if(selEl != null) {
    		rowClassName=selEl.className;
    		if(rowClassName.indexOf("rowBorder")==-1){
    			selEl.className="suggestRow";	
    		}
    		else{
    			selEl.className="suggestRow rowBorder";	
    		}
    	}
    	else {
	        for (var i in pSuggest) {
	            selEl = getRow(i);
	            if (selEl != null) {
	            	rowClassName=selEl.className;
	            	if(rowClassName.indexOf("rowBorder")==-1){
	            		selEl.className="suggestRow";
	            	}
	            	else{
	            		selEl.className="suggestRow rowBorder";	
	            	}
	            }
	        }
    	}
    };

    function getRow(pos) {
        var selEl;
        selEl = document.getElementById(pDivName + "_" + pos);
        return selEl;
    };

    function setXPosition(){
    	var targetObj = document.getElementById(pDivName);
    	var logoObj = document.getElementById(pDivLogo);
    	var posX=0,posY=0;
    	//alert(pDivLogo+", "+logoObj);
    	if( typeof( logoObj.offsetParent ) != 'undefined' ) {
    		for( var posX = 0, posY = 0; logoObj; logoObj = logoObj.offsetParent ) {
    			posX += logoObj.offsetLeft;
    			posY += logoObj.offsetTop;
    		}
    	}		
    	targetObj.style.left = (parseInt(posX)+parseInt(getMarginLeftSAYT()))+"px";
    	targetObj.style.top = (parseInt(posY)+parseInt(getMarginTopSAYT()))+"px";
    	targetObj.style.width = parseInt(getWidthSAYT())+"px";
    };

};

function testAlerter(){
	alert("yeeeees!");	
}

/* initalize the suggest box */
function initSuggestBox(){
	if ($("#WFSimpleSearch_NameOrID").length <= 0) return;
	eval("var selfParams = " + $("#WFSimpleSearch_NameOrID").attr("alt") );
	window.suggestBox	 = new SuggestBox();
	var divName          = "suggestBox";  
	var formname		 = "SimSearch";  
	var queryParamName	 = "WFSimpleSearch_NameOrID";
	var instanceName	 = "suggestBox";
	var divLogo 		 = "chLogo";
	window.suggestBox.init(selfParams.url, formname, queryParamName, divName, instanceName, selfParams.msg, divLogo);
	$("#WFSimpleSearch_NameOrID").blur(window.suggestBox.hideLayerOutsideCall);
}


function translateType(type) {
	if(type=='category'){
		translatedType=document.getElementById("suggestCategoryType").innerHTML;
    }
	else if(type=='brand'){
		translatedType=document.getElementById("suggestBrandType").innerHTML;
	}
	//Strangely it whats enfinity sends for product hits
	else if(type=='unspecified'){
		translatedType=document.getElementById("suggestProductType").innerHTML;
	}
	else if(type=='content'){
		translatedType=document.getElementById("suggestContentType").innerHTML;
	}
	else if(type=='store'){
		translatedType=document.getElementById("storeContentType").innerHTML;
	}

	
	return translatedType;
}


function getStyleElement(el,styleProp) {
    el = document.getElementById(el);
    var result;
    if(!ifOpera()&&el.currentStyle) {
        result = el.currentStyle[styleProp];
        //document.title += ('current-style='+styleProp+",result="+result);
    } else if (window.getComputedStyle) {
        result = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
        //document.title += ('computed-style='+styleProp+",result="+result);
    } else {
        result = '0';
    }
    if(result!=null&&result.length >0&&result.indexOf('px')>0){
    	result= result.substring(0,result.indexOf('px'));
        //document.title += ('px-style='+styleProp+",result="+result);
    }
    return result;
}

function getMarginTopSAYT() {
	var result =getStyleElement("menuPosition","margin-top");
	if(result==undefined)
		result =getStyleElement("menuPosition","top");
    return result;
}
function getMarginLeftSAYT() {
	var result = getStyleElement("menuPosition","margin-left");
	if(result==undefined)
		result =getStyleElement("menuPosition","left");
    return result;
}
function getWidthSAYT() {
    return getStyleElement("menuPosition","width");
}

/*
 * END OF Search Suggest Box
 */

/*** FAQ ****/
function visibleQA(id){
	var objById = document.getElementById(id);
	if(objById != undefined){
		if(objById.style.display=='none'){
			objById.style.display='block';
		}else{
			objById.style.display='none';
		}
		var liObj = document.getElementById('LI_'+id);
		if(liObj != undefined){
			if(objById.style.display=='none'){
				liObj.className=liObj.className.replace('active','');
			}else{
				liObj.className=liObj.className+" active";
			}
		}
	}
}
function foldAllQuestions(form){
	var uuid = form.FAQ_PAGELETUUID;
	if(uuid!=undefined &&uuid.length>2){
		for(var i=2;uuid.length>i;i++){
			visibleQA(uuid[i].value);
		}
	}
}
/*** END:FAQ ***/


/*** Customer Review ***/
function showCustomerReview(){
	scrollingToObj('tProductTabcontent');
	enableTab('RatingBV','');
}

function initFlyoutMenu(){
	if($(".menuAsDropdown, .menu_hidden, .left_hidden").length > 0){
		$("#depMenuId").hover(
			function(){ $("#cnCategory, #menuShadow, #notFixedLevel1Bottom, .category-b").css("display", "block");$("#menuShadow").css("height", parseInt($("#cnCategory").height())+'px');},
			function(){ $(".level2Menu").css("display", "none"); $("#cnCategory, #menuShadow, #notFixedLevel1Bottom, .category-b").css("display", "none"); }
		);
	}
	$("#level1 > li").each(function(){
		var menuItem = $(this);
		this.containerObj = $(this).parent();
		menuItem.hover(function(){
			var self = this;
			var cObj = this.containerObj;
			if (cObj.timer) { clearTimeout( cObj.timer ) }
			cObj.timer = setTimeout( function(){ $(".level2Menu", self).show(); }, 200);
		},
		function(){
			var self = this;
			var cObj = this.containerObj;
			if (cObj.timer) { clearTimeout( cObj.timer ) }
			cObj.timer = setTimeout(function(){ $(".level2Menu", self).hide(); }, 200);
		})
	});
}

function getTargetObj(e) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	return targ;
}

/*** BigBang - Onclick ***/
var bigbangFlg = true;
function BigbangOnclick(urllink,newwindow){
	document.body.className="bigbang-active";
	document.getElementById("allContent").onclick = function(e){
		targetObj = getTargetObj(e);
		if(targetObj.id=="body_wrapper"){ bbGo2URL(urllink,newwindow) }
	};
}


function bbGo2URL(urllink,newwindow){
	if(bigbangFlg){
		if(newwindow=='true'){
			window.open(urllink);
		}else{
			go2URL(urllink);
		}
	}
	bigbangFlg = true;
}
/*** Featured Promotions ****/
function manageFeaturePromotion(cnt,minCnt){
	if(parseInt(cnt)<parseInt(minCnt)){
		var obj = document.getElementById("cnPromotions");
		if(obj!=undefined){
			obj.innerHTML = "";
			obj.style.display = "none";
		}
	}
}
/*** Store-Locator: Google Maps ***/
var map;
var gdir;
var storeId;
var selectedStore;
var storeAddress;
var fromAddress;
var fromAddParam;
var fromAddressLatLng;
var toAddress;
var addressSearchPoint;
var currentGLatLng;
var farestStoreDistance=0;
var geoCodeGlobal='';
var latitudeCenterAt;
var longitudeCenterAt;
var dirn;
var html = "";
var iconWidth='', iconHeight='',iconStoreImage='';
var browserSupportFlag;//the flag whether the browser supports the GeoLocation or not.
var initialLocation;
var strCountryCode;
var addressOptions;
var addressOptionsInfo;
var initAddressId='address';
var directionsDisplay;
var directionsService
var infowindow;
function Store() {
}
function showStoresMap()
{
	initialisingStoreIcon();
	setMapResultElement(storesMapDiv, mapWidth, mapHeight);
	browserSupportFlag =  new Boolean();
	map;
	infowindow = new google.maps.InfoWindow();
	var myOptions = {
			zoom: 6,
			mapTypeId: google.maps.MapTypeId.ROADMAP
	};
	map = new google.maps.Map(document.getElementById(storesMapDiv), myOptions);
	
	var tab1Header = ADDRESS_TEXT;
    var tab1Contents = fromAddress;
	// If we have a store passed in, try to find the store and use its coordinates as the center of the map
	if (storeId != null&&storeId!=undefined&&storeId!='') {
		selectedStore = findStoreById(storeId);
		if (selectedStore != null){ 
			mapPoint = new google.maps.LatLng(selectedStore.latitude, selectedStore.longitude);intZoomLevel=15;
		}else{
		    mapPoint =  new google.maps.LatLng(parseFloat(latitudeCenterAt),parseFloat(longitudeCenterAt));
		}
		map.setCenter(mapPoint);
	}else if(fromAddress==''||fromAddress.replace(' ','')==''){			
	 	//first time landing to the pager --> Try W3C Geolocation (Preferred)
		if(navigator.geolocation) {
			browserSupportFlag = true;
		    navigator.geolocation.getCurrentPosition(
		    		function(position) {
		    			initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
		    			map.setCenter(initialLocation);
		    		}, 
		    		function() {});
		  // Try Google Gears Geolocation
		}else if (google.gears) {
			browserSupportFlag = true;
		    var geo = google.gears.factory.create('beta.geolocation');
		    geo.getCurrentPosition(
		    		function(position) {
		    			initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
		    			map.setCenter(initialLocation);
		    		}, 
		    		function() {});
		// Browser doesn't support Geolocation
		} else {
		}
	 	getPointByAddress(stores[0].country,strCountryCode,'setCenterPointByAddress');
	}	 
	showStores(stores);
	
    if (intZoomLevel == null) 
    	intZoomLevel = 7;
	
    map.setZoom(intZoomLevel);
	resetHeightDirectionMap();
}
function findStoreById(storeId) {
	for (var i = 0; i < stores.length; i++)
	{
		if (stores[i].id == storeId)
		{
			return stores[i];
		}
	}
	return null;
}
function resetHeightDirectionMap(){
	var mapDiv = document.getElementById(directionsMapDiv);
	if(mapDiv){
		mapDiv.innerHTML =''; 
	}
	setTimeout('defaultCenterByStore()',100);
}
function clickShowStoreInfo(storeId){
	var selectedStore = findStoreById(storeId);
	if(parseInt(intZoomLevel)<11)
		intZoomLevel=11;
	showBubbleWindow(selectedStore.order);
}
function defaultCenterByStore(){
	if(storeId!=''&&selectedStore!=undefined){
		showBubbleWindow(selectedStore.order);
	}
	else if(fromAddress!=undefined && fromAddress.replace(' ','')!=''){

	    map.setCenter(currentGLatLng,7);
        marker = new google.maps.Marker({
           position: currentGLatLng, 
           map: map
        }); 
        marker.setTitle(YOUR_ADDRESS_HERE_TEXT);
        loadNewInfoWindow();
        infowindow.setContent(YOUR_ADDRESS_HERE_TEXT);
        infowindow.open(map, marker);
        setMapZoomBasedOnDistance(farestStoreDistance);
	}
}
function loadNewInfoWindow(){
	if(infowindow!=undefined)
		infowindow.close();
	infowindow = new google.maps.InfoWindow();
	
}
function setMapZoomBasedOnDistance(distance){
    if(parseInt(distance) < 1000){ //1km
    	intZoomLevel=14;
    }else if(parseInt(distance) < 2000){ //2km
    	intZoomLevel=13;
    }else if(parseInt(distance) < 5000){ //5km
    	intZoomLevel=12;
    }else if(parseInt(distance) < 10000){ //10km
    	intZoomLevel=11;
    }else if(parseInt(distance) < 20000){ //20km
    	intZoomLevel=10;
    }else{
    	intZoomLevel=7;//default
    }
	map.setZoom(intZoomLevel);
}
function showMapTabsInfo(order){
    if (order != null&&stores[order].marker!=undefined) {
        // Open an info window indicating the elevation at the clicked position
    	loadNewInfoWindow();
    	
		infowindow.setContent(stores[order].infoTabs);
        infowindow.set("isdomready", false);
        infowindow.open(map, stores[order].marker);
        
        // On Dom Ready
        google.maps.event.addListener(infowindow, 'domready', 
	        function () {
	            if (infowindow.get("isdomready")) { 
	            	if(document.getElementById("hidingSpaceInfoWindow")!=undefined){
	            		document.getElementById("hidingSpaceInfoWindow").style.display='none';
	            	}
	            } else {
	                // trigger a domready event again.
	                google.maps.event.trigger(infowindow, 'content_changed');
	                infowindow.set("isdomready", true);
	            }
	        });
    }
}
function showBubbleWindow(order)
{
    if (order != null&&stores[order].marker!=undefined) {
    	map.setZoom(intZoomLevel);
    	showMapTabsInfo(order);
    }
}
function getIconWidth(){
	if(iconWidth==''){
		initialisingStoreIcon();
	}
	return iconWidth;
}
function getIconHieght(){
	if(iconHeight==''){
		initialisingStoreIcon();
	}
	return iconHeight;
}
function getStoreIcon(){
	var iconStoreImage = document.getElementById("storeIconImage").src;
	
	return iconStoreImage;
}
function initialisingStoreIcon(){   

    var img = document.getElementById("storeIconImage");   
    iconHeight = img.clientHeight;
    iconWidth = img.clientWidth;
    img.style.display='none';
}
function showStores(storeArray)
{
    for (var i = 0; i < storeArray.length; i++)
    {
    	var store = storeArray[i];		    
        marker = getMarker(store);
        storeArray[i].marker = marker;
    }
}
function getMarker(store)
{	
    var curHeight = getIconHieght();
    var curWidth = getIconWidth();	 
	var icon = new google.maps.MarkerImage();  
	icon.url = getStoreIcon(); 
	icon.size = new google.maps.Size(parseInt(curWidth), parseInt(curHeight));
	icon.anchor = new google.maps.Point(parseInt(curWidth)/2, parseInt(curHeight));
    
    var tab1Header = ADDRESS_TEXT;
    var strAddressText = ''
    if(store.image!=''){
        strAddressText += '<div class="store-image">' + store.image + '</div>'
    }
    strAddressText += '<b> ' + store.name + '</b><br>'
    strAddressText += store.address + '<br>';
    strAddressText += store.city + ', ';
    strAddressText += store.state + ' ';
    strAddressText += store.zip + '<br/>';
    strAddressText += '<br/><b>' + GET_DIRECTIONS_TEXT + ':<br/></b>';
    strAddressText += '<div class="search-error" ><span id="searchFlayoutErrorTxt" style="display:none"></span></div>';
    
	if (fromAddress != null&&fromAddress!=''){
		strFromAddress = fromAddress;
	}
	else{
		strFromAddress = DRIVING_FROM_TEXT;
	}
    strAddressText += '<input type="text" id="address' + store.order + '" value="' + strFromAddress + '" onfocus="removeText(this,DRIVING_FROM_TEXT);" onclick="removeText(this,DRIVING_FROM_TEXT);" onblur="defaultTextPopup(this,DRIVING_FROM_TEXT);" onkeyup="if(event.keyCode==\'13\') {getDirections(\'' + store.id + '\', document.getElementById(\''+initAddressId + store.order + '\').value,\'\');}">';
    strAddressText += '<input type="button" value="' + GO_TEXT + '" class="store-direction" onclick="getDirections(\'' + store.id + '\', document.getElementById(\''+initAddressId + store.order + '\').value,\'\');">';
    
    var tab1Contents = strAddressText;

    var tab2Header = STORE_INFO_TEXT;
    var strStoreInfoText = '';
    if(store.image!=''){
    	strStoreInfoText += '<div class="store-image">' + store.image + '</div>'
    }
    strStoreInfoText += '<b>' + store.name + '</b><br>';
    if (store.phone != '')
    {
        strStoreInfoText += PHONE_TEXT + ': ' + store.phone + '<br>';
    }
		strStoreInfoText += HOURS_TEXT + ': ' + store.hours + '<br>';
		strStoreInfoText += '<center>';
		strStoreInfoText +='<br/><div class="button-box"><a class="submit btn-img" href="'+store.StoreLink+'" ><span>'+GO_TO_STORE_BUTTON_TEXT+'</span></a></div>';
    strStoreInfoText += '</center>';
    var tab2Contents = strStoreInfoText
    var contentString = [
	     '<div id="tabs" >',
	     '<ul class="tab-nav norrow-tab">',
	       '<li><a href="javascript:void(0);" onclick="enableTab(\'Address\',\'map\')" ><span id="AddressTab" class="active"><div class="tab-txt-box" ><div class="text">'+tab1Header+'</div></div></span></a></li>',
	       '<li><a href="javascript:void(0);" onclick="enableTab(\'Store\',\'map\')" ><span id="StoreTab" class=""><div class="tab-txt-box" ><div class="text">'+tab2Header+'</div></div></span></a></li>',
	     '</ul><br/>',
	     '<div id="AddressInfo" style="display:block">',
	       '<p>'+tab1Contents+'</p>',
	     '</div>',
	     '<div id="StoreInfo" style="display:none">',
	      '<p>'+tab2Contents+'</p>',
	     '</div>',
	     '</div>',
	     '<div id="hidingSpaceInfoWindow"><br/></div>'
	   ].join('');

	   store.infoTabs = contentString;
	   
	   var marker = new google.maps.Marker({icon:icon,map: map,position:new google.maps.LatLng(store.latitude, store.longitude)});
	 	
	   google.maps.event.addListener(marker, 'click', function() {
		   showMapTabsInfo(store.order);
	   });
    
    return marker;
}
function setMapResultElement(elementID, width, height)
{
    document.getElementById(elementID).style.width = width + "px";
		if (height != null){
			document.getElementById(elementID).style.height = height + "px";
		}
}

function showDirections()
{
    // the directions pane.
    setMapResultElement(directionsMapDiv, mapWidth, mapHeight);
    setMapResultElement(directionsTxtDiv, 300);
    
    fromAddParam = fromAddress;
    if(fromAddressLatLng!='')
    	fromAddParam = fromAddressLatLng;
    
    directionsService = new google.maps.DirectionsService();
    directionsDisplay = new google.maps.DirectionsRenderer();
    var myOptions = {
      zoom:intZoomLevel,
      mapTypeId: google.maps.MapTypeId.ROADMAP      
    }
    
    map = new google.maps.Map(document.getElementById(directionsMapDiv), myOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById(directionsTxtDiv));
    calcRoute(fromAddParam,toAddress,'DRIVING');
    simpleShow(travelModesDiv);
}
function changeTravelMode(mode){
	calcRoute(fromAddParam,toAddress,mode.value);
}
function calcRoute(start,end,mode) {
  var request = {
      origin:start, 
      destination:end,
      travelMode: google.maps.DirectionsTravelMode[mode]
  };
  directionsService.route(request, function(response, status) {
    if (status == google.maps.DirectionsStatus.OK) {
      directionsDisplay.setDirections(response);
    }
  });
}
var directionStoreId;
var directionAddress;
var directionLatLng;
function getDirections(storeid, address, latLng)
{	
	if(document.getElementById("searchFlayoutErrorTxt")!=undefined){
		simpleHide("searchFlayoutErrorTxt");
	}
	directionStoreId=storeid;
	directionAddress=address;
	directionLatLng=latLng;

	getPointByAddress(address,strCountryCode,'processDirections');
}
function defaultAddressPopupSearchTxt(index,id){
	if(document.getElementById(id)!=undefined)
		document.getElementById(id).value=addressOptions[index];
}
function processDirections(lat,long,regionFlg,retID)
{	
	if(lat!=undefined &&(""+lat).replace(' ','')!=''){			

		if(addressOptions!=undefined&&addressOptions.length>1){
			var store = findStoreById(directionStoreId);
			var addressFieldId = initAddressId+store.order;
			var addressBoxById = document.getElementById(addressFieldId);
			var optionsTxt = "<div class=\"stores-list\"  style='width:100%;padding-top:0;padding-left:0;'>";
			optionsTxt = optionsTxt + "<ul  style='padding-top:0;'>";
			optionsTxt = optionsTxt + "<li class=\"state-header\"><a style='white-space: nowrap;'> <span class=\"state-name\">"+ADDRESS_OPTIONS_TEXT+"</span></a></li>";
			for(var i=0;i<addressOptions.length;i++){
				optionsTxt = optionsTxt + "<li class=\"state-header\"><a href=\"javascript:void(0)\"  alt='"+addressOptionsInfo[i]+"' title='"+addressOptionsInfo[i]+"' onclick=\"closeCounty();defaultAddressPopupSearchTxt("+i+",'"+(initAddressId+store.order)+"')\" style=\"white-space: nowrap;\"> <span class=\"store-name\">"+addressOptions[i]+"</span></a></li>";
			}
			optionsTxt = optionsTxt + "</ul><\div>";
			if(addressBoxById!=undefined){
				var popupId = 'countyTableContent';
				var popupContentTxt= createFlyoutHTML(popupId,1,false,optionsTxt);
				createFlyoutPopupLayout("StoresMap",200,120,popupContentTxt,popupId);
			}
		}else{
			if(directionAddress!=''&&directionAddress.replace(' ','')!=''&&directionAddress!=DRIVING_FROM_TEXT)
		    	document.location.href = DIRECTIONS_LINK + '?StoreUUID=' + directionStoreId + '&Address=' + directionAddress+"&AddressLatLng="+directionLatLng;
		}
		
	}else{
		if(document.getElementById("searchFlayoutErrorTxt")!=undefined){
			simpleShow("searchFlayoutErrorTxt");
			document.getElementById("searchFlayoutErrorTxt").innerHTML=UNKNOWN_ADDRESS_ERROR_MESSAGE;
		}
	}
}

function setCenterByAddress(address) {
	var geocoder = getGeoCoder();
	geocoder.getLatLng(
	    address,
	    function(point) {
	      if (!point) {
	      } else {
			latitudeCenterAt = point.lat();
			longitudeCenterAt = point.lng();
	      }
	    }
	);
 }
function getPointByAddress(address,countryCode,retFunc,retID) {
	var geocoder = getGeoCoder();
	var searchAddress = address;
	if(searchAddress.replace(" "+strCountryCode,'')==searchAddress){
		searchAddress = address+" "+strCountryCode;
	}
	geocoder.geocode({"address":searchAddress,"language":strLanguageCode,"region":strCountryCode}	, /* if the user can use the dress from the country, the 'region' has to be applied*/
		function(results, status){
			var lat ='';
			var long='';	
			addressOptions = [];
			addressOptionsInfo = [];

			 if (status == google.maps.GeocoderStatus.OK) {		        
		        countryFlg = false;
			    place = results[0];
			    
			    if(countryCode!=undefined&&countryCode!=''&& results.length>0){
			    	for(var i=0;i<results.length;i++){
			    		var tmpAddress = "";
			    		var tmpAddressInfo="";
		    			for(var j=0;j<results[i].address_components.length;j++){
		    				if(tmpAddress.indexOf(results[i].address_components[j].long_name) <0){
		    					if(tmpAddress.length>0){
		    						tmpAddress+=", ";
		    						tmpAddressInfo +="\n"
		    					}
			    				tmpAddress+=results[i].address_components[j].long_name;
			    				var compType = "";
			    				var rType = results[i].address_components[j].types[0];
			    				if(rType!=undefined&&rType!=''){
				    				if(rType.indexOf("country")>=0){
				    					compType=COUNTRY_TEXT;
				    				}else if(rType.indexOf("area")>=0){
				    					compType=AREA_TEXT;
				    				}else if(rType.indexOf("locality")>=0){
				    					compType=LOCALITY_TEXT;
				    				}else if(rType.indexOf("postal")>=0){
				    					compType=POSTCODE_TEXT;
				    				}else if(rType.indexOf("route")>=0){
				    					compType=SEARCH_ADDRESS_TEXT;
				    				}	   	
				    				if(compType!=""){
			    						tmpAddressInfo += (compType+": "+results[i].address_components[j].long_name);
				    				}
			    				}
		    				}
		    				if(results[i].address_components[j]!=undefined
		    					&&results[i].address_components[j].types!=undefined
		    					&&results[i].address_components[j].types[0]=='country'){					    		
					    		if(!countryFlg&&results[i].address_components[j].short_name==countryCode){
					    			place = results[i];
					    			countryFlg=true;
					    		}
		    				}
		    			}
			    		addressOptions[addressOptions.length]=tmpAddress;
			    		addressOptionsInfo[addressOptionsInfo.length]=tmpAddressInfo;
			    	}
			    }
			    
			    lat = place.geometry.location.lat();
				long = place.geometry.location.lng();
				if(retID!=undefined)
					eval(retFunc)(lat,long,countryFlg,retID);
				else
					eval(retFunc)(lat,long,countryFlg);
		      } else {
		        //alert("Geocode was not successful for the following reason: " + status);
				eval(retFunc)(lat,long,false,retID);
		      }
			 
	    });
 }
function setCenterPointByAddress(lat,long,regionFlg){
	latitudeCenterAt = lat;
	longitudeCenterAt = long;
    mapPoint =  new google.maps.LatLng(parseFloat(latitudeCenterAt),parseFloat(longitudeCenterAt));
	map.setCenter(mapPoint);
}
function getGeoCoder(){
	if(geoCodeGlobal==null||geoCodeGlobal==undefined||geoCodeGlobal==''){	
		geoCodeGlobal=new google.maps.Geocoder();
	}
	return geoCodeGlobal;
}
var tempKey;
function searchStores(url, searchKey)
{	if(searchKey!=undefined && searchKey.replace(' ','')!=''){
		tempKey = searchKey;
		URL_SEARCH = url;
 		getPointByAddress(tempKey,strCountryCode,'processSearch');
	}
}
function processSearch(lat,long,countryFlg){
	if(lat!=undefined &&(""+lat).replace(' ','')!=''){
		if(addressOptions!=undefined&&addressOptions.length>1){
			simpleShow(searchOptionsDiv);
			simpleHide(searchErrorDiv);
			var optionsObj = document.getElementById(searchOptionsDiv);
			var optionsTxt = "<br/>"+ADDRESS_OPTIONS_TEXT;
			for(var i=0;i<addressOptions.length;i++){
				optionsTxt += "<br/><a href='javascript:void(0)' onclick='defaultAddressSearchTxt("+i+")' alt='"+addressOptionsInfo[i]+"' title='"+addressOptionsInfo[i]+"'>"+addressOptions[i]+"</a>";
			}
			optionsObj.innerHTML =optionsTxt;
		}else{
			if(toAddress!=''&&storeId!=undefined&&storeId!='')
				document.location.href = DIRECTIONS_LINK + '?StoreUUID='+storeId+'&AddressLatLng=' + lat + ',' + long+ '&Address=' + tempKey+"&regionFlg="+countryFlg;
			else
				document.location.href = URL_SEARCH + '?Lat=' + lat + '&Long=' + long+ '&Address=' + tempKey+"&regionFlg="+countryFlg;
		}
	}else{
		showErrMsg(UNKNOWN_ADDRESS_ERROR_MESSAGE);
	}    
}
function defaultAddressSearchTxt(index){
	document.getElementById("mapSearchTxt").value=addressOptions[index];
}
function getDistanceByCurrentAddress(storeLat,storeLong,returnID){
	var returnObj = document.getElementById(returnID);
	if(returnObj!=undefined){
		var gPoint = getCurrentGLatLng();
		distance = getDistanceBetweenPointV3(getCurrentGLatLng(),storeLat,storeLong);
		returnObj.innerHTML=distance;
		if(distance>farestStoreDistance){
			farestStoreDistance = distance;
		}
	}
}
function getDistanceBetweenPointV3(fromLatLng,storeLat,storeLong){
  var lat = [fromLatLng.lat(), storeLat]
  var lng = [fromLatLng.lng(), storeLong]
  var R = 6378137;
  var dLat = (lat[1]-lat[0]) * Math.PI / 180;
  var dLng = (lng[1]-lng[0]) * Math.PI / 180;
  var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
  Math.cos(lat[0] * Math.PI / 180 ) * Math.cos(lat[1] * Math.PI / 180 ) *
  Math.sin(dLng/2) * Math.sin(dLng/2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c;
  return Math.round(d);
}
function getCurrentGLatLng(){
	if(!currentGLatLng){
		currentGLatLng =new google.maps.LatLng(latitudeCenterAt,longitudeCenterAt);
	}
	return currentGLatLng;
}
function showErrMsg(message)
{
	simpleShow(searchErrorDiv);
	simpleHide(searchOptionsDiv);
	var errorDiv = document.getElementById(searchErrorDiv);
	if(errorDiv){
		errorDiv.innerHTML = message;
	}else{
		alert(message);
	}
}
var numberStoresCol=5;
var countyWidth=0,countyHeight=0;
var countyCurrX=0,countyCurrY=0;

function openCounty(){		 
	var popupId = 'countyTableContent';
	var popupContentTxt= createFlyoutHTML(popupId,numberStoresCol,true,document.getElementById(storeCountySelectionDiv).innerHTML);
	createFlyoutPopupLayout(storeCountyLinkDiv,0,45,popupContentTxt,popupId);
}
function createFlyoutHTML(popupId,numberOfColumns,showArrowFlag,bodyTxt){

	var responseArrow = '<div class="store-locator-arrow ">&nbsp;</div>';
	if(!showArrowFlag){
		responseArrow='';
	}
	var responseTextStart = '<div id="'+popupId+'"';
		if(numberOfColumns!=''&&parseInt(numberOfColumns)>0){
			responseTextStart = responseTextStart + 'class="level2Menu level2Menu-top stores-'+numberOfColumns+'-column">';
		}else{
			responseTextStart = responseTextStart + 'class="level2Menu level2Menu-top">';
		}
		responseTextStart= responseTextStart+'<div class="level2Menu-bottom"></div><div class="level2Menu-content"><div class="level2Menu-left"><div class="level2Menu-top-left"></div><div class="level2Menu-bottom-left"></div></div><div class="level2Menu-right"><div class="level2Menu-top-right"></div><div class="level2Menu-bottom-right"></div></div>';
	var responseTextBody = '<div class="level2Menu-innerContent"><div class="stores-by-state">'+bodyTxt+'</div></div>';	 
	var responseTextEnd = '</div></div></div></div>';
	
	return responseArrow+responseTextStart+responseTextBody+responseTextEnd;
	
}
function createFlyoutPopupLayout(objectId, /*the flyout popup will fly over the object*/
		adjPosX, /*adjusting the position of the popup in a herizontal line*/
		adjPosY, /*adjusting the position of the popup in a vertical line*/
		htmlTxt, /*the HTML content of the popup*/
		popupId
		){

	var basedObj = document.getElementById(objectId);
	var posX=0,posY=0;
	if( typeof( basedObj.offsetParent ) != 'undefined' ) {
		for( var posX = 0, posY = 0; basedObj; basedObj = basedObj.offsetParent ) {
			posX += basedObj.offsetLeft;
			posY += basedObj.offsetTop;
		}
	}	
	countyCurrX=posX+parseInt(adjPosX);
	countyCurrY=posY+parseInt(adjPosY);
	var cInfoDiv = document.getElementById(storeCountyInfoDiv);
	cInfoDiv.style.left = countyCurrX+"px";
	cInfoDiv.style.top = (countyCurrY)+"px";
	cInfoDiv.style.display='block';
	cInfoDiv.innerHTML=htmlTxt;
	
	if(document.getElementById(popupId)!=undefined){
		document.getElementById(popupId).onmouseout = function (e){mouseOutCounty(e,popupId)};
		countyWidth = document.getElementById(popupId).clientWidth;
		countyHeight = document.getElementById(popupId).clientHeight;
	}
}
function mouseOutCounty(e,popupId){
	if (ifIE()) { // grab the x-y pos.s if browser is IE
	    tempX = event.clientX + document.body.scrollLeft
	    tempY = event.clientY + document.body.scrollTop
	} else {  // grab the x-y pos.s if browser is NS
		tempX = e.pageX
    	tempY = e.pageY
	}  
	if( (parseInt(countyCurrX)+parseInt(countyWidth)<parseInt(tempX))
		||(parseInt(countyCurrX)>parseInt(tempX)) ){
		closeCounty();
	}else if((parseInt(countyCurrY)+parseInt(countyHeight)< parseInt(tempY))
			||(parseInt(countyCurrY)>parseInt(tempY))){
		closeCounty();
	}else if(document.getElementById(popupId)!=undefined){
		document.getElementById(popupId).onmousemove = function (e){mouseOutCounty(e)};
	}
}
function closeCounty(){
	document.getElementById(storeCountyInfoDiv).style.display='none';
	document.getElementById(storeCountyInfoDiv).innerHTML="";
}
function performCounty(){
	if(document.getElementById(storeCountyInfoDiv).style.display=='none'){
		openCounty();
	}else{
		closeCounty();
	}
}
function clickCenterCounty(lat,lng,regionFlg,countId){
	if(lat!=undefined&&lat!=''&&regionFlg==true){
		var gPoint = new google.maps.LatLng(lat,lng);
		var maxDistance=0;
		var storesByCounty = eval("document.StoreForm.county"+countId);	
		map.setCenter(gPoint);
	   if(storesByCounty!=undefined&&storesByCounty.length>1){
			for(var i=1;i<storesByCounty.length;i++){
				var paramValue = storesByCounty[i].value;
				var paramLat = paramValue.substring(0,paramValue.indexOf(','));
				var paramLng = paramValue.substring(paramValue.indexOf(',')+1,paramValue.length);
				var distance = getDistanceBetweenPointV3(gPoint,parseFloat(paramLat),parseFloat(paramLng));
				if(parseInt(paramLat)!=0&&(distance>maxDistance)){
					maxDistance = distance;
				}	
			}		
		}
		if(maxDistance>0)
			setMapZoomBasedOnDistance(maxDistance);
		else
			setMapZoomBasedOnDistance(9999999);
		closeCounty();
	}
}
function setStateCenter(stateName,cntID){
	getPointByAddress(stateName,strCountryCode,'clickCenterCounty',cntID);
}
function updateStoreSelectionColumnInLink(numCol){
	numberStoresCol= numCol;
}
/*
 *Shipping and Payment Method 
 */
function disabledPaymentMethod(){		
	var shippingArr = document.getElementById("frmbilling").shippingId;
	if(shippingArr!=undefined &&shippingArr.length>1){
		for(var i=1;i<shippingArr.length;i++){
			var shippingId = shippingArr[i].value;
			if(document.getElementById(shippingId+"PaymentMethod")!=undefined)
				document.getElementById(shippingId+"PaymentMethod").style.display='none';
		}
	}
}
function resetPaymentMethod(){		
	var pMethodOption = document.getElementById("frmbilling").PaymentMethodSelection;
	if(pMethodOption!=undefined &&pMethodOption.length>1){
		for(var i=1;i<pMethodOption.length;i++){
			pMethodOption[i].checked = '';
		}
	}
}
function updateShippingPaymentBasket(){
	var url = document.getElementById("refreshShippingPaymentBasketURL").innerHTML;
	var paymentMethodUUID="";
	var paymentMethodCheckboxes = document.getElementById("frmbilling").PaymentMethodSelection;
	if(paymentMethodCheckboxes!=undefined){
		if(paymentMethodCheckboxes.length>1){
			for(var i=0;i<paymentMethodCheckboxes.length;i++){
				if(paymentMethodCheckboxes[i].checked){
					paymentMethodUUID = paymentMethodCheckboxes[i].value;
					break;
				}
			}
		}else if(paymentMethodCheckboxes.checked){
			paymentMethodUUID = paymentMethodCheckboxes.value;
		}
	}
	$.ajax({ url: url,data: "paymentMethodUUID="+paymentMethodUUID,
		success: function(html){
			$("#ShippingPaymentSummaryBox .summary-box-holder .summary-box").html(html);
			reloadECCPanel();
		}
	});
	
}
function changeShippingMethod(shippingId){
	var paymentMethodDiv = document.getElementById(shippingId+"PaymentMethod");
	disabledPaymentMethod();
	resetPaymentMethod();
	if(paymentMethodDiv!=undefined){
		paymentMethodDiv.style.display='block';
	}
	updateShippingPaymentBasket();
}

function initDeliveryCalendar(){
	var selectedSlotTime="";
	$(".calendar a").click(function(e){
		e.preventDefault();
		var thisBox         = $(this);
		var timeDropdownObj = $("#sareaDeliveryTimeDD");
		eval("var params = " + this.getAttribute("rel"));
		
		if(timeDropdownObj.data("currentSelectedDate")){
			timeDropdownObj.data("currentSelectedDate").removeClass("selected");
		}
		timeDropdownObj.data("currentSelectedDate", thisBox);
		thisBox.addClass("selected");
		
		$("#selectOptionsDeliveryTimeDD option").remove();
		$("#optionsDivDeliveryTimeDD li").remove();
		document.getElementById("mySelectTextDeliveryTimeDD").innerHTML = $("#mySelectTextDeliveryTimeDD").attr("title");
		$("#selectOptionsDeliveryTimeDD").append('<option value="">??</option>'); //add blank value
		var selectedIndex = 0;
		for(var i = 0; i < params[1].length; i++){
			var selectedSlotTimeTag = "";
			if(params[2][i]==selectedSlotTime){selectedSlotTimeTag="selected";selectedIndex=(i+1)}
			$("#selectOptionsDeliveryTimeDD").append('<option value="'+params[2][i]+';'+params[0][i]+'" '+selectedSlotTimeTag+'>'+params[1][i]+'</option>'); //TimeslotNum;TimeslotUUID
			$("#optionsDivDeliveryTimeDD ul").append('<li><a href="javascript:showOptionsCheckout(\'DeliveryTimeDD\',\'\'); selectValue(\'\','+(i+1)+',\'DeliveryTimeDD\',document.frmbilling.selectOptionsDeliveryTimeDD.value);">'+params[1][i]+'</a></li>');
		}
		$(".deliveryTime:hidden").show("slow");
		if(selectedSlotTime!=""){
			showOptionsCheckout('DeliveryTimeDD',''); 
			selectValue('',selectedIndex,'DeliveryTimeDD',document.frmbilling.selectOptionsDeliveryTimeDD.value);
		}
		selectedSlotTime="";
	});
	if($("#SelectedTimeSlot").attr("value")!=undefined&&$("#SelectedTimeSlot").attr("value")!=""){
		var selectedId = $("#SelectedTimeSlot").attr("value");
		selectedSlotTime = selectedId.substring(0, selectedId.indexOf(";"));
		selectedId = selectedId.substring(selectedId.indexOf(";")+1, selectedId.length);
		try{
			$("#"+selectedId).click();
		}catch(e){}
	}
}


/* 
 *  Gets Session status String from the cookie, used both in login box and Omniture Script
 */
function getSessionStatus() {
	sessionStatus = readCookie("sessionStatus");
	
	// if not registered check if it has "Rememeber me" cookie instead.
	if (sessionStatus == "" || sessionStatus == null) {
		// Remember me
		var viewKey = readCookie("ViewKey");		
		if (viewKey != null && viewKey != "") {			
			url = $("#updateSessionURL").html();
			$.ajax({ url:url, async:false,
				success: function(html){
				    void(s.t());
				    if (html.substr(0,3) == "ok:") sessionStatus = html.substr(3);				    					
				}
			});
		}			
	}	
	// sessionStatus was first encoded in UTF-8 entities to escape "special" letters like "?" in &#000;
	// then URLencoded to avoid "&" and ";" to mess with the cookie. Replaces also all "+" with spaces.
	if (sessionStatus !== null) sessionStatus = decodeURIComponent(sessionStatus).replace(/\+/g," ");
	
	return sessionStatus;
}


/*
 *  Inits the ViewLoginBasket include depending on the session cookies that are set.
 *  "sessionStatus" is a global variable because it must be visible also from  Omniture Javascript!
 */

function initBasketLoginPanel() {
	
    var sid = readCookie("sid");
	sessionStatus = getSessionStatus();
	
	if (sessionStatus != null) {
		// the sessionStatus was generated with the current session
		if (sessionStatus != "" && (sessionStatus.indexOf(sid) != -1)) {
			var ss = sessionStatus.split("|");
			$(".LoginForm-FirstAndLastName").html(ss[1]);			
			$("#LoginForm-Anonymous").css("display","none");
			$("#LoginForm-LoggedIn").css("display","block");
		} else {
			$("#LoginForm-Anonymous").css("visibility","visible");
		}
	} else {
		$("#LoginForm-Anonymous").css("visibility","visible");
	}
		
	var basketcookie = readCookie("basketStatus");
	if (basketcookie != null && basketcookie != "") {
		basketcookie=decodeURIComponent(basketcookie).replace(/\+/g," ");
		var Values = basketcookie.split("|");
		$("#minicart-Items").html(Values[0]);
		if (Values[0] != "1") {
			$("#minicart-ItemMore").css("display","inline");
		} else {
			$("#minicart-Item1").css("display","inline");
		}
		$("#minicart-SubTotal").html(Values[1]);
		$("#minicart-Shipping").html(Values[2]);
		if (Values[3] != "") {		
			$("#minicart-Payment").html(Values[3]);
		} else {
			$("#minicart-PaymentRow").css("display","none");
		}
		$("#minicart-Total").html(Values[4]);
		$("#minicart-contentEmpty").css("display","none");
		$("#minicart-contentFull").css("display","block");
	}

}
function setDefaultBodyStyle(){	
		var contentObj = document.getElementById("allContent"); 
		contentObj.className="default-body";
		
}
function initBigbang(){
	if ( typeof(jsonBB) == 'undefined' ){
		setDefaultBodyStyle();
		return;
	}
	if( typeof(jsonBB.backgroundImage)!= 'undefined' && jsonBB.backgroundImage != '' ){
		var image = jsonBB.backgroundImage;
		var attachement = jsonBB.backgroundAttachment;
		var repeat = jsonBB.backgroundRepeat;
		var url = jsonBB.backgroundURL;
		var newwindow = jsonBB.backgroundNewwindow;
		var styleContainerObj = document.getElementById("bigBangStyleContainer");
		if(attachement == 'stretch'){			
			$('#allContent').append('<img id="BigbangFit2Screen" alt="" title="Bigbang: Fit to Screen" src="'+image+'" />');
		}else{
			var body = "body { background-image: url("+image+");";
			body+= "background-attachment: "+attachement+";";
			body+= "background-repeat: "+repeat+";";
			body+= "background-color: transparent;background-position: 0 0;}";
			cssNodes = document.createTextNode(body);			
			if (styleContainerObj.styleSheet) {
				styleContainerObj.styleSheet.cssText = cssNodes.nodeValue;
            } else {
            	styleContainerObj.appendChild(cssNodes);
            }
			
		}		
		cssNodes = document.createTextNode("#body_wrapper{background:none; }");			
		if (styleContainerObj.styleSheet) {
			styleContainerObj.styleSheet.cssText += cssNodes.nodeValue;
        } else {
        	styleContainerObj.appendChild(cssNodes);
        }
		if(url!=undefined&&url!=''){
			cssNodes = document.createTextNode("#body_wrapper:hover { cursor: pointer; background:none; }");			
			if (styleContainerObj.styleSheet) {
				styleContainerObj.styleSheet.cssText += cssNodes.nodeValue;
            } else {
            	styleContainerObj.appendChild(cssNodes);
            }
		}
		//setting onclick function on BB
		if(url!=undefined&&url!=''){
			BigbangOnclick(url,newwindow);
		}
	}
}

/*
 *  Inits the Compare Products basket.
 *  It calls the pipeline only if the cookie with the product is defined.
 */

function initCompareBasket() {
    var cp = readCookie("CompareProducts");    
	if ((cp != null) && (cp != "")) {
		$.ajax({ url: compareBasketURL+"?ShowCompareMini="+ShowCompareMini,
			success: function(html){
				$("#compareBasket").html(html);
				simpleShow('cnCompare');
			}
		});
	}
}

/*
 * Functions for "notify me" button when product is not available.
 * Functions for "wishlist popup".
 */
function initPopups() {
	if ($("#notify-popup").length == 0){
		$("<div id='notify-popup'>").appendTo("body");
	}
	if ($("#wishlist-popup").length == 0){
		$("<div id='wishlist-popup'>").appendTo("body");
	}	
	$(".notify-box a").click(function(e){
		var icon = $(this);
		$("#notify-popup:visible").hide();
		$("#notify-popup").load($(this).attr("href"),function(){
			$("#notify-popup").css("top",icon.offset().top - $("#notify-popup").height() - 3);
		
			$("#notify-popup").css("left", icon.offset().left - ($("#notify-popup").width() / 2) + (icon.width() / 2) );
			$("#notify-popup").fadeIn();
			$("#notify-popup a.link-button").click(function(e){return sendNotification(e,$(this));});
		});
		return false;	
	});
	
	$("a.add-to-wishlist").click(function(e){
		var icon = $(this);
		var productRefList = getProductRefIDsFromBasket();
		$("#wishlist-popup:visible").hide();
		$("#wishlist-popup").load($(this).attr("href"),{'ProductRefList': productRefList},function(){
			$("#wishlist-popup").css("top",icon.offset().top - $("#wishlist-popup").height() - 3);
		
			$("#wishlist-popup").css("left", icon.offset().left - ($("#wishlist-popup").width() / 2) + (icon.width() / 2) );
			$("#wishlist-popup").fadeIn();
			$("#wishlist-popup a.link-button").click(function(e){return ($(".basket .cell01 a.add-to-wishlist").length > 0)?addingWishlistProductsFromBasket(e,$(this)):addingWishlistProduct(e,$(this));});
		});
		return false;	
	});

	$("#wishlist-popup").click(function(e){
		e.stopPropagation();
	});	

	$("#notify-popup").click(function(e){
		e.stopPropagation();
	});
	$("#NotifyProductPage .notify-form a.link-button").click(function(e){
		return sendNotification(e,$(this));
	});
	
	$("#wishlist-popup .notify-form a.link-buttont").click(function(e){
		return addingWishlistProduct(e,$(this));
	});	

	$(document).click(function(){
		$("#notify-popup").fadeOut();
		$("#wishlist-popup").fadeOut();		
	});
}

/*
 * This function initializes all checkboxes/buttons for product include.
 * It is called in the "document.ready()" function, but also when new content
 * is loaded via Ajax for endles paging in categories and search.
 */
function initProductsControls() {	
	initAddToCartButtons();
	initCompareCheckboxes();
	initPopups();
	setTimeout("initBorder()",1500);
}
function initBorder(){
	//this function will be used for updating graphical border in the red design
	//when the products are loaded automatically in a product search result page and a category product result page.
}
function removeHeightBorder(){}
var addingWishlistProduct = function(e,elm){
	var wishlistName = $("#wishlistFillingNameID .text-wrapper input").val();
	var wishlistUUID = $("#wishlistSelectingNameID .select-wrapper select").val();
	if(wishlistUUID=='new'&&wishlistName==''){
		$('#addToWishlistError').show();
		return false;
	}
	var product_ref = elm.attr("rel");
	if(wishlistUUID=='new'){wishlistUUID='';}

	/*
	var dataString = {'ProductRefID':product_ref,'WishlistUUID':wishlistUUID,'WishlistName':wishlistName};
	$.ajax({
		type: "POST",
		url: elm.attr("href"),
		data: dataString,
		contentType: "application/x-www-form-urlencoded;charset=UTF-8",
		cache: false,
		success: function(html){
			$('#wishlist-popup').html(html);
		}});
		*/
	$('#wishlist-popup').load(elm.attr("href"),{
		'ProductRefID':product_ref, 
		'WishlistUUID':wishlistUUID, 
		'WishlistName':wishlistName});
	e.stopPropagation();
	return false;
	}

var addingWishlistProductsFromBasket = function(e,elm){
	var wishlistName = $("#wishlistFillingNameID .text-wrapper input").val();
	var wishlistUUID = $("#wishlistSelectingNameID .select-wrapper select").val();	
	if(wishlistUUID=='new'&&wishlistName==''){
		$('#addToWishlistError').show();
		return false;
	}
	if(wishlistUUID=='new'){wishlistUUID='';}
	var productRefList =getProductRefIDsFromBasket() 
	$('#wishlist-popup').load(elm.attr("href"),{
		'ProductRefList':productRefList, 
		'WishlistUUID':wishlistUUID, 
		'WishlistName':wishlistName});
	e.stopPropagation();
	return false;
}
function getProductRefIDsFromBasket(){
	var productRefList = '';
	var selectedProducts = $("input[name='Selected']");
	if(selectedProducts!=undefined && selectedProducts.length >0){
		for(var i=0;i<selectedProducts.length;i++){
			if(selectedProducts[i].checked)
			{
				productRefList+= (selectedProducts[i].value+";")
			}
		}
	}
	return productRefList;
}
function selectWishlistName(ele){
	var wishlistUUID = ele.value;
	if("new"==wishlistUUID){
		$("#wishlistSelectingNameID").hide();
		$("#wishlistFillingNameID").show();
		$("#wishlistLinkID").show();
	}
	return false;
}
function selectAllWishlist(obj){
	var checkboxlist = $("input[name='Selected']");
	if(checkboxlist.length >0){
		for(var i=0;i<checkboxlist.length;i++){
			if(checkboxlist[i].checked!=obj.checked)
				changeWishlistCheckboxes('prodWishlist_'+checkboxlist[i].id,checkboxlist[i].id);				
		}
	}
}
var redirect2TrackURL = function(e,elm){
	var targetURL = elm.attr("href");	
	$.ajax({url: targetURL,
		async: false,
		type: 'POST',
		dataType: "json",
		success: function(data){
			if (data.JumpTarget&&data.JumpTarget!='') {
				var url = data.JumpTarget.replace(/\&amp;/g,'&');
				window.open(url+data.TrackingNumbers, '_blank');
			}else{
				var txtInfo = "There is no url available for "+data.ProductSKU+" - ProviderCode and BigBox ('"+data.ProviderCode+"','"+data.BigBox+"')";
				elm.attr("alt",txtInfo);
				elm.attr("title",txtInfo);
			}
		}});

	e.stopPropagation();
	return false;
}

function updateOrderExpectDateProductLineItem(){
	var productRefList = '';
	var lineItems = $("div[class='product-expect-date']");
	if(lineItems!=undefined && lineItems.length >0){
		for(var i=0;i<lineItems.length;i++){
			if(productRefList=="" || productRefList.indexOf(lineItems[i].id)<0)
				productRefList+= (lineItems[i].id+";")
		}
		if(productRefList!=""){
			var targetURL = updateExpectedDateOrderLineItemURL;	
			$.ajax({url: targetURL,
				async: false,
				type: 'POST',
				data: "RefIDs=" + productRefList,
				dataType: "json",
				success: function(data){
					for(var i=0;i<lineItems.length;i++){
						var index=0;
						while(eval("data.RefID"+index)!=undefined){
							if(eval("data.RefID"+index)==lineItems[i].id){
								lineItems[i].innerHTML=eval("data.RefIDDate"+index);
							}
							index++;
						}
					}
				}});
		}
	}
	return productRefList;
}
/*
 * Document ready DO NOT PUT ANY CODE BELOW THIS ONLOAD HANDLER
 * Add all functions and others that needs to be executed when document html has loaded in here
 * in the order they need to be executed 
*/
$(document).ready(function(){
	initBasketLoginPanel();
	initFlyoutMenu();
	
	initProductsControls();
	
	initDefaultInputTextSwitcher();
	initSubmitTriggers();
	initSuggestBox();
	// used only in login box
	initCheckboxes();
	
	initDeliveryButtons();
	initDeliveryCalendar();
	if( $('#cnCompare').length ) initCompareBasket();
	initBigbang();
	
	exeFunc();
	
	$('#BillingAddressInfo input, #userForm input').bind('keypress', function(e){
		var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;
	    if(key == 13) {
	        e.preventDefault();
	        var inputs = $(this).closest('form').find(':input:visible');
	        inputs.eq( inputs.index(this)+ 1 ).focus();
	    }
	});
	$('a.track-url').click(function(e){return redirect2TrackURL(e,$(this));});
	
	if ($('div.product-expect-date').length > 0){
		updateOrderExpectDateProductLineItem();
	}
});
