var hitButton;
var xPosOfCarWidget;
var yPosOfCartWidget;





/*-------------------------------------------------------------------------------------------------
yahoo curve animation
-------------------------------------------------------------------------------------------------*/
function curve(whichButton,qty) {

	// Only do this if the demo div isn't in the document...ie if another animation isn't running
	if(!document.getElementById("demo")) {

		// Set this global variable so we can reference it later in the replace1up function
		hitButton = whichButton;
		
		// Where exactly is our cart widget? This is where we throw the bubble
		xPosOfCarWidget = findPosX(document.getElementById("results_refreshCartWidget"));
		yPosOfCarWidget = findPosY(document.getElementById("results_refreshCartWidget"));
	
		// Is the x position of this add to cart button greater than the button thats before it? and on the same Y level
		thisButtonX 	= findPosX(document.getElementById("addToCart_" + whichButton));
		thisButtonY     = findPosY(document.getElementById("addToCart_" + whichButton));
		
		// LEFT OR RIGHT?
			// Where is the button positioned in relation to the cart widget? To the left or the right?
			controlX = thisButtonX - xPosOfCarWidget;
			
			// If buttons are stacked (ex. premium mailers) we want the top one to go left and the bottom one to go right
			// Get previous button x pos.
			previousButton = whichButton - 1;
			if(document.getElementById("addToCart_" + previousButton)) { // Only attempt to do this if there actually is a previous button
				previousButtonX = findPosX(document.getElementById("addToCart_" + previousButton));
			}
			else { // If there isn't just set it to 0
				previousButtonX = 0;
			}
			
			// Go Left - if buttonx is less than widget x and this button isn't lined up with the button above
		    //if(whichButton % 2 != 0) { 
			if(controlX < 0 && previousButtonX != thisButtonX) { 
				shakeDirection = 5;
				controlX = xPosOfCarWidget - 120; // Go left 120px from left side of cart
			}
			// Go Right
			else {
				shakeDirection = -5;
				controlX = xPosOfCarWidget + 120 + 120; // Go right 120px from right side of cart. Extra 120 is added because thats the width of the widget. so x + width = y
			}
	
		// The html we'll put in the new bubble
		var bubble = "<div style='position:absolute; z-index:0; left:35px; color:white; background-image:url(/store/awesomeness/images/oneUp.gif); width:30px; height:30px; margin-bottom:1em;'>";
		bubble 	  += "<div style='padding:2px; padding-top:4px; font-family:lucida grande; font-weight:800;'>+"+qty+"<\/div>";
		bubble    += "<\/div>";
		
		// Create our new bubble div
		var newBubble 		     = document.createElement("div");
		newBubble.id 		     = "demo";
		newBubble.style.zIndex   = 60;
		newBubble.style.position = "absolute";
		newBubble.style.width    = 99;
		newBubble.style.height   = 37;
		newBubble.style.top      = -37;
		newBubble.style.left     = 0;
		
		// Append new bubble div to the document / add to cart button
		whichAddToCart = document.getElementById("addToCart_" + whichButton);
		whichAddToCart.appendChild(newBubble);
		
		// Insert our html into this div we just created
		newBubble.innerHTML = bubble;
	
		var attributes = {
			points: { to: [xPosOfCarWidget, 40], control: [ [controlX, -120] ] }
		};
		
		// Setup animation object
		var anim = new YAHOO.util.Motion('demo', attributes);
		
		// Set duration
		anim.duration = .75; 
		
		// Set ease
		anim.method = YAHOO.util.Easing.easeOut;
		
		// Set complete action - fade it out
		anim.onComplete.subscribe(fadeOut1up);
		
		// For every frame, see how close we are to the end so we know when to fire the shake
		anim.onTween.subscribe(function() { 
			
			// Shake between the windows of 175-150 frames before completion
			if(anim.currentFrame > anim.totalFrames - 175 && anim.currentFrame < anim.totalFrames - 150) {
				shake(shakeDirection);
			}
			 
		});
		
		// Move it!
		anim.animate();
		
	} // end demo div not existing

}




