$(document).ready(function() {

	// set placement of container
	setPlacement(); $(window).resize(function() { setPlacement(); });

	// lazy load product images
	$('.product-image img').lazyload({placeholder:"/images/placeholder.gif",effect:"fadeIn"});
	$('.product-detail_image img').lazyload({placeholder:"/images/placeholder.gif"});
	
	// product image rollovers
	$('.products li').mouseover(function(){
		$(this).children('div.product-detail_image').css('visibility','visible').css('z-index','100');
		$(this).children('div.product-details').children('div.name').css('text-decoration','underline');
		$(this).children('div.product-details').children('div.desc').css('text-decoration','underline');
	});
	$('.products li').mouseout(function(){
		$(this).children('div.product-detail_image').css('visibility','hidden').css('z-index','-100');
		$(this).children('div.product-details').children('div.name').css('text-decoration','none');
		$(this).children('div.product-details').children('div.desc').css('text-decoration','none');
	});
	$('.product #product-thumbnails li').mouseover(function(){$('#product-image img').attr('src',$(this).children('img').attr('src'));});

	// product option rollovers
	$('.product-option').mouseover(function(){$(this).css('opacity','1');});
	$('.product-option').mouseout(function(){$(this).css('opacity','.75');});

	// product option clicks, add to cart
	$('.product-option').click(function(){
		addItemToCart($(this).attr('value'),1,null);
	});
	
	// other clicks
	$('.customer_type').click(function(){
		if ($('input:radio[name=customer_type]:checked').val() == 'new') {
			$('#newCustomer').hide();
			$('#newCustomer-password').show();
			$('#existingCustomer').show();
			$('#email').attr('name','uname');
			$('#checkout_form').attr('action','/x/c/register.php');
		} else {
			$('#newCustomer').show();
			$('#newCustomer-password').hide();
			$('#existingCustomer').hide();
			$('#email').attr('name','username');
			$('#checkout_form').attr('action','/x/c/s3_login.php');
		}		
	});

	// draw cart
	drawCart();
	
	// draw browse
	if (productid) {
		drawBrowse(productid);
	}
	
	// validate order status form
	$('#status_form').validate({
		rules: {
			email: {
				required: true,
				email: true
			}
		},
		messages: {
			email: {
				required: "Please enter an email address.",
				email: "Please enter a valid email address."
			},
			orderid: {
				required: "Please enter an order number."
			}
		}
	});
	
	// validate customer support form
	$('#support_form').validate({
		rules: {
			email: {
				required: true,
				email: true
			}
		},
		messages: {
			name: {
				required: "Please enter a name."
			},
			email: {
				required: "Please enter an email address.",
				email: "Please enter a valid email address."
			},
			body: {
				required: "Please enter a message."
			}
		}
	});
	
	// validate checkout form
	$('#checkout_form').validate({
		ignore: ":hidden",
		rules: {
			passwd1: {
				required: false,
				minlength: 5,
				maxlength: 16
			},
			passwd2: {
				required: false,
				minlength: 5,
				maxlength: 16,
				equalTo: "#passwd1"
			}
		},
		messages: {
			username: {
				required: "Please enter an email address.",
				email: "Please enter a valid email address."
			},
			uname: {
				required: "Please enter an email address.",
				email: "Please enter a valid email address."
			},
			passwd1: {
				minlength: "Your password must be at least 5 characters long."
			},
			passwd2: {
				minlength: "Your password must be at least 5 characters long.",
				equalTo: "Please enter the same password as above."
			},
			password: "Please enter a password."
		}
	});
	
	// validate payment form
	$('#payment_form').validate({
		ignore: ":hidden",
		rules: {
			card_type: {
				required: true
			},
			card_number: {
				required: true,
				creditcard: true
			},
			card_expire_month: {
				required: true
			},
			card_expire_year: {
				required: true
			},
			card_csc: {
				required: true,
				minlength: 3
			}
		},
		messages: {
			card_number: {
				required: "Please enter a credit card number."
			},
			card_csc: {
				required: "Please enter a security code."
			}
		}
	});
	
	// checkout form onchanges
	$('#b_country').change(function(){loadStates('billing');});
	$('#s_country').change(function(){loadStates('shipping');});
	
	// checkout form load states
	loadStates('billing');
	loadStates('shipping');
	
	// top navigation functions
	$('#top-navigation-tagid').change(function(){refreshArtistList();});
	$('#top-navigation-csid').change(function(){window.location='/x/c/home.php?csid=' + $(this).val() + '&tag_id='+$('#top-navigation-tagid').val();});
	$('#share-button').click(function(){$('#top-navigation-growl').hide();$('#top-navigation-share').show();});
	$('#next-button').click(function(){window.location='/x/c/home.php?csid=' + csid + '&a=next&tag_id='+$('#top-navigation-tagid').val();});
	$('#top-navigation-share-close').click(function(){$('#top-navigation-share').hide();});
	$('#top-navigation-growl-close').click(function(){$('#top-navigation-growl').fadeOut();});
});

