/* Adds products to the cart and updates total items and price */
function updateCart( whichId, whichPrice ) {
	var pageOverlay = document.getElementById( 'overlay' );
	var cartTable = document.getElementsByTagName( 'table' )[ 0 ];
	
	var pageBody = document.getElementsByTagName( 'body' )[ 0 ];
	var pageOverlayBox = document.getElementById( 'overlay_box' );
	
	var cartPrice = document.getElementById( 'total_price' );
	var cartItems = document.getElementById( 'total_items' );
	
	var currProducts;
	var currItems = 1;
	
	var totalPrice = 0;
	var totalItems = 0;
	
	// Get product cookie and create a 2-D array of product values
	if( getCookie( 'products' ) ) {
		currProducts = new Array();
		var productRow = getCookie( 'products' ).split( ',' );
		
		for( var i = 0; i < productRow.length; i++ ) {
			var productInfo = productRow[ i ].split( ':' );
			currProducts.push( productInfo );
		}
	}
	
	// Set total price in cart
	if( cartPrice ) {
 		if( getCookie( 'price' ) ) {
 			totalPrice = parseFloat( getCookie( 'price' ) ); // Set price from cookie
 		}
		
		if( whichPrice ) {
			totalPrice += parseFloat( whichPrice ); // Increment price
		}
		
		totalPrice = roundNumber( totalPrice, 2 ); // Round price (Firefox bug)
		setCookie( 'price', totalPrice ); // Set the cookie again to access later
		
		// Format the price string in the cart
		totalPrice = '$' + ( totalPrice == 0 ? '0.0' : totalPrice ) + ( ( ( totalPrice * 100 ) % 10 ) == 0 ? '0' : '' );
		// Set the value of the node to change the text
		setNodeValue( cartPrice, totalPrice );
	}
	
	// Set total items in cart	
	if( cartItems ) {
		if( currProducts ) {
 			for( var i = 0; i < currProducts.length; i++ ) {
				totalItems += parseInt( currProducts[ i ][ 1 ] ); // Parse through cookie data and add up number of items
				
				if( currProducts[ i ][ 0 ] == whichId ) {
					currProducts[ i ][ 1 ]++; // Increment: new item!
				}
 			}
 		}
			
		if( whichId ) {
			totalItems++;
		}
		
		// Set the text in the cart
		totalItems += ' Items | ';
		setNodeValue( cartItems, totalItems );						
	}
			
	// Set cookie again with new info	
	if( whichId ) {
		if( currProducts ) {
			var myCookie = getCookie( 'products' );
			var myVal = '';
			
			// Check to see if there are other products in the list, 
			// then extract the one we want, increment the number of items
			// and put it back in the cookie
			for( var i = 0; i < currProducts.length; i++ ) {
				// Check to see if this is the cookie we want to update
				if( currProducts[ i ][ 0 ] == whichId ) {
					
					var startPos = myCookie.indexOf( whichId );
					var endPos = myCookie.indexOf( ',', startPos );
					
					if( startPos == -1 ) {
						myVal = myCookie;
					}
					else if( endPos == -1 ) {
						myVal = myCookie.substring( 0, startPos - 1 );
					}
					else {
						myVal = myCookie.substring( 0, startPos - 1 ) + myCookie.substring( endPos + 1, myCookie.length );  
					}
					
					myVal = currProducts[ i ].join( ':' ) + ( myVal ? ',' : '' ) + myVal;
				}
				
			}
			
			if( myVal ) {
				setCookie( 'products', myVal );
			}
			else {
				setCookie( 'products', myCookie + ',' + whichId + ':' + currItems );
			}
		}
		else {
			setCookie( 'products', whichId + ':' + currItems );
		}
	}
	
	// Load product data for updating the cart's info
	var tableConn = new xmlConn();
	tableConn.getXML( 'product_data.xml', function() {
		loadTableData( tableConn.getConn(), cartTable );
	} );
}