// ^^
/*-------------------------------------------------------------------------------------------------
after curve is done, fade out the 1up
-------------------------------------------------------------------------------------------------*/

function fadeOut1up() {

	// Fade out
	var attributes = {  opacity: {from: 1, to: 0 }  }	
	var ani = new YAHOO.util.Anim('demo' , attributes, 0, YAHOO.util.Easing.easeNone);
	ani.onComplete.subscribe(replace1up);
	ani.animate(); 
	
}


// ^^
/*-------------------------------------------------------------------------------------------------
shake() shake the cart widget
-------------------------------------------------------------------------------------------------*/
function shake(shakeDirection) {

	// Where's the cart at this moment? 
	cartNowY = findPosY(document.getElementById("results_refreshCartWidget"));
	
	/// Only if the cart now is where it should be do we shake it
	if(cartNowY == yPosOfCarWidget) {
		var attributes = {
			points: { to: [xPosOfCarWidget, yPosOfCarWidget], control: [ [xPosOfCarWidget + shakeDirection ,yPosOfCarWidget + 5] ] }
		};
		var shake = new YAHOO.util.Motion('results_refreshCartWidget', attributes);
		shake.duration = .1; 
		shake.method = YAHOO.util.Easing.easeOut;
		shake.method = YAHOO.util.Easing.easeOut;				 
		shake.animate();
		
	}
	
	
}

// ^^
/*-------------------------------------------------------------------------------------------------
replace 1up
-------------------------------------------------------------------------------------------------*/
function replace1up() {
	whichAddToCart = document.getElementById("addToCart_" + hitButton);
	whichAddToCart.removeChild(document.getElementById('demo'));	
}




/*-------------------------------------------------
clearAllErrors
--------------------------------------------------*/
function clearAllErrors() {

	var arrayOfDivs = document.getElementsByTagName('div');
	
	for (var i = 0; i < arrayOfDivs.length; i++){
		if (arrayOfDivs[i].className == "errorTab"){
			arrayOfDivs[i].style.display = "none";
		}
	}

}




/*-------------------------------------------------
toggleStockMessage
--------------------------------------------------*/
function toggleStockMessage(buttonCounter) {
	
	var theDropdown = document.getElementById("selectOption_" + buttonCounter);
	var n           = theDropdown.selectedIndex;     		
	var optionId    = theDropdown[n].value;  

	// Grab the stock message from the hidden field which holds it
	stockMessage    = document.getElementById("stockMessageHolder_" + optionId).value;
	
	// Now put it in the div for line 0 (may be blank)
	document.getElementById("buttonStockMessageLine0_" + buttonCounter).innerHTML = stockMessage;
	
	// Turn off the "We'll letcha know" line in case it was on
	document.getElementById("buttonStockMessageLine2_" + buttonCounter).style.display = "none";
	
	// Determine whether to turn on line 1 (notify me link)
	blockOrNone = (stockMessage != "") ? "block" : "none";
	
	document.getElementById("buttonStockMessageLine1_" + buttonCounter).style.display = blockOrNone; 
	document.getElementById("buttonStockMessage_" + buttonCounter).style.display      = blockOrNone;

}




