//  These functions are used on the details page for a product
var currentCurrency;

function loadDetailsDOL(existingDolSessionId, productStyleCode, productName, productSize, openDOL){
	if(validateItemQuantity()){
		saveItemsToCartFromDetails(openDOL);
		//loadDOL(existingDolSessionId, productStyleCode, productName, productSize);
	}
}

function validateItemQuantity(){
	var qtyObjects = $$('.detailsQuantitySelect');
	var len = qtyObjects.length;
	var allZeroQuantities = true;
	for(var i = 0; i<len; i++){
		if($F(qtyObjects[i]) != '0'){
			allZeroQuantities = false;
			break;
		}	
	}
	
	if(allZeroQuantities == false){
		return true;
	} else {
		if(len < 2){
			alert('Please select a quantity.');
		} else {
			alert('Please select a quantity for one of the products.');
		}
		return false;
	}
}

function saveItemsToCartFromDetailsDOL(openDOL, isLoggedIn){
	var openDOL = true;
	var isLoggedIn = false;
	saveItemsToCartFromDetails(openDOL, isLoggedIn)
}

function saveItemsToCartFromDetails(openDOL, isLoggedIn){
	if(validateItemQuantity()){
		var detailsForm = $('quantityForm');
		var productId;
		var productQuantity;
		var familyQuantityJSONArray;
		var familyProductIdJSONArray;
		
		if(detailsForm != null){
			var tempInput;
			var len;
			
			productId= $F('productId');
			productQuantity= $F('quantity');	    
		    
			var quantities = $$('.detailsQuantitySelect')
			len = quantities.length;
		    var familyQuantityJSONArray = "[{";
		    var isFirst = true;
		    if(len > 0){
		        for(var i=0; i<len; i++){
		        	tempInput = quantities[i];
		        	if(!isFirst){
		        		familyQuantityJSONArray += ",";
		        	}
	        		familyQuantityJSONArray += tempInput.id + ":" + $F(tempInput);
	        		isFirst = false;
		        }
		    }
		    familyQuantityJSONArray += "}]";
		    
		    var familyProductIds = detailsForm.getInputs('hidden', 'familyProductId');
			len = familyProductIds.length;
		    var familyProductIdJSONArray = "[{familyProductIds:'";
		    if(len > 0){
		        for(var j=0; j<len; j++){
		        	if(j != 0){
		        		familyProductIdJSONArray += ",";
		        	}
		        	tempInput = familyProductIds[j];
		        	familyProductIdJSONArray += $F(tempInput);
		        }
		    }
		    familyProductIdJSONArray += "'}]";
		    
		    saveItemsToCart(productId, productQuantity, familyProductIdJSONArray, familyQuantityJSONArray, openDOL, isLoggedIn);
		}
	}
}

function saveItemsToCart(productId, productQuantity, familyProductIdJSONArray, familyQuantityJSONArray, openDOL, isLoggedIn){
	var saveItemsToCartURL = '/store/saveItemsToCart';
	saveItemsToCartURL += '/market/' + $F('marketId');
	saveItemsToCartURL += '/productId/' + escape(productId);
	saveItemsToCartURL += '?productQuantity=' + escape(productQuantity);
	saveItemsToCartURL += '&familyProductIdJSONArray=' + encodeURIComponent(familyProductIdJSONArray);
	saveItemsToCartURL += '&familyQuantityJSONArray=' + encodeURIComponent(familyQuantityJSONArray);
	
	new Ajax.Request(saveItemsToCartURL, {
		method: 'post',
		onSuccess: function(request) {
    		doOnSaveItemsToCartSuccess(request.responseJSON, openDOL, isLoggedIn);
    	},
		onFailure: function(request) {
    		doOnSaveItemsToCartFailure(request, openDOL, isLoggedIn);
    	}
    });
}

function doOnSaveItemsToCartSuccess(responseJSON, openDOL, isLoggedIn){
	if(responseJSON.status == "failed"){
		showDetailsErrorMessage(responseJSON.message)
	} else {
		if(openDOL){
			$('addToCartDOL').addClassName('visibilityHidden');
			$('loadingDOLText').show();
			launchedFromCart = false;
			loadDOL(responseJSON.DOLSessionId, responseJSON.DOLItemsJSON, isLoggedIn, false);
			setTimeout('hidePersonalizeButton()', 10000);
		} else {
			goToCart();
		}
	}
}

function doOnSaveItemsToCartFailure(response, openDOL, isLoggedIn){
	alert('There was an error saving the items to the cart.');
}

function hidePersonalizeButton(){
	if($('loadingDOLText') != null){
		$('loadingDOLText').hide();
		$('addToCartDOL').removeClassName('visibilityHidden');
	}
}