/* Load XML data for products */
function loadTableData( conn, whichTable ) {
	if( conn.readyState == 4 ) {
		if( conn.status == 200 ) {
			var tableParent = whichTable.parentNode;
			var newTable = createTable( new Array( 'Image', 'Name', 'Price', 'Quantity' ), 'products' );
			
			var totalPrice = 0;
			var totalItems = 0;
			
			tableParent.insertBefore( newTable, whichTable.nextSibling );
			tableParent.removeChild( whichTable );
			
			if( getCookie( 'products' ) ) {
				var productList = conn.responseXML.getElementsByTagName( 'product' );
				
				var currProducts;
				
				if( getCookie( 'products' ) ) {
					currProducts = new Array();
					var productRow = getCookie( 'products' ).split( ',' );
		
					for( var i = 0; i < productRow.length; i++ ) {
						var productInfo = productRow[ i ].split( ':' );
						currProducts.push( productInfo );
						totalItems += parseInt( currProducts[ i ][ 1 ] );
					}
				}
	
				for( var i = 0; i < currProducts.length; i++ ) {
					for( var j = 0; j < productList.length; j++ ) {
						if( currProducts[ i ][ 0 ] == productList[ j ].getAttribute( 'id' ) ) {
							
							var newImage = createImage( productList[ j ].getAttribute( 'image' ) );
							var newName = productList[ j ].getAttribute( 'title' );
							var newQuantity = currProducts[ i ][ 1 ];
							var newPrice = productList[ j ].getAttribute( 'price' );
							
							insertRows( newTable, new Array( newImage, newName, '$' + newPrice, newQuantity ) );
						}
					}
				}
			}
			
			
			insertRows( newTable, new Array( '', 'Total: ', '$' + ( getCookie( 'price' ) ? getCookie( 'price' ) : 0 ), '' + totalItems ), '', '', 'bottom' );
		}
	}
}