// ---------------------------------------------------------------
function drawCart() {

	$.post('/x/xml/cart.php',function(xml){

		var cart=xml.documentElement, cartChild=cart.firstChild, total, productCount=0;
	
		// parse xml file for the goods	
		while(cartChild != null) {
			if(cartChild.nodeName == "sub_total") {
				total = cartChild.firstChild.nodeValue;		
			}
			if(cartChild.nodeName == "products") {
				var product = cartChild.firstChild;
				while(product != null) {
					if(product.nodeType == 3) {
						product = product.nextSibling;	
						continue;	
					}
					productChild = product.firstChild;			
					while(productChild != null) {
						if(productChild.nodeName == 'quantity') {
							productCount = parseInt(productCount) + parseInt(productChild.firstChild.nodeValue);
						}
						productChild = productChild.nextSibling;
					}
					product = product.nextSibling;
				}
			}
			cartChild = cartChild.nextSibling;
		}
		
		// "draw" cart icon
		if (productCount > 0) {
			$('#cart-image').removeClass('cart-empty').addClass('cart-full');
			$('#cart-text').html(productCount);
		} else {
			$('#cart-image').removeClass('cart-full').addClass('cart-empty');
			$('#cart-text').html("");
		}
	});
}

// ---------------------------------------------------------------
function drawBrowse(productid) {
	var response, product, productChild, browse_productid, browse_imageid, is_prev=0, is_next=0;
	
	// Get 'prev' product
	$.post('/x/xml/browseCategory.php?rm=getPrevProduct&productid=' + productid,function(response){
		if (response) {
			product = response.documentElement;	
			productChild = product.firstChild;
			
			while(productChild != null) {
				if (productChild.nodeName == "productid") {
					browse_productid = productChild.firstChild.nodeValue;		
				} else if (productChild.nodeName == "imageid") {
					browse_imageid = productChild.firstChild.nodeValue;
				}
				productChild = productChild.nextSibling;
			}
			
			$('#browse-prev img').attr('src','/x/detail_image.php?imageid=' + browse_imageid);
			$('#browse-prev a').attr('href','/x/c/product.php?productid=' + browse_productid);
			$('#browse-prev').css('display','block');
			$('#browse').css('display','block');
		}
	});

	// Get 'next' product
	$.post('/x/xml/browseCategory.php?rm=getNextProduct&productid=' + productid,function(response){
		if (response) {
			product = response.documentElement;
			productChild = product.firstChild;
			
			while(productChild != null) {
				if (productChild.nodeName == "productid") {
					browse_productid = productChild.firstChild.nodeValue;		
				} else if (productChild.nodeName == "imageid") {
					browse_imageid = productChild.firstChild.nodeValue;
				}
				productChild = productChild.nextSibling;
			}
			$('#browse-next img').attr('src','/x/detail_image.php?imageid=' + browse_imageid);
			$('#browse-next a').attr('href','/x/c/product.php?productid=' + browse_productid);
			$('#browse-next').css('display','block');
			$('#browse').css('display','block');
		}
	});
}