/*-------------------------------------------------
notifyMePopup
--------------------------------------------------*/
function notifyMePopup(optionIdOrDropdown,linkObj,buttonCounter) {
	
	// optionIdOrDropdown will be either the optionId number or something like "select_3" where three is the drop down id count
	
	// If it's just a number, then it's the optionId
	if(optionIdOrDropdown == parseInt(optionIdOrDropdown)) {
		var optionId = optionIdOrDropdown;
	}
	// Otherwise 
	else {		
		optionIdOrDropdown = optionIdOrDropdown.replace("select_", "");
		var theDropdown        = document.getElementById("selectOption_" + optionIdOrDropdown);
		var n                  = theDropdown.selectedIndex;     		
		var optionId           = theDropdown[n].value;  
	} 
	
	var popup = document.getElementById('notifyMePopup');
	
	// Find out where the notify link is 
	xPosLink = findPosX(linkObj);
	yPosLink = findPosY(linkObj);
	
	// Position and turn on the popup
	popup.style.display = "block";
	popup.style.left     = xPosLink - 281;
	popup.style.top      = yPosLink - 80;
	
	// Insert the sku in the hidden field
	document.getElementById("notifyOptionId_hidden").value = optionId;
	document.getElementById("buttonCounter_hidden").value  = buttonCounter;
		
}




/*-------------------------------------------------
submitNotifyMe
--------------------------------------------------*/
function submitNotifyMe() {

	// Variables
	var email         = document.getElementById("notifyEmail").value;
	var optionId      = document.getElementById("notifyOptionId_hidden").value;
	var buttonCounter = document.getElementById("buttonCounter_hidden").value;

	// Email test
	var filter=/^.+@.+\..{2,4}$/
	
	// Fail
	if (!filter.test(email) || email == "you@email.com") {
		document.getElementById("notifyEmail").style.backgroundImage = "url(/store/checkout/images/field-status-pink.jpg)";
	}
	// Pass
	else {
		// Clear the error background
		document.getElementById("notifyEmail").style.backgroundImage = "";
		
		// Close the popup
		document.getElementById('notifyMePopup').style.display = "none";
		
		// Turn on the "We'll letcha know" confirmation
		document.getElementById("buttonStockMessageLine2_" + buttonCounter).style.display = "block";
		
		// Turn off the nofity link
		document.getElementById("buttonStockMessageLine1_" + buttonCounter).style.display = "none";
		
		params     = new Array();i = 0;
		params[i]  = "action=submitNotifyMe"; i++;	
		params[i]  = "email=" + email; i++;
		params[i]  = "optionId=" + optionId; i++;
		putResults = "submitNotifyMe_results";	
		ajaxMagic('product_ajax.php',params,putResults,'','doNotFade');
	}

}




/*-------------------------------------------------
pressAddToCart
Used on the onmousedown and onmouseup event attached
to the add to cart button. 1=up 0=down
--------------------------------------------------*/
function pressAddToCart(whichOne,state) {

	if(state == 0) {
		whichOne.src = '/store/awesomeness/images/addToCart_down.gif';
	}
	else {
		whichOne.src = '/store/awesomeness/images/addToCart.gif';
	}

}




/*-------------------------------------------------
addToCart
--------------------------------------------------*/
function addToCart(buttonCounter,optionId,qty,giftCert) {
	
	clearAllErrors();
	
	// If no optionId is passed we have to grab it from the select
	if(optionId == 0) {
		selectObj    = document.getElementById("selectOption_" + buttonCounter);
		var n        = selectObj.selectedIndex;     // Which menu item is selected
		var optionId = selectObj[n].value;          // Return string value of menu item
		
		// They haven't chosen an option
		if(n == 0) {
			// Throw error
			errorField("selectOption_" + buttonCounter,false,"You need to choose which one you'd like.",1,true);	
			return 0;
		}
	}
	
	
	// Add to cart or move on to check gift certificate function
	if(giftCert) {
		checkGiftCertificate(optionId,qty,buttonCounter);
	} 
	else {
		changeQuantity(optionId,"",qty,"product",buttonCounter); 
		window.scroll(0,0);
		curve(buttonCounter,qty);
	}

}