/* Build the checkout elements */
function buildCheckout() {
	var totalItems = 0;
	var totalPrice = 0;
	
	if( getCookie( 'products' ) ) {
		var productRow = getCookie( 'products' ).split( ',' );
		
		for( var i = 0; i < productRow.length; i++ ) {
			var productInfo = productRow[ i ].split( ':' );
			totalItems += parseInt( productInfo[ 1 ] );
		}
	}
	
	if( getCookie( 'price' ) ) {
		totalPrice = parseFloat( getCookie( 'price' ) );
	}
	
	var pageOverlayBox = document.getElementById( 'overlay_box' );
	
	while( pageOverlayBox.lastChild ) {
		pageOverlayBox.removeChild( pageOverlayBox.lastChild );
	}
	
	var closeImage = createImage( 'images/close.gif' + ( document.all ? '?' + Math.random() : '' ), 'close' );
	
	closeImage.onload = function() {
		setFakeLink( this );
	
		this.onclick = function() {
			hideOverlay();							
		}
	}
	
	pageOverlayBox.appendChild( closeImage );
	
	var checkoutHeader, checkoutPara, checkoutSpan, checkoutBreak, checkoutInput, checkoutList, checkoutForm;
	
	checkoutHeader = createHeader( 'h2', 'Checkout Time!' );
	pageOverlayBox.appendChild( checkoutHeader );
	
	checkoutPara = createParagraph( null, '', 'totals' );
	
	checkoutSpan = createNewElement( 'span', '', 'bold' );
	checkoutSpan.appendChild( document.createTextNode( 'Total Price: ' ) );
	
	checkoutPara.appendChild( checkoutSpan );
	checkoutPara.appendChild( document.createTextNode( '$' + totalPrice ) );
	
	checkoutBreak = createNewElement( 'br' );
	checkoutPara.appendChild( checkoutBreak );
	
	checkoutSpan = createNewElement( 'span', '', 'bold' );
	checkoutSpan.appendChild( document.createTextNode( 'Total Items: ' ) );
	
	checkoutPara.appendChild( checkoutSpan );
	checkoutPara.appendChild( document.createTextNode( totalItems ) );
	pageOverlayBox.appendChild( checkoutPara );
	
	// Build the form
	checkoutForm = createNewElement( 'form' );
	
	if( document.all ) {
		checkoutForm.onsubmit = function() {
			return validate();
		};
	}
	else {
		checkoutForm.setAttribute( 'onsubmit', 'return validate()' );
	}
	
	checkoutList = createList( 'ul' );
	
	// Build all the inputs
	checkoutItem = createNewElement( 'li' );
	checkoutLabel = createLabel( 'First Name' );
	checkoutInput = createInput( 'text', 30, null, 'custFName' );
	checkoutSpan = createNewElement( 'span', 'custFName' );
	checkoutItem.appendChild( checkoutLabel );
	checkoutItem.appendChild( checkoutInput );
	checkoutItem.appendChild( checkoutSpan );
	checkoutList.appendChild( checkoutItem );
	
	checkoutItem = createNewElement( 'li' );
	checkoutLabel = createLabel( 'Last Name' );
	checkoutInput = createInput( 'text', 30, null, 'custLName' );
	checkoutSpan = createNewElement( 'span', 'custLName' );
	checkoutItem.appendChild( checkoutLabel );
	checkoutItem.appendChild( checkoutInput );
	checkoutItem.appendChild( checkoutSpan );
	checkoutList.appendChild( checkoutItem );
	
	checkoutItem = createNewElement( 'li' );
	checkoutLabel = createLabel( 'E-mail' );
	checkoutInput = createInput( 'text', 30, null, 'custEmail' );
	checkoutSpan = createNewElement( 'span', 'custEmail' );
	checkoutItem.appendChild( checkoutLabel );
	checkoutItem.appendChild( checkoutInput );
	checkoutItem.appendChild( checkoutSpan );
	checkoutList.appendChild( checkoutItem );
	
	checkoutItem = createNewElement( 'li' );
	checkoutLabel = createLabel( 'Address' );
	checkoutInput = createInput( 'text', 30, null, 'custAddress' );
	checkoutSpan = createNewElement( 'span', 'custAddress' );
	checkoutItem.appendChild( checkoutLabel );
	checkoutItem.appendChild( checkoutInput );
	checkoutItem.appendChild( checkoutSpan );
	checkoutList.appendChild( checkoutItem );
	
	checkoutItem = createNewElement( 'li' );
	checkoutLabel = createLabel( 'City' );
	checkoutInput = createInput( 'text', 30, null, 'custCity' );
	checkoutSpan = createNewElement( 'span', 'custCity' );
	checkoutItem.appendChild( checkoutLabel );
	checkoutItem.appendChild( checkoutInput );
	checkoutItem.appendChild( checkoutSpan );
	checkoutList.appendChild( checkoutItem );
	
	checkoutItem = createNewElement( 'li' );
	checkoutLabel = createLabel( 'State' );
	checkoutInput = createInput( 'text', 5, null, 'custState' );
	checkoutSpan = createNewElement( 'span', 'custState' );
	checkoutItem.appendChild( checkoutLabel );
	checkoutItem.appendChild( checkoutInput );
	checkoutItem.appendChild( checkoutSpan );
	checkoutList.appendChild( checkoutItem );
	
	checkoutItem = createNewElement( 'li' );
	checkoutLabel = createLabel( 'Zip' );
	checkoutInput = createInput( 'text', 5, null, 'custZip' );
	checkoutSpan = createNewElement( 'span', 'custZip' );
	checkoutItem.appendChild( checkoutLabel );
	checkoutItem.appendChild( checkoutInput );
	checkoutItem.appendChild( checkoutSpan );
	checkoutList.appendChild( checkoutItem );
	
	checkoutItem = createNewElement( 'li' );
	checkoutInput = createInput( 'reset', null, 'Reset', 'custReset' );
	checkoutItem.appendChild( checkoutInput );
	checkoutItem.appendChild( document.createTextNode( ' ' ) );
	checkoutInput = createInput( 'submit', null, 'Submit', 'custSubmit' );
	checkoutItem.appendChild( checkoutInput );
	checkoutList.appendChild( checkoutItem );
	
	checkoutForm.appendChild( checkoutList );
	pageOverlayBox.appendChild( checkoutForm );
	
}

