// JavaScript Document
//  Javascripts - Scripts on the productArea - view product page layouts
// Sleeping Giant Studios, LLC
// Created by David Ellenwood - 12/13/2006


/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FUNCTIONS TO CONTROL THE INFORMATIONAL TASK (TAB) SWITCHING EVENTS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

// Function to set the initial task on the page
function setInfoTabsTask() {
	
	// Get the currently set task from the page URL
	var currentTask = window.location.hash.replace(/#/,"");
	
	// Make sure the current task is one of the correct tabs
	if(!(currentTask == 'overview' || currentTask == 'customize' || currentTask == 'giftWrap')) 
		{
			currentTask = 'overview';
		}


	
	// Set the onclick event for the task buttons
	btns = document.getElementById('prodInfoTabs').getElementsByTagName('a');
	for(var x=0; x<btns.length; x++) {
		btns[x].onclick = infoTaskSwitch;
	}
	
	// Switch to the current task
	infoTaskSwitch(currentTask);
}


// Function to switch between the different options on a page
function infoTaskSwitch(currentTask) {
	
	// Figure out which task is supposed to be selected
	if(this.href)	var taskToShow	= this.href.match(/#.+$/)[0].replace(/#/,"");
	else 			var taskToShow	= currentTask;
		
	// Collect all the buttons, set their IDs to null and set the correct one to 'selectedBtn'
	btns = document.getElementById('prodInfoTabs').getElementsByTagName('a');
	for(var x=0; x<btns.length; x++) {
		if(btns[x].className == 'tabBtn')								btns[x].id = '';
		if(btns[x].href.match(/#.+$/)[0].replace(/#/,"") == taskToShow) btns[x].id = 'selectedBtn';
	}
	
	// Collect all the DIVs on the page, hide all the task DIVs then show the one that we want to see
	var divs = document.getElementsByTagName('div');
	for(var w=0; w<divs.length; w++) {
		if(divs[w].className == 'prodInfoTab')	divs[w].style.display = 'none';
		if(divs[w].id == taskToShow)			divs[w].style.display = 'block';
	}

}	// End function infoTaskSwitch


/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FUNCTIONS TO CONTROL THE VISUAL TASK (TAB) SWITCHING EVENTS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

// Function to set the initial task on the page
function setImgTabsTask() {
	
	// Get the currently set task from the page URL
	var currentTask = window.location.hash.replace(/#/,"");
	
	// Make sure the current task is one of the correct tabs
	if(!(currentTask == 'images' || currentTask == 'view3D')) {
		currentTask = 'images';
	}
	
	// Set the onclick event for the task buttons
	btns = document.getElementById('prodImageTabs').getElementsByTagName('a');
	for(var x=0; x<btns.length; x++) {
		btns[x].onclick = imgTaskSwitch;
	}

	// Attach onclick events to the close view links
	var anchors = document.getElementsByTagName("a");
	for(var a=0; a<anchors.length; a++) {
		if(anchors[a].className == "closeBtn") {
			anchors[a].onclick = imgTaskSwitch;
		}
	}

	// Switch to the current task
	imgTaskSwitch(currentTask);
}


// Function to switch between the different options on a page
function imgTaskSwitch(currentTask) {
	
	// Figure out which task is supposed to be selected
	if(this.href)	var taskToShow	= this.href.match(/#.+$/)[0].replace(/#/,"");
	else 			var taskToShow	= currentTask;
		
	// Collect all the buttons, set their IDs to null and set the correct one to 'selectedBtn'
	btns = document.getElementById('prodImageTabs').getElementsByTagName('a');
	for(var x=0; x<btns.length; x++) {
		if(btns[x].className == 'tabBtn')								btns[x].id = '';
		if(btns[x].href.match(/#.+$/)[0].replace(/#/,"") == taskToShow) btns[x].id = 'selectedBtn';
	}
	
	// Collect all the DIVs on the page, hide all the task DIVs then show the one that we want to see
	var divs = document.getElementsByTagName('div');
	for(var w=0; w<divs.length; w++) {
		if(divs[w].className == 'prodImageTab')	divs[w].style.display = 'none';
		if(divs[w].id == taskToShow)			divs[w].style.display = 'block';
	}

}	// End function imgTaskSwitch


/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FUNCTIONS TO CONTROL THE IMAGE SELECTION EVENTS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

// Switches the image currently displayed on the page.
function selectImage() {
	var displayImage	= document.getElementById('displayImage');
	var viewDetailLink1	= document.getElementById('viewDetailLink1');
	var viewDetailLink2	= document.getElementById('viewDetailLink2');
	if(BrowserDetect.browser == 'Explorer') {
		var zoomImgLink		= this.childNodes[0].src.replace(/w70/,"w700");
		zoomImgLink			= zoomImgLink.replace(/_sq/,"");
		displayImage.src	= this.childNodes[0].src.replace(/w70/,"w440");
		displayImage.src	= displayImage.src.replace(/_sq/,"");
	}
	else {
		var zoomImgLink		= this.childNodes[1].src.replace(/w70/,"w700");
		zoomImgLink			= zoomImgLink.replace(/_sq/,"");
		displayImage.src	= this.childNodes[1].src.replace(/w70/,"w440");
		displayImage.src	= displayImage.src.replace(/_sq/,"");
	}
	viewDetailLink1.href = zoomImgLink
	viewDetailLink2.href = zoomImgLink

}

// Function to set the initial image and image events
function setImages() {
	var thumbs = document.getElementById('imageThumbs').getElementsByTagName('a');
	
	for(var x=0; x<thumbs.length; x++) {
		thumbs[x].onclick = selectImage;
	}

}

// Opens a window for the large image viewer
function openCenteredWindow(fileLocation, winName, winDressing, winWidth, winHeight)
{
	if (winWidth == null) winWidth = 500;
	if (winHeight == null) winHeight = 350;
	var winLeft = (screen.width - winWidth) / 2;
	var winTop = (screen.height - winHeight) / 2;
	var features = 'height='+winHeight+',width='+winWidth+',top='+winTop+',left='+winLeft+','+winDressing;
	
	win = window.open(fileLocation, winName, features)
	
	if (parseInt(navigator.appVersion) >= 4) { win.window.focus(); }
}


/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FUNCTIONS TO CONTROL THE PRODUCT ATTRIBUTE HOVER AND SELECTION EVENTS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

function select(attributeId,attributeContainer,titleId,selectedTitleId,inputId) {
	if(document.getElementById) {
		var attribute		= document.getElementById(attributeId);
		var attributeText	= attribute.title;
		var container		= document.getElementById(attributeContainer);
		var attributes		= container.getElementsByTagName('a');
		var titleBox		= document.getElementById(titleId);
		var selectedBox		= document.getElementById(selectedTitleId);
		var inputField		= document.getElementById(inputId);
		
		for(var i=0; i<attributes.length; i++){
			attributes[i].className = '';
			if(attributes[i].id == attributeId){
				attributes[i].className = 'selected';
			}
		}
		
		titleBox.innerHTML		= attributeText;
		selectedBox.innerHTML	= attributeText;
		inputField.value		= attributeText;
				
	} else {return;}
}

function select_DD(attributeId,attributeContainer,titleId,selectedTitleId,inputId) {
	if(document.getElementById) {
		var attribute		= document.getElementById(attributeId);
		var attributeText	= attribute.value;
		var selectedBox		= document.getElementById(selectedTitleId);
		var inputField		= document.getElementById(inputId);
		
		if(attributeText != "-1") {
			selectedBox.innerHTML	= attributeText;
			inputField.value		= attributeText;
		}
		else {
			selectedBox.innerHTML	= "";
			inputField.value		= "";
		}
				
	} else {return;}
}

function updateSelectedBox() {
	if(document.getElementById) {
		if(document.getElementById("sizeInputValue").value != "-1" && document.getElementById("colorInputValue").value != "-1") {
			var selectedSize = document.getElementById("selectedSize")
			var selectedColor = document.getElementById("selectedColor")
	
			selectedSize.innerHTML = document.getElementById("sizeInputValue").value
			selectedColor.innerHTML = document.getElementById("colorInputValue").value
		} 
	} else {return;}
}

function over(attributeId,titleId) {
	if(document.getElementById) {
		var attribute		= document.getElementById(attributeId);
		var attributeText	= attribute.title;
		var titleBox		= document.getElementById(titleId);
		titleBox.innerHTML	= attributeText;
	} else {return;}
}

function out(titleId,selectedTitleId) {
	if(document.getElementById) {
		var titleBox		= document.getElementById(titleId);
		var selectedBox		= document.getElementById(selectedTitleId);
		titleBox.innerHTML 	= selectedBox.innerHTML;
	} else {return;}
}

function editState(elementId,disabledState,classState){
	if(document.getElementById) {
		var container 		=	document.getElementById(elementId);
		container.disabled	=	disabledState;
		container.className = 	classState;
		container.value		=	'Add to Cart';
	}
}

function editState_DD(elementId){
	if(document.getElementById) {
		if(document.getElementById("prodPrice").innerHTML != 'Call or e-mail for discount price') {
			if(document.getElementById("sizeInputValue").value != "-1" && document.getElementById("colorInputValue").value != "-1") {
				var container 		=	document.getElementById(elementId);
				container.disabled	=	false;
				container.className = 	'submitBtn';
				container.value		=	'Add to Cart';
			}
			else {
				var container 		=	document.getElementById(elementId);
				container.disabled	=	true;
				container.className = 	'submitBtnDisabled';
				container.value		=	'Select a Product';
			}			
		}
		else {
				var container 		=	document.getElementById(elementId);
				container.disabled	=	true;
				container.className = 	'submitBtnDisabled';
				container.value		=	'Select a Product';
				container.style.display = 'none';

		}
	}
}

function editTagInnerHTMLFromTagInnerHTML(elementFromId,elementToId){
	if(document.getElementById) {
		var elementFrom		= document.getElementById(elementFromId);
		var elementTo		= document.getElementById(elementToId);
		elementTo.innerHTML = elementFrom.innerHTML;
	}
}


/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FUNCTIONS FOR THE CUSTOMIZE (EBROIDERY) EVENTS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

// Sets the initial Embroidery State
function setEmbroidery() {
	
	if(document.getElementById('customize')) {

		// Set events for the embroidery form
		document.getElementById('embroideryTextBox').onkeyup	= checkEmbroidery;
		document.getElementById('embroideryTextFont').onchange	= switchFont;
		document.getElementById('embroideryBtn').onclick		= addEmbroidery;
		document.getElementById('embroideryRemoveBtn').onclick	= removeEmbroidery;
		document.getElementById('inputEmbroidery').value		= 'false';
		document.getElementById('inputGiftWrap').value 			= 'false';
		
		// set the inital state for the embroidery form
		checkEmbroidery();
		switchFont();
		
	}

} // End setEmbroidery Function

// Checks to see that embroidery form contains text and that text is less than the maxlength
function checkEmbroidery() {
	var textField	= document.getElementById('embroideryTextBox');
	var addBtn		= document.getElementById('embroideryBtn');
	var maxChars	= textField.getAttribute('maxlength');
	if((textField.value.length > 0) && (textField.value.length <= maxChars)) {
		addBtn.disabled = false;
		addBtn.className = 'submitBtn';
	} else {
		addBtn.disabled = true;
		addBtn.className = 'submitBtnDisabled';
	}
} // End checkEmbroidery Funtion

// Changes the selected font for the Embroidery textfield
function switchFont() {
	var textField	= document.getElementById('embroideryTextBox');
	var fontOptions	= document.getElementById('embroideryTextFont');
	//alert(fontOptions.length);
	for(var x=0; x<fontOptions.length; x++) {
		//alert(fontOptions[x].value);
		if(fontOptions[x].selected) {
			textField.style.fontFamily = fontOptions[x].value;
		}
	}
} // End switchFont function

function addEmbroidery() {
	
	var textFieldValue	= document.getElementById('embroideryTextBox').value;
	var prodPrice		= document.getElementById('prodPrice').innerHTML.replace(/\$/,"");
	var embroideryTotal	= document.getElementById('selectedEmbroidery');
	var totalLine		= document.getElementById('totalLine');
	var totalPrice		= document.getElementById('totalPrice');
	var totalTitle		= document.getElementById('totalTitle');
	var embroideryInput	= document.getElementById('inputEmbroidery');
	var giftWrapInput	= document.getElementById('inputGiftWrap');
	var embroideryCost	= 7.70;
	var giftWrapCost	= 10.00;
	var total 			= (prodPrice*1)+embroideryCost;
	
	// Check and add gift wrap cost to total price if necessary
	if(giftWrapInput.value == 'true') total=(total*1)+giftWrapCost; 
	
	// Fill the correct values into the correct fields
	document.getElementById('EmbroideryText').innerHTML = textFieldValue;
	embroideryInput.value = 'true';
	totalPrice.innerHTML = '$'+total.toFixed(2);

	// Set the display property to block for the correct items
	embroideryTotal.style.display	= 'block';
	totalLine.style.display			= 'block';
	totalPrice.style.display		= 'block';
	totalTitle.style.display		= 'block';

} // End addEmbroidery function

function removeEmbroidery() {

	var prodPrice		= document.getElementById('prodPrice').innerHTML.replace(/\$/,"");
	var embroideryTotal	= document.getElementById('selectedEmbroidery');
	var totalLine		= document.getElementById('totalLine');
	var totalPrice		= document.getElementById('totalPrice');
	var totalTitle		= document.getElementById('totalTitle');
	var embroideryInput	= document.getElementById('inputEmbroidery');
	var giftWrapInput	= document.getElementById('inputGiftWrap');
	var embroideryCost	= 7.70;
	var giftWrapCost	= 10.00;
	
	// Check and add gift wrap cost to total price if necessary
	if(giftWrapInput.value == 'true') prodPrice=(prodPrice*1)+giftWrapCost; 
	
	// Fill the correct values into the correct fields
	document.getElementById('EmbroideryText').innerHTML = '';
	embroideryInput.value = 'false';
	totalPrice.innerHTML = '$'+(prodPrice*1).toFixed(2);

	// Set the display property to none for the correct items
	embroideryTotal.style.display	= 'none';
	
	if(giftWrapInput.value == 'false') { 
		totalLine.style.display		= 'none';
		totalPrice.style.display	= 'none';
		totalTitle.style.display	= 'none';
	}

} // End removeEmbroidery function

/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FUNCTIONS FOR THE GIFT WRAPPING EVENTS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

// Sets the initial gift wrap state
function setGiftWrap() {
	
	if(document.getElementById('giftWrap')) {
	
		// Set events for the gift wrap form
		document.getElementById('giftWrapBtn').onclick			= addGiftWrap;
		document.getElementById('GiftWrapRemoveBtn').onclick	= removeGiftWrap;
		document.getElementById('inputEmbroidery').value		= 'false';
		document.getElementById('inputGiftWrap').value			= 'false';
		setMaxLength();		// Initializes the character counter
		
	}

} // End setGiftWrap function


// Displays the number of characters used/allowed each time a key is released.
function setMaxLength() {

	var x = document.getElementsByTagName('textarea');
	var counter = document.createElement('div');
	counter.className = 'counter';
	for (var i=0;i<x.length;i++) {
		if (x[i].getAttribute('maxlength')) {
			var counterClone = counter.cloneNode(true);
			counterClone.relatedElement = x[i];
			counterClone.innerHTML = 'Characters used: <span>0</span> of '+x[i].getAttribute('maxlength');
			x[i].parentNode.insertBefore(counterClone,x[i].nextSibling);
			x[i].relatedElement = counterClone.getElementsByTagName('span')[0];
			x[i].onkeyup = x[i].onchange = checkMaxLength;
			x[i].onkeyup();
		}
	}
	
} // End setMaxLength function

// Checks the number of characters entered.
// If more than the maxlength, then added a class to the character count
function checkMaxLength() {

	var maxLength = this.getAttribute('maxlength');
	var currentLength = this.value.length;
	var addBtn = document.getElementById('giftWrapBtn');
	if (currentLength > maxLength) {
		this.relatedElement.className = 'alert';
		addBtn.disabled = true;
		addBtn.className = 'submitBtnDisabled';
	} else {
		this.relatedElement.className = '';
		addBtn.disabled = false;
		addBtn.className = 'submitBtn';
	}
	this.relatedElement.firstChild.nodeValue = currentLength;
	// not innerHTML
	
} // End checkMaxLength function


function addGiftWrap() {
	
	var textFieldValue	= document.getElementById('giftWrapTextBox').value;
	var prodPrice		= document.getElementById('prodPrice').innerHTML.replace(/\$/,"");
	var giftWrapTotal	= document.getElementById('selectedGiftWrap');
	var totalLine		= document.getElementById('totalLine');
	var totalPrice		= document.getElementById('totalPrice');
	var totalTitle		= document.getElementById('totalTitle');
	var embroideryInput	= document.getElementById('inputEmbroidery');
	var giftWrapInput	= document.getElementById('inputGiftWrap');
	var embroideryCost	= 7.70;
	var giftWrapCost	= 10.00;
	var total 			= (prodPrice*1)+giftWrapCost;
	
	// Check and add gift wrap cost to total price if necessary
	if(embroideryInput.value == 'true') total=(total*1)+embroideryCost; 
	
	// Fill the correct values into the correct fields
	document.getElementById('GiftWrapText').innerHTML = textFieldValue;
	giftWrapInput.value = 'true';
	totalPrice.innerHTML = '$'+total.toFixed(2);
	
	// Set the display property to block for the correct items
	giftWrapTotal.style.display		= 'block';
	totalLine.style.display			= 'block';
	totalPrice.style.display		= 'block';
	totalTitle.style.display		= 'block';

} // End addGiftWrap function

function removeGiftWrap() {

	var prodPrice		= document.getElementById('prodPrice').innerHTML.replace(/\$/,"");
	var giftWrapTotal	= document.getElementById('selectedGiftWrap');
	var totalLine		= document.getElementById('totalLine');
	var totalPrice		= document.getElementById('totalPrice');
	var totalTitle		= document.getElementById('totalTitle');
	var embroideryInput	= document.getElementById('inputEmbroidery');
	var giftWrapInput	= document.getElementById('inputGiftWrap');
	var embroideryCost	= 7.70;
	var giftWrapCost	= 10.00;
	
	// Check and add gift wrap cost to total price if necessary
	if(embroideryInput.value == 'true') prodPrice=(prodPrice*1)+embroideryCost; 
	
	// Fill the correct values into the correct fields
	document.getElementById('GiftWrapText').innerHTML = '';
	giftWrapInput.value = 'false';
	totalPrice.innerHTML = '$'+(prodPrice*1).toFixed(2);

	// Set the display property to none for the correct items
	giftWrapTotal.style.display	= 'none';
	
	if(embroideryInput.value == 'false') { 
		totalLine.style.display		= 'none';
		totalPrice.style.display	= 'none';
		totalTitle.style.display	= 'none';
	}

} // End removeGiftWrap function

function updateProductInformation(intPricingID) {
	var strColorValue, strSizeValue, strPricingValue, strImageCode
	var blnDisplayImage_updated = false
	strColorValue = $('#color'+intPricingID).val()
	strSizeValue = $('#size'+intPricingID).val()
	strPricingValue = $('#PricingSell'+intPricingID).val()
	strImageCode = $('#code'+intPricingID).val()
	//Set color/size
	$('#colorInputValue').val(strColorValue);
	$('#sizeInputValue').val(strSizeValue);
	
	//show correct images
	$('#imageThumbs').children().each( 
	  function(){
	    //access to form element via $(this)
	    if($(this).attr("id").indexOf(strImageCode) >= 0) {
			$(this).css({display:""}) 
			if(blnDisplayImage_updated == false) {
				$('#displayImage').css({display:""});
				if(strImageCode != "") {
					var displayImgSrc	= $('#thumbnail_'+strImageCode).attr("src").replace(/w70/,"w440");
					displayImgSrc		= displayImgSrc.replace(/_sq/,"");
					$('#displayImage').attr("src",displayImgSrc);
					$('#viewDetailLink1').attr("href",displayImgSrc.replace(/w440/,"w700"));
					$('#viewDetailLink2').attr("href",displayImgSrc.replace(/w440/,"w700"));
				}
				blnDisplayImage_updated = true;
			}
	    }
	    else {
	    	$(this).css({display:"none"})
	    }
	    
	  }
	);

	//set item code:
	$('#prodCodeValue').html(strImageCode);
	
	//set item price 
	$('#prodPrice').html(strPricingValue);
}

function IsNumeric(sText)

{
   var ValidChars = "0123456789.";
   var IsNumber=true;
   var Char;

 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
   }


/*
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FUNCTION TO INITIALIZE THE PAGE
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*/

$(document).ready(function(){
	setInfoTabsTask();	// Setup the task (tab) switching for the info tabs (Overview, Embroidery, Gift Wrapping)
	setImgTabsTask();	// Setup the task (tab) switching for the image tabs (Images, 3D View)
	setImages();		// Setup the images tab
	setEmbroidery();	// Setup the embroifery form
	setGiftWrap();		// Setup the gift wrapping form
	updateProductInformation($("#ddl_options :selected").val());
	editState_DD('addToCartSubmitBtn');
	
	//$("#displayImg .jqzoom").jqueryzoom({xzoom:330,yzoom:280,offset:0,position:"left",preload:0}); // Initiates the magnifier/close-up image functions
});
