
var debugVar;



function stripAlphaChars(pstrSource){ 
	var m_strOut = new String(pstrSource); 
	m_strOut = m_strOut.replace(/[^0-9]/g, ''); 						
	return m_strOut; 
}


function correctCategoryPriority(){	
	//prostores sortby not functioning -> place items with 9998 priority before 9999 priority 
	//priority stored in lang attribute
	if($('#catalogSubNavigationInner div').length > 0){
		$('#catalogSubNavigationInner div[lang=9998]').insertBefore('#catalogSubNavigationInner div[lang=9999]');			
	}
	if($('#categoryLandingContainer div').length > 0){
		$('#categoryLandingContainer div[lang=9998]').insertBefore('#categoryLandingContainer div[lang=9999]');			
	}
	if($('.promo1Category').length > 0){
		$('.promo1Category[lang=9998]').insertBefore('.promo1Category[lang=9999]');			
	}
	if($('.promo2Category').length > 0){
		$('.promo2Category[lang=9998]').insertBefore('.promo2Category[lang=9999]');			
	}
	if($('.promo1Category').length > 0){
		$('.promo3Category[lang=9998]').insertBefore('.promo3Category[lang=9999]');			
	}	
}

//Home Page Scripts
function getSubCategoryCount(e){
	//Build storefront API url with subcategory.parentChainDisplay (stored in .lang attribute of element)
	var url = "http://www.tvliftcabinet.com/Products.bok?category=" + e.lang;
	
	//Post URL to storefront API and get results -> store JSON data in the products object
	$.get(
		url, 
		function(data, textStatus) {
			
			//prepare response string for JSON -> remove block comment
			responseString = data.replace(/\/\*.+\*\//g, '');
			
			// this will give us an array of objects
			//var productData = JSON.parse(responseString);
			var productData = $.parseJSON(responseString);
			
			var products = new Array();
			products = productData.echo;
			
			//place returned total in subCategoryCount element
			e.innerHTML = products.total;			
		}, 
	'text');
}




function reviewClick(){
	//Shows Reviews tab and scrolls down
	showTab(3);
	window.scroll(0,570);
}



// List Page Template
function hideUnreviewed(){
	var divs = document.getElementById('powerReviews').getElementsByTagName('div');
	for(i=0; i<divs.length; i++){
		if(divs[i].className == 'prSnippetNumberOfRatingsText'){
			if(divs[i].innerHTML.indexOf('(0 Ratings)') != -1){
				document.getElementById('powerReviews').innerHTML = '<br/>';
			}
		}
	}
	document.getElementById('powerReviews').style.display = 'block';
}

function updateReviewsText(){
	var divs = document.getElementById('liProds').getElementsByTagName('div');
	for(i=0; i<divs.length; i++){
		if(divs[i].className == 'prSnippetNumberOfRatingsText'){
			var tmpRatingsText = divs[i].innerHTML;
			divs[i].innerHTML = '';
			divs[i].innerHTML = tmpRatingsText.replace("Ratings", "Reviews").replace("Rating", "Review");
			divs[i].style.visibility = 'visible';
		}
		if(divs[i].className == 'pr_snippet_category'){
			divs[i].style.display = 'inline-block';				
		}
	}
}


//BEGIN Detail template

//BEGIN detail page multi-layered zoom
function highlightCurrentImage(e){
	var dtThumbs = document.getElementById('dtMediaContent').getElementsByTagName('img');
	for(i=0; i<dtThumbs.length; i++){
		if(dtThumbs[i].className == 'dtProdThumb'){
			dtThumbs[i].style.border = '1px solid #ddd';
		}
	}
	e.style.border = '1px solid #444';
}

function setCurrentZoom(i){
	//Hide all enlarge links
	$('.dtEnlarge').each(function(index){
		this.style.display = 'none';
	});
	
	
	
	//Show current enlarge link
	if(document.getElementById('dtZoomLink' + i)){
		document.getElementById('dtZoomLink' + i).style.display = 'block';
	}
}
//END detail page multi-layered zoom


//BEGIN detail page tab scripts
function clearTabs(){
	$(".productTab div").attr('class', 'productTab_off');
	$('.productTabData').css('display', 'none');
	
	//place nav in reverse z-index order so that left tabs overlay right tabs
	$(".productTab_off").each(function(key, value){
		$(this).css('z-index', 9 - key);
	});
}

	
function showTab(id){
	
	clearTabs();
	
	//select current tab
	$('.productTab_off')[id].className = 'productTab_on';
	
	//place current tab on top of other tabs
	$('.productTab_on').css('z-index', '10');
	
	//display current data
	$($('.productTabData').get(id)).css('display', 'block');
	
}


//END detail page tab scripts


function toggleSelectHover(optionNumber){
	var numOfOptions = 3;
	var optionDiv = document.getElementById('dtOption' + optionNumber);
	var selectHoverDiv = document.getElementById('dtHover' + optionNumber);
	
	//close all other drop downs
	for(i=0; i<=numOfOptions; i++){
		if(i != optionNumber){
			if(document.getElementById('dtOption' + i) && document.getElementById('dtHover' + i)){
				document.getElementById('dtOption' + i).style.zIndex = 1;
				document.getElementById('dtHover' + i).style.display = 'none';
			}			
		}
	}
	
	//toggle selected drop down
	if(selectHoverDiv.style.display == 'none'){
		optionDiv.style.zIndex = 10 - optionNumber;
		selectHoverDiv.style.display = 'block';
	}
	else{
		optionDiv.style.zIndex = 1;
		selectHoverDiv.style.display = 'none';
	}
}

//color attribute object
var colorAttribute = {
	isPresent: false, //updated in domready
	isSelected: false //updated in dtColorSelect()
};

function dtColorSelect(color, id){
	colorAttribute.isSelected = true;
	document.getElementById(id).checked = 'true';
	//assign selected color
	document.getElementById('dtColorSelectText').innerHTML = "Color: " + color;
	
	toggleSelectHover(1); //close hover
}


function dtOptionSelect(optionText, optionIndex, optionTitle){
	document.getElementById('dtSelectText' + optionIndex).innerHTML = optionTitle + ': ' + optionText;
	toggleSelectHover(optionIndex);
}



//Adjusts subtotal based on selected related products
function updateMasterSubtotal(id){
	var inputs = document.getElementById('dtInfo').getElementsByTagName('input');
	var basePrice = document.getElementById('priceAsConfigured').lang;
	var relatedBasePrice = 0.00;
	var subTotal = 0.00;
	
	//select corresponding hidden radio
	document.getElementById(id).checked = 'true';
	
	for(i=0; i<inputs.length; i++){
		if(inputs[i].className == 'dtRelatedAdd'){
			if(inputs[i].checked == true){
				relatedBasePrice = parseFloat(relatedBasePrice) + parseFloat(inputs[i].lang);
			}
		}
	}
	
	subTotal = parseFloat(basePrice) + parseFloat(relatedBasePrice);
	document.getElementById('priceAsConfigured').innerHTML = '$' + subTotal.toFixed(2);
}


/* BEGIN siblingNavigation object */
/* gets products from selected category on detail page using Storefront API -> set prev and next sibling navigation links*/
var siblingNavigation = {
	previousLink: '#',
	nextLink: '#',
	siblingProducts: new Array(),
	currentProductNumber: 'all',
	currentProductIndex: 0,
	
	init: function(){
		if($('#siblingNavigationContainer').length > 0){
			//pass current category to .getProducts -> current category is stored in #siblingNavigationContainer.lang
			siblingNavigation.getProducts($('#siblingNavigationContainer').attr('lang'));			
		}
	},
	
	getProducts: function(currentCategory){
		//Build storefront API url with subcategory.parentChainDisplay (stored in .lang attribute of element)
		var url = "http://www.tvliftcabinet.com/Products.bok?category=" + currentCategory + "&echo=name&echo=displayurl&echo=productnumber";
		
		//Post URL to storefront API and get results -> store JSON data in the products object
		$.get(
			url, 
			function(data, textStatus) {
				
				//prepare response string for JSON -> remove block comment
				responseString = data.replace(/\/\*.+\*\//g, '');
				
				// this will give us an array of objects
				//var productData = JSON.parse(responseString);
				var productData = $.parseJSON(responseString);
				
				siblingNavigation.siblingProducts = productData.echo.results;
				
				//must call remaining chain of functions from here instead of init() because there is a small delay in returning data from the Storefront API
				siblingNavigation.getProductsComplete();
				
			}, 
		'text');
	},
	
	getProductsComplete: function(){
		//this function is called after data is returned from the storefront API
		siblingNavigation.getCurrentProductIndex();
		siblingNavigation.setNavigationLinks();
	},
	
	getCurrentProductIndex: function(){
		siblingNavigation.currentProductNumber = $('#siblingNavigationContainer').attr('rel');
		
		$.each(siblingNavigation.siblingProducts, function(key, val){
			if(siblingNavigation.currentProductNumber == val.productnumber){
				siblingNavigation.currentProductIndex = key;
			}
		});		
	},
	
	setNavigationLinks: function(){
		var i = siblingNavigation.currentProductIndex;
		
		if(siblingNavigation.siblingProducts.length <= 1){
			$('#siblingNavigationContainer').hide();
			return false;
		}
		
		//if current product is not the first -> set the prev
		if(i > 0){
			$('#productSiblingLink_prev').attr('href', siblingNavigation.siblingProducts[i - 1].displayurl);
		}	
		
		//if the current product is the first -> set prev to the last element in the array
		if(i == 0){
			$('#productSiblingLink_prev').attr('href', siblingNavigation.siblingProducts[siblingNavigation.siblingProducts.length - 1].displayurl);
		}
		
		//if the current product is not the last -> set next to the first element in the array
		if(i < siblingNavigation.siblingProducts.length - 1){
			$('#productSiblingLink_next').attr('href', siblingNavigation.siblingProducts[i + 1].displayurl);
		}
		
		//if the current product is the last -> set next to the first element in the array
		if(i == siblingNavigation.siblingProducts.length - 1){
			$('#productSiblingLink_next').attr('href', siblingNavigation.siblingProducts[0].displayurl);
		}
		
		
	}
}
/* END siblingNavigation object */



//detail page pricing -> Adjusts subtotal based on selected related products
var detailPagePricing = {
	basePrice: 0,
	optionsPrice: 0,
	priceAsConfigured: 0,
	
	updatePrices: function(id){
	
		detailPagePricing.basePrice = $('#priceAsConfigured').attr('lang');

		//select corresponding hidden radio
		detailPagePricing.setHiddenOption(id);
		
		//set options price display
		$('.dtOption').each(function(key, value){	
			//find each radio within .dtOption
			$(this).find("input[type=radio]").each(function(){
				if(this.checked == true){
					//find .sectionPrice within current .dtOption and apply selected radio price (radio.lang)
					$(value).find('.dtSectionPrice').html('$' + parseFloat(this.lang).toFixed(2));
				}
			});
		});
		
		//reset optionsPrice
		detailPagePricing.optionsPrice = 0;
		
		//tally optionsPrice
		$('.dtRelatedAdd').each(function(){			
			if(this.checked == true){
				//total all selected radio option prices (radio.lang)
				detailPagePricing.optionsPrice += parseFloat(this.lang);
			}
		});
		
		//alert(detailPagePricing.optionsPrice);
		
		
		detailPagePricing.priceAsConfigured = parseFloat(detailPagePricing.basePrice) + parseFloat(detailPagePricing.optionsPrice);
		document.getElementById('priceAsConfigured').innerHTML = '$' + detailPagePricing.priceAsConfigured.toFixed(2);
	},
	
	setHiddenOption: function(id){
		//select corresponding hidden radio
		document.getElementById(id).checked = true;		
	}
}



//collects checkbox values and builds parameters -> redirects page to new url
function verifyChecks(prodNo){
	var product = '&product_no=' + prodNo + '&';
	var counter = 0;
	var url = '';
	var inputs = document.getElementsByTagName('input');
	for (i=0; i < inputs.length; i++){
		if (inputs[i].type == 'checkbox' || inputs[i].type == 'radio'){
			if (inputs[i].checked == true){
				counter++;
				url = url + String.fromCharCode(38) + '' + inputs[i].value;
			}
		}
	}
	
	if (counter < 20) {
		url = url.substr(1);
		
		//require color selection -> if color option is present and has not been selected show error
		if(colorAttribute.isPresent && colorAttribute.isSelected == false){
			alert('Please select a color option');
			$('#dtColorSelect').effect("highlight", {}, 3000);
			return false;
		}
		window.location= '/Cart.bok?smode=add' + product + url;		
	}
}


function dtModifyPowerReviewsText(){
	//Grabs number of reviews from a DOM element in the reviews section and injects it into "Read Reviews" link
	if(document.getElementById('powerReviews')){
		if(document.getElementById('powerReviews').getElementsByTagName('p')){
			var reviewCount = 0;		
			var paragraphs = document.getElementById('powerReviews').getElementsByTagName('p');
			for(i=0; i<paragraphs.length; i++){
				if(paragraphs[i].className == 'pr-snippet-review-count'){
					if(paragraphs[i].innerHTML.indexOf('(0 Ratings)') == -1){
						reviewCount = stripAlphaChars(paragraphs[i].innerHTML);				
					}										
				}
			}
			document.getElementById('dtReviewCount').innerHTML = '(' + reviewCount + ') ';
		}
	}
}


//Adjusts subtotal based on selected related products
function updateSubtotal(){
	var inputs = document.getElementById('relatedproducts').getElementsByTagName('input');
	var basePrice = document.getElementById('basePriceHolder').lang;
	var relatedBasePrice = 0.00;
	var subTotal = 0.00;
	
	for(i=0; i<inputs.length; i++){
		if(inputs[i].className == 'dtRelatedAdd'){
			if(inputs[i].checked == true){
				relatedBasePrice = parseFloat(relatedBasePrice) + parseFloat(inputs[i].lang);
			}
		}
	}
	
	subTotal = parseFloat(basePrice) + parseFloat(relatedBasePrice);
	document.f1.total.value = '$' + subTotal.toFixed(2);
}


//Place the debug function with a custom message in a script and input 'debug' as a parameter in a URL - an alert will display - this allows for debugging on a live store version
function debug(message){
	if(window.location.href.indexOf('debug') != -1){
		alert(message);
	}
}


//BEGIN footer scripts
function setImageSource(image, source){
	image.src = store.storeversionImagesDirectory + source;
}
//END footer scripts



$(document).ready(function () {
	
	correctCategoryPriority();
	
	if($('.subCategoryCount').length > 0){
		$('.subCategoryCount').each(function(index, value){ 
			getSubCategoryCount(this);
		});
	}
	
	siblingNavigation.init();
	    
	//if color attribute selector is available (detail template)
	if(document.getElementById('dtColorSelect')){
		colorAttribute.isPresent = true;
	}

	if(document.getElementById('gallery')){
		clickMenu('gallery');
	}
	
	//Modify List Page PowerReviews text
	if(document.getElementById('liProds')){
		var timer = setTimeout("updateReviewsText()", 1000);
	}
	
	//Modify Detail Page PowerReviews text
	if(document.getElementById('powerReviews')){
		hideUnreviewed();		
		setTimeout("dtModifyPowerReviewsText()", 1000);
	}
	
	if(document.getElementById('player')){
		flowplayer("player", {src: "flash/flowplayer/flowplayer-3.1.5.swf", wmode: 'opaque'}); 
	}
});