/* Builds the shopping cart overlay */
function buildCart() {
	var pageOverlayBox = document.getElementById( 'overlay_box' );
	
	while( pageOverlayBox.lastChild ) {
		pageOverlayBox.removeChild( pageOverlayBox.lastChild );
	}
	
	var testCloseImage = createImage( 'images/close.gif' + ( document.all ? '?' + Math.random() : '' ), 'close' );
	pageOverlayBox.appendChild( testCloseImage );
	
	var testHeader = createHeader( 'h2', 'Your Shopping Cart' );
	pageOverlayBox.appendChild( testHeader );
	
	// Build the table
	var testTable = createTable( new Array( 'Image', 'Name', 'Price', 'Quantity' ), 'products' );
	pageOverlayBox.appendChild( testTable );
	/*** Display bug in IE -- for some reason dynamically created tables won't show up without it ***/
	pageOverlayBox.innerHTML = pageOverlayBox.innerHTML;
	
	var testCheckout = createImage( 'images/checkout.gif' + ( document.all ? '?' + Math.random() : '' ), 'checkout_button' );
	
	testCheckout.onload = function() {
		setFakeLink( this );
	
		this.onclick = function() {
			if( getCookie( 'price' ) && parseInt( getCookie( 'price' ) ) != 0 ) {
				buildCheckout();							
			}
			else {
				alert( "There's nothing in your cart!" );
			}
		}
	}
	
	pageOverlayBox.appendChild( testCheckout );
}

/* Adds dynamic error messages to the form */
function addErrorMsg( whichElem, whichId, whichMsg ) {
	// Set styles
	whichElem.style.border = '2px solid #c30';
	whichElem.style.background = '#fee';
	whichElem.style.paddingTop = '10px';
	whichElem.style.paddingBottom = '10px';
	whichElem.style.margin = '5px 0';
	
	// Set the text of the span element to the right of the input
	var myError = document.getElementById( whichId );
	myError.style.color = '#c30';
	myError.style.textTransform = 'none';
	
	// Remove everything from the span, then add a new textNode
	while( myError.lastChild ) {
		myError.removeChild( myError.lastChild );
	}
	
	myError.appendChild( document.createTextNode( whichMsg ) );
}

/* Removes dynamic error mesages */
function removeErrorMsg( whichElem, whichId ) {
	// Reset styles
	whichElem.style.border = 'none';
	whichElem.style.background = 'transparent';
	whichElem.style.paddingTop = '5px';
	whichElem.style.paddingBottom = '5px';
	whichElem.style.margin = '0';
	
	// remove everything from the span
	var myError = document.getElementById( whichId );
	while( myError.lastChild ) {
		myError.removeChild( myError.lastChild );
	}
}