function setUpCurrency(){
	var currency = getCookie('mgstCurrency');
	
	/*if(currentCurrency != null && currentCurrency == 'USD'){
		new Effect.Fade($('CDNFlag'), {duration: 0.3, to: 0.5});
	} else if(currentCurrency != null && currentCurrency == 'CDN') {
		new Effect.Fade($('USFlag'), {duration: 0.3, to: 0.5});
	}
	
	if($('errorText'))
		new Effect.Highlight($('errorText'), {duration: 2.0});
		*/
}

function showDetailsErrorMessage(errorMessage){
	$('detailsErrorMessage').innerHTML = errorMessage;
	$('detailsErrorMessageContainer').show();
}

/*****************************/
/****** Package Pricing ******/
/*****************************/

function useCDNPackagePricing(){
	currentCurrency = getCookie('mgstCurrency');
	if(currentCurrency != 'CDN'){
		var cdnObjects = $$('.cdnPricing');
		var len = cdnObjects.length;
		for(var i = 0; i<len; i++){
			cdnObjects[i].show();	
		}
		
		if($('currencyTag') != null){
			$('currencyTag').innerHTML = "CDN";
		}
		//new Effect.Appear($('CDNFlagDown'), {duration: 0.3, to: 1.0, queue: 'parallel'});
		//new Effect.Fade($('CDNFlag'), {duration: 0.3, to: 0.5, queue: 'parallel'});
		new Effect.BlindDown($('CDNPricingDisclaimer'), {duration: 0.3});
		$('CDNFlag').removeClassName('currentCurrency');
		$('CDNFlag').addClassName('otherCurrency');
		$('CDNFlagDown').removeClassName('otherCurrency');
		$('CDNFlagDown').addClassName('currentCurrency');
		setCookie('mgstCurrency', 'CDN', getExpDate(1,0,0), '/');
		
		var numOfProducts = $F('numOfProducts');
		var quantitySelects = $$('.detailsQuantitySelect');
		for(var j=0; j<numOfProducts; j++){
			eval('currentPricingArray_' + j + ' = CDNPricingArray_' + j);
			updateDetailsItem(quantitySelects[j],j, false, false);
		}
		updateDetailsTotal();		
	}
}

function useUSDPackagePricing(){
	currentCurrency = getCookie('mgstCurrency');
	if(currentCurrency != 'USD'){
		var cdnObjects = $$('.cdnPricing');
		var len = cdnObjects.length;
		for(var i = 0; i<len; i++){
			cdnObjects[i].hide();	
		}
		
		if($('currencyTag') != null){
			$('currencyTag').innerHTML = "USD";
		}
		//new Effect.Fade($('CDNFlagDown'), {duration: 0.3, to: 0.5, queue: 'parallel'});
		//new Effect.Appear($('CDNFlag'), {duration: 0.3, to: 1.0, queue: 'parallel'});
		new Effect.BlindUp($('CDNPricingDisclaimer'), {duration: 0.3});
		$('CDNFlag').removeClassName('otherCurrency');
		$('CDNFlag').addClassName('currentCurrency');
		$('CDNFlagDown').removeClassName('currentCurrency');
		$('CDNFlagDown').addClassName('otherCurrency');
		setCookie('mgstCurrency', 'USD', getExpDate(1,0,0), '/');
		
		var numOfProducts = $F('numOfProducts');
		var quantitySelects = $$('.detailsQuantitySelect');
		for(var j=0; j<numOfProducts; j++){
			eval('currentPricingArray_' + j + ' = USDPricingArray_' + j);
			updateDetailsItem(quantitySelects[j],j, false, false);
		}
		updateDetailsTotal();
	}
}


function updateDetailsMainItem(quantitySelect, highlightRow, updateTotal){
	var tbl = $('detailsPricingSubTable');
	tempDetailsRow = tbl.rows[1];	
	var newPerPiece;
	var newTotal;
	var newQuantity;
	var len = currentPricingArray_0.length;
	if(len == 1){
		newPerPiece = currentPricingArray_0[0][2];
		if(getCookie('mgstCurrency') == "USD"){
			newPerPiece = newPerPiece.toFixed(2);
		}
		
		newTotal = (quantitySelect.value * newPerPiece).toFixed(2);
	} else {
		for(i=0; i<len; i++){
			if(quantitySelect.value <= currentPricingArray_0[i][1]){
				newPerPiece = currentPricingArray_0[i][2];
				if(getCookie('mgstCurrency') == "USD"){
					newPerPiece = newPerPiece.toFixed(2);
				}
				newTotal = (quantitySelect.value * newPerPiece).toFixed(2);
				break;
			}
		}
	}
	
	newQuantity = Math.round(newQuantity);

	$('pricePerPiece_0').innerHTML = newPerPiece;
	$('priceTotal_0').innerHTML = newTotal;			
	if(updateTotal == true && $('priceTotal')){
		updateDetailsTotal();
	}
	
	if(highlightRow == true){
		new Effect.Highlight(tempDetailsRow, {duration: 2.0});
	}
}