// ---------------------------------------------------------------
function addItemToCart(inventoryid, quantity, notes) {

	// store original message for later
	var tmp_cart_added = $('#cart-added').html();
	
	$('#cart-added').hide();
	$('#cart-added').html('<img src="/images/ajax-loader.gif"/> Adding...');
	$('#cart-added').animate({'opacity':'toggle'},'fast');
	
	$.post('/x/xml/cart.php?rm=addItemToCart&inventoryid='+inventoryid+'&quantity='+quantity+'&notes='+notes,function(response){

		var cart=response.documentElement, cartChild=cart.firstChild, tmp_message, success = 1;
		
		while(cartChild != null) {
			if(cartChild.nodeName == "messages") {
				var messages=cartChild, message=messages.firstChild, messageChild;
				while(message != null) {
					if(message.nodeType == 3) {
						message = message.nextSibling;
						continue;	
					}
					messageChild = message.firstChild;
					while(messageChild != null) {
						if(messageChild.nodeType == 3) {
							messageChild = messageChild.nextSibling;
							continue;	
						}
						if(messageChild.nodeName == "messageid") {
							messageid = messageChild.firstChild.nodeValue;
							messageChild = messageChild.parentNode.lastChild;
						}
						messageChild = messageChild.nextSibling;
					}
					if(messageid == 1) {	
						success = 0;
						message = null;
						cartChild = cartChild.parentNode.lastChild;
						break;
					}
					message = message.nextSibling;	
				}
			}		
			cartChild = cartChild.nextSibling;
		}
		
		if (success) {
			if (quantity == 1) {
				 tmp_message = '1 Item Added.';
			} else {
				 tmp_message = quantity + ' Items Added.';
			}
			
			$('#btn_checkout').show();
			
			// replace 'adding...' message with original
			$('#cart-added').html(tmp_cart_added);
			
			$('#cart-added-quantity').html(tmp_message);
			$('#cart-added').hide();
			$('#cart-added').animate({'opacity':'toggle'},'fast');
			
		} else {
			$('#cart-added').html('Item no longer available.');
			$('#cart-added').hide();
			$('#cart-added').animate({'opacity':'toggle'},'fast');
		}
		
		drawCart();
	});
}
 
// ---------------------------------------------------------------
function removeItemFromCart(inventoryid, csid) {
	$.post('/x/xml/cart.php?rm=removeItemFromCart&inventoryid='+inventoryid,
		function(response){ location.href='/x/c/cart.php?csid=' + csid + '&mode=checkout'; }
	);
}

// ---------------------------------------------------------------
function loadStates(type) {
	if (type == 'billing') {
		$.post('/x/xml/states.php?country_code=' + $('#b_country').val(),function(response){
			if (response.getElementsByTagName('state').length) {
				$('#b_state').html('');
				$('#b_state').show();	
				$('#o_b_state').hide();	
				for (i = 0; i < response.getElementsByTagName('state').length; i++) {
					name = response.getElementsByTagName('name').item(i).firstChild.data;
					code = response.getElementsByTagName('code').item(i).firstChild.data;				
					optionObj = new Option(name, code);
					document.getElementById('b_state').options[i+1] = optionObj;
				}
				$('#b_state').val($('#o_b_state').val());	
			} else {
				$('#b_state').hide();	
				$('#o_b_state').show();
			}
		});
	} else { // type == 'shipping'
		$.post('/x/xml/states.php?country_code=' + $('#s_country').val(),function(response){
			if (response.getElementsByTagName('state').length) {
				$('#s_state').html('');
				$('#s_state').show();	
				$('#o_s_state').hide();
				for (i = 0; i < response.getElementsByTagName('state').length; i++) {
					name = response.getElementsByTagName('name').item(i).firstChild.data;
					code = response.getElementsByTagName('code').item(i).firstChild.data;				
					optionObj = new Option(name, code);
					document.getElementById('s_state').options[i+1] = optionObj;
				}
				$('#s_state').val($('#o_s_state').val());	
			} else {
				$('#s_state').hide();	
				$('#o_s_state').show();
			}
		});
	}
}

// ---------------------------------------------------------------
function setCardExpire() {
	$('#card_expire').val($('#card_expire_month').val() + $('#card_expire_year').val());
}

// ---------------------------------------------------------------
function setPlacement() {
	
	if ($(window).width() < $('#container').width()+30) {
		$('.container').css('left', '15px');
		$('.container').css('margin-left', '0px');
	} else {
		$('.container').css('left', '50%');
		$('.container').css('margin-left', '-' + $('#container').width()/2 + 'px');
	}
}

//---------------------------------------------------------------//
function refreshArtistList() {

	$.post('/x/xml/storesByTag.php?tag_id=' + $('#top-navigation-tagid').val(),
		function(resp) {
		
			$('#top-navigation-csid').html('<option>Shop by Store...</option>');
			$(resp).find('store').each(function(){
				$('#top-navigation-csid').html($('#top-navigation-csid').html() + '<option value="' + $(this).find('id').text() + '">' + $(this).find('name').text() + '</option>');
			});
		}
	);
}