/* Validates the form's values */
function validate() {
	var myForm = document.getElementsByTagName( 'form' )[ 0 ];
	var retVal = true;
	
	for( var i = 0; i < myForm.elements.length; i++ ) {
		var myElem = myForm.elements[ i ];
		var myElemValue = myForm.elements[ i ].value;
		
		// Check each element and cosntruct appropriate error messages
		switch( myElem.getAttribute( 'name' ) ) {
			case 'custFName':
			case 'custLName':
			case 'custAddress':
			case 'custCity':
				if( !myElemValue ) {
					addErrorMsg( myElem.parentNode, myElem.getAttribute( 'name' ), 'Please enter a value.' );
				}
				else {
					removeErrorMsg( myElem.parentNode, myElem.getAttribute( 'name' ) );
				}
				break;
			case 'custEmail':
				// Format email correctly
				var atSymb = myElemValue.indexOf( '@' );
				var dotSymb = myElemValue.indexOf( '.', atSymb );
				
				if( !myElemValue ) {
					addErrorMsg( myElem.parentNode, myElem.getAttribute( 'name' ), 'Please enter a value.' );
					retVal = false;
				}
				else if( atSymb == 0 || atSymb == -1 || dotSymb == atSymb + 1 || dotSymb == myElemValue.length - 1 || dotSymb == -1 ) {
					addErrorMsg( myElem.parentNode, myElem.getAttribute( 'name' ), 'Email address must be in this format: blah@blah.blah' );
					retVal = false;
				}
				else {
					removeErrorMsg( myElem.parentNode, myElem.getAttribute( 'name' ) );
				}
				break;
			case 'custState':
				if( !myElemValue ) {
					addErrorMsg( myElem.parentNode, myElem.getAttribute( 'name' ), 'Please enter a value.' );
					retVal = false;
				}
				else if( myElemValue.length != '2' ) {
					addErrorMsg( myElem.parentNode, myElem.getAttribute( 'name' ), 'State must be 2 characters long.' );
					retVal = false;
				}
				else {
					removeErrorMsg( myElem.parentNode, myElem.getAttribute( 'name' ) );
				}
				break;
			case 'custZip':
				var myZip = parseInt( myElemValue );
				
				if( !myElemValue ) {
					addErrorMsg( myElem.parentNode, myElem.getAttribute( 'name' ), 'Please enter a value.' );
					retVal = false;
				}
				else if( !myZip ) {
					addErrorMsg( myElem.parentNode, myElem.getAttribute( 'name' ), 'Zip Code must be a number.' );
					retVal = false;
				}
				else if( myElemValue.length != 5 ) {
					addErrorMsg( myElem.parentNode, myElem.getAttribute( 'name' ), 'Zip Code must be 5 digits long.' );
					retVal = false;
				}
				else {
					removeErrorMsg( myElem.parentNode, myElem.getAttribute( 'name' ) );
				}
				break;
			default:
				break;
		}						
	}
	
	if( retVal ) {
		alert( "Thank you! Your order is being processed." );
		removeCookies();
	}
	
	return retVal;
}

/* Create initial overlay by setting large background with transparency over everything else */
function addOverlay() {
	var pageOverlay = createDiv( 'overlay' );
	
	setOpacity( pageOverlay, 70 );
	
	var pageOverlayBox = createDiv( 'overlay_box' );
	
	pageOverlay.onclick = function() {
		hideOverlay();
	}
	
	pageOverlay.style.display = 'none';
	pageOverlayBox.style.display = 'none';
	
	var pageBody = document.getElementsByTagName("body")[ 0 ];
	pageBody.insertBefore( pageOverlay, pageBody.firstChild );
	pageBody.insertBefore( pageOverlayBox, pageBody.nextSibling );
	
	buildCart();
	updateCart();			
}

/* Show the overlay over top of everything */
function showOverlay() {
	// Animate scrolling to the top so it's not so jolting
	scrollPage( -10 );
	
	// Build and update cart info
	buildCart();
	updateCart();
	
	var pageOverlay = document.getElementById( 'overlay' );
	var pageOverlayBox = document.getElementById( 'overlay_box' );
	var pageBody = document.getElementsByTagName( 'body' )[ 0 ];
	
	if( pageOverlayBox ) {
		pageOverlayBox.style.display = 'block';	
	
		var closeImage = document.getElementById( 'close' );
		setFakeLink( closeImage );
		
		closeImage.onclick = function() {
			hideOverlay();							
		}
	}
	
	if( pageOverlay ) {
		if( document.all ) {
			var mySelects = document.getElementsByTagName( 'select' );
			
			for( var i = 0; i < mySelects.length; i++ ) {
				mySelects[ i ].style.visibility = 'hidden';								
			}
		}
		
		// Get the scroll height so it extends all the way down
		pageOverlay.style.height = getWindowHeight() + 'px';
		pageOverlay.style.display = 'block';				
	}
}

/* Hide the overlay */
function hideOverlay() {
	var pageOverlay = document.getElementById( 'overlay' );
	var pageOverlayBox = document.getElementById( 'overlay_box' );
	var pageBody = document.getElementsByTagName( 'body' )[ 0 ];
	
	// Build cart info
	buildCart();
	
	if( pageOverlay ) {
		if( document.all ) {
			var mySelects = document.getElementsByTagName( 'select' );
			
			for( var i = 0; i < mySelects.length; i++ ) {
				mySelects[ i ].style.visibility = 'visible';								
			}
		}
		
		pageOverlay.style.display = 'none';
	}
	
	if( pageOverlayBox ) {
		pageOverlayBox.style.display = 'none';
	}
}