/*-------------------------------------------------------------------------------------------------
checkGiftCertificate() 
-------------------------------------------------------------------------------------------------*/
function checkGiftCertificate(optionId,theqty,resultPosition) {
	
	// Innocent until proven guilty
	var pass = true;
	
	var toField   = document.getElementById("giftCertTo_input").value;
	var fromField = document.getElementById("giftCertFrom_input").value;
 
	// Make sure To: is filled out
	if(toField == "") {
	
		// Throw error
		errorField("giftCertTo",false,"Don't forget the lucky recipient's name!",1,false);
		
		// Guilty
		pass = false;
		 
	}
	// Make sure To: has only usable characters
	else if(englishOnlyChars(toField) != true) {
		// Throw error
		errorField("giftCertTo",false,"Only letters A-Z and numbers 1-9 please!",1,false);
		
		// Guilty
		pass = false;
	}
	else {
		errorField("giftCertTo",true);
	}
	
	// Make sure From: is filled out
	if(fromField == "") {
		
		// Throw error
		errorField("giftCertFrom",false,"Don't forget to take <br>credit for your gift!",1,false);
		
		// Guilty
		pass = false;
	}
	
	// Make sure From: has only usable characters
	else if(englishOnlyChars(fromField) != true) {
		// Throw error
		errorField("giftCertFrom",false,"Only letters A-Z and numbers 1-9 please!",1,false);
		
		// Guilty
		pass = false;
	}
	else {
		errorField("giftCertFrom",true);
	}
	
	
	// Did it pass all tests?
	if(pass == true) {
	
		// Throw a 1up
		curve(resultPosition,1);
		
		// Connect To and From as custom variable
		custom = document.getElementById("giftCertTo_input").value + "_" + document.getElementById("giftCertFrom_input").value;
		
		// Add to cart
		changeQuantity(optionId,custom,theqty,"product",resultPosition);
	
	}
	
}




/*-------------------------------------------------------------------------------------------------
englishOnlyChars(theValue)
THIS SAME FUNCTION IS IN checkout_functions.php
pass it a value and it'll return true if its english only, false if its not
-------------------------------------------------------------------------------------------------*/
function englishOnlyChars(stringToTest) {

	var matchString = new RegExp("[a-zA-Z0-9]");

	// Loop through each character in this string
	for(i=0; i < stringToTest.length; i++ ) {
	
		charToTest = stringToTest.charAt(i);
				
	     // If this char does not match our ascii chars, return false
		 if(!charToTest.match(matchString) && charToTest != " ") {
		 	//console.log("non ascii!:" + charToTest);
		 	return false;
		 }
	}
	
	// If we made it this far and didn't get any non-asciis, return true
	return true;

}




/*-------------------------------------------------------------------------------------------------
slideDiv()
Generic slid-o-div function
-------------------------------------------------------------------------------------------------*/
function slideDiv(whichDiv,direction,location) {
	var moveDiv = new Fx.Style($(whichDiv),
	direction, {duration: 300}).addEvent('onComplete', function() {
		//console.log("slide is complete");
	});
	moveDiv.start(location);
}
  
 


/*-------------------------------------------------------------------------------------------------
popBalloon()
-------------------------------------------------------------------------------------------------*/
function popBalloon() {
	//document.getElementById("balloon_img").src = "images/balloonTopPopped.png";
	slideDiv("balloonStringCover","height",575); // Not sliding here, actually growing. Change the height to 600 to cover the string
	slideDiv("balloon","top",-50);				 // Move the f down
}


 

/*-------------------------------------------------------------------------------------------------
toggleTabs()
-------------------------------------------------------------------------------------------------*/
function toggleTabs(whichOne,howManyTabs) {

	// Turn this one's content on
	document.getElementById("tabContent_" + whichOne).style.display = "block";
	
	// Make sure its small tab version is off
	document.getElementById("smallTab_" + whichOne).style.display          = "none";
	
	// And its big tab version is on
	document.getElementById("bigTab_" + whichOne).style.display            = "block";
	
	// Turn the rest off
	for(var i = 0; i < howManyTabs; i++) {
		if(i != whichOne) {
			document.getElementById("tabContent_" + i).style.display = "none";
			document.getElementById("bigTab_" + i).style.display     = "none";
			document.getElementById("smallTab_" + i).style.display   = "block";
		}
	}

}