function updateDetailsItem(quantitySelect, detailsRowToUpdate, highlightRow, updateTotal){
	var tbl = $('detailsPricingSubTable');
	tempDetailsRow = tbl.rows[detailsRowToUpdate+2];	
	var newPerPiece;
	var newTotal;
	var newQuantity;
	var len = eval('currentPricingArray_' + detailsRowToUpdate).length;
	if(len == 1){
		newPerPiece = eval('currentPricingArray_' + detailsRowToUpdate)[0][2];
		if(getCookie('mgstCurrency') == "USD"){
			newPerPiece = newPerPiece.toFixed(2);
		}
		newTotal = (quantitySelect.value * newPerPiece).toFixed(2);
	} else {
		for(i=0; i<len; i++){
			if(quantitySelect.value <= eval('currentPricingArray_' + detailsRowToUpdate)[i][1]){
				newPerPiece = eval('currentPricingArray_' + detailsRowToUpdate)[i][2];
				if(getCookie('mgstCurrency') == "USD"){
					newPerPiece = newPerPiece.toFixed(2);
				}
				newTotal = (quantitySelect.value * newPerPiece).toFixed(2);
				break;
			}
		}
	}
	
	newQuantity = Math.round(newQuantity);

	$('pricePerPiece_' + detailsRowToUpdate).innerHTML = newPerPiece;
	$('priceTotal_' + detailsRowToUpdate).innerHTML = newTotal;			
	if(updateTotal == true && $('priceTotal')){
		updateDetailsTotal();
	}
	
	if(highlightRow == true){
		new Effect.Highlight(tempDetailsRow, {duration: 2.0});
	}
}

function updateDetailsTotal(){
	totals = $$('.detailsTotal');
	var len = totals.length;
	var newTotal = 0;
	for(i=0; i<len; i++){
		newTotal = newTotal + parseFloat(totals[i].innerHTML);
	}
	if($('priceTotal') != null){
		$('priceTotal').innerHTML = newTotal.toFixed(2);
	}
}

var changeLargeImageThumbnailImg;
function changeLargeImage(thumbnailImg){
	new Effect.Fade($('detailsLargePhoto'), {queue: 'front', duration: 0.3, to: 0.1});
	changeLargeImageThumbnailImg = thumbnailImg;
	updateIndicators(thumbnailImg.id);
	setTimeout('replaceLargeImageSrc()', 300);
}

function replaceLargeImageSrc(){
	var thumbnailSrc = changeLargeImageThumbnailImg.src;
	var largeImageSrc = thumbnailSrc.replace("_xs", "");
	$('detailsLargePhoto').src = largeImageSrc;
	$('detailsLargePhoto').title = changeLargeImageThumbnailImg.title.replace("View larger ", "");
	$('productPreviewName').innerHTML = changeLargeImageThumbnailImg.title.replace("View larger ", "");
	setTimeout('showLargeImage()', 300);
}

function showLargeImage(){
	new Effect.Appear($('detailsLargePhoto'), {queue: 'front', duration: 0.3});
	
	if($('productImageControls') != null){
		if(changeLargeImageThumbnailImg.hasClassName('productImage')){
			$('productImageControls').removeClassName('visibilityHidden');
		} else {
			$('productImageControls').addClassName('visibilityHidden');
		}
	}
	simpleImageChangerIndex = -1;
}

function updateIndicators(selectedId){
	var tableIndicatorObjects = $$('.tableIndicator');
	var len = tableIndicatorObjects.length;
	for(var i = 0; i<len; i++){
		if(tableIndicatorObjects[i].id == (selectedId + "TableIndicator")){
			tableIndicatorObjects[i].removeClassName('visibilityHidden');
		} else {
			tableIndicatorObjects[i].addClassName('visibilityHidden');
		}	
	}
	
	var thumbnailIndicatorObjects = $$('.thumbnailIndicator');
	len = thumbnailIndicatorObjects.length;
	for(i = 0; i<len; i++){
		if(thumbnailIndicatorObjects[i].id == (selectedId + "Indicator")){
			thumbnailIndicatorObjects[i].removeClassName('visibilityHidden');
		} else {
			thumbnailIndicatorObjects[i].addClassName('visibilityHidden');
		}	
	}
}


