$(document).ready(function(){
	//for getting length of an object like Array.length
	Object.size = function(obj) {
		var size = 0, key;
		for (key in obj) {
			if (obj.hasOwnProperty(key)) size++;
		}
		return size;
	};
	//adds decimal places
	function money_format(value, currency_symbol){
		value = parseFloat(value);
		if(value.toFixed){//function does not exist in older browsers so we check
			value = value.toFixed(2);//add 2 decimal places
		}
		return currency_symbol+value;
	}
	
	
	var cart_items = {};//cart items are saved here
	var current_item = 0;//store product id
	var products = {};//products
	
	//save items to js object so that we dont have to use jquery.find().html() for this info
	if($('.products ul li').length > 0){
		var pid = 0;
		$('.products ul li').each(function(index) { 
			pid = parseInt($(this).find('.meta .pid').html());

			products[pid]={
				'full_image': $(this).find('.meta .prod-full-image').html(),
				'cart_thumbnail': $(this).find('.meta .prod-cart-thumbnail').html(),
				'description': $(this).find('.meta .prod-description').html(),
				'stock': parseInt($(this).find('.meta .prod-stock').html()),
				'sale': $(this).find('.meta .prod-sale').html(),
				'currency_symbol': $(this).find('.prod-price .currency_symbol').html(),
				'amount': parseFloat($(this).find('.prod-price .amount').html()),
				'name': $(this).find('.prod-name').html()
			};
			
		});
	}
	
	if($.JSONCookie("cart_items")){//we use cookies to save the data even if we leave the page and comeback later
		cart_items = $.JSONCookie('cart_items');
	}
	//if($.JSONCookie("products")){
		//products = $.JSONCookie('products');
	//}
	$('.store-options a.counter').html(Object.size(cart_items));//get item count
	function save_to_cookies(){
		$.JSONCookie('cart_items', cart_items, {path: '/'});//store cart items in cookie
		//$.JSONCookie('products', products, {path: '/'});//products in cookie. overwrite the above loop
	}
	
	//clears textbox on focus. but returns the initial value if it loses focus, only when textbox is blank
	$('input.item-textbox').focus(function(){
		if(!$(this).data('cleared')){
			$(this).data('value', $(this).val());
			$(this).data('cleared', true).val('');
		}
	}).blur(function(){
		if($.trim($(this).val())==''){
			$(this).data('cleared', false).val($(this).data('value'));
		}
	});
	
	//check email
	function isValidEmail(str) {
   		return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
	}
	//when a product is clicked
	$('.products li').click(function() {
		var pid = parseInt($(this).find('.meta .pid').html());
		
		var product = products[pid];
		if($(this).html()!=''){
			$('.popup-page').hide();
			
			$('#product-view input.item-qty').val(1);
			$('#product-view').find('.product-image').html(product['full_image']);
			$('#product-view').find('.product-desc').html(product['description']);
			$('#product-view').find('.item-name').html(product['name']);
			$('#product-view').find('.item-price').find('.currency_symbol').html(product['currency_symbol']);
			$('#product-view').find('.item-price').find('.amount').html(product['amount']);
			
			current_item = pid;//store post id. use it as product id to identify products uniquely
			
			$('#product-view').css("top", ($(window).scrollTop()+20) + "px").show();//position and show it
		}
		return false;
	});
	//add to cart is clicked
	$('#product-view input.btn-add-to-bag').click(function(){

		var add = parseInt($('#product-view input.item-qty').val());
		var pid = current_item;
		var product = products[pid];
		
		if(product['stock']-add<0){
			alert('Sorry but item is out of stock.');	
			return false;
		}
		products[pid]['stock']-=add;
		if(cart_items[pid]!=null){//key does exist, update it
			var current_count = cart_items[pid]['count'];
			current_count=current_count+add;
			cart_items[pid]['count']=current_count;
		} else {
			cart_items[pid]={
				'count':add,
				'name':product['name'],
				'price':product['amount'],
				'currency_symbol':product['currency_symbol']
			};
		}
		//debug cart contents
		/*
		var str = '';
		$.each(cart_items, function(key, value) { 
			str += key+':{count:'+value['count']+', name:'+value['name']+', price:'+value['price']+"}\n";
		});
		alert(str);
		*/
		//
		$('.store-options a.counter').html(Object.size(cart_items));

		$('#product-view').fadeOut();
		save_to_cookies();//store cart items in cookie
		return false;										 
	});
	//when the update button is click on the shopping cart, to change item quantity
	$('#shopping-cart-view input.btn-update').click(function(){
		var total = 0.00;
		var qty = 0;
		var price = 0.00;
		var currency_symbol = '';
		var product;
		$('#shopping-cart-view .items .item').each(function(index) { 
			pid = parseInt($(this).find('div.pid').html());
			product = products[pid];
			qty = parseInt($(this).find('input.item-qty').val());
			price = product['amount'];
			currency_symbol = product['currency_symbol'];
			total += qty * price;
			cart_items[pid]['count']=qty;
		});
		var orig = $('#shopping-cart-view .total .price').css('color');//get original color
		$('#shopping-cart-view .total .price').css('color', '#B70000');//set color to a different one
		$('#shopping-cart-view .total .price').animate({color: orig},'slow');//now animate color from the the current color to the original color															   

		$('#shopping-cart-view .total .price').html(money_format(total,currency_symbol));//show amount
		save_to_cookies();//store cart items in cookie
		return false;
	});
	//delete cart items 
	$('#shopping-cart-view .item-delete').live('click', function() {
		var parent = $(this).parent('.item');
		var pid = parseInt(parent.find('.pid').html());
		var product = products[pid];
		
		var price = product['amount'];
		var currency_symbol = product['currency_symbol'];

		var qty = parseInt(parent.find('input.item-qty').val());
		var total = parseFloat($('#shopping-cart-view .total .price').html().replace(currency_symbol,''));
		total = total - (price*qty);
		//update total
		$('#shopping-cart-view .total .price').html(money_format(total,currency_symbol));
		//hide and remove the deleted item
		parent.fadeOut(400, function(){ parent.remove() } );
		//update cart items
		
		delete cart_items[pid];
		//update item count
		$('.store-options a.counter').html(Object.size(cart_items));
		save_to_cookies();//store cart items in cookie
		return false;
	});
	//delete cart items on checkout
	$('#checkout-view .item-delete').live('click', function() {
		var parent = $(this).parent('.item');
		var pid = parseInt(parent.find('.pid').html());
		var product = products[pid];
		
		var price = product['amount'];
		var currency_symbol = product['currency_symbol'];
		
		var qty = parseInt(parent.find('input.item-qty').val());
		var total = parseFloat($('#checkout-view .total .price').html().replace(currency_symbol,''));
		total = total - (price*qty);
		//update total
		$('#checkout-view .total .price').html(money_format(total,currency_symbol));
		//hide and remove the deleted item
		parent.fadeOut(400, function(){ parent.remove() } );
		//update cart items
		
		delete cart_items[pid];
		//update item count
		$('.store-options a.counter').html(Object.size(cart_items));
		save_to_cookies();//store cart items in cookie
		return false;
	});
	//button continue
	$('#shopping-cart-view input.btn-continue').click(function(){
		$('#shopping-cart-view').hide();
		return false;												   
	});
	//button checkout
	$('#shopping-cart-view input.btn-checkout').click(function(){
		$('.store-options li.checkout').trigger('click');
		return false;												   
	});
	
	//checkout now
	$('#checkout-view input.btn-complete').click(function(){
		var firstname = $('#checkout-view input[name=firstname]');
		var lastname = $('#checkout-view input[name=lastname]');
		var email = $('#checkout-view input[name=email]');
		var address1 = $('#checkout-view input[name=address1]');
		var address2 = $('#checkout-view input[name=address2]');
		var city_county = $('#checkout-view input[name=city_county]');
		var state = $('#checkout-view select[name=state]');
		var zip = $('#checkout-view input[name=zip]');
		var country = $('#checkout-view select[name=country]');
		var phone = $('#checkout-view input[name=phone]');
		var captcha = $('#checkout-view input[name=captcha]');
		var errors = [];
		var dir = $('#checkout-view input[name=stylesheet_dir]').val();
		
		firstname.val($.trim( firstname.val() ));
		lastname.val($.trim( lastname.val() ));
		email.val($.trim( email.val() ));
		address1.val($.trim( address1.val() ));
		address2.val($.trim( address2.val() ));
		city_county.val($.trim( city_county.val() ));
		zip.val($.trim( zip.val() ));
		phone.val($.trim( phone.val() ));
		captcha.val($.trim( captcha.val() ));
		
		if(Object.size(cart_items)<=0){
			alert('You have an empty shopping bag.');
			return false;
		}
		if(!firstname.data('cleared') ){
			errors.push('First Name should not be blank.');
			firstname.css('border-color', '#B70000');	
		} 
		
		if(!lastname.data('cleared') ){
			errors.push('Last Name should not be blank.');
			lastname.css('border-color', '#B70000');	
		}
		
		if(!email.data('cleared') ){
			errors.push('Email should not be blank.');
			email.css('border-color', '#B70000');	
		} else {
			if(!isValidEmail(email.val())){
				errors.push('Email appears to be invalid.');
				email.css('border-color', '#B70000');
			}
		}
		
		if(!address1.data('cleared') ){
			errors.push('Address 1 should not be blank.');
			address1.css('border-color', '#B70000');	
		}
		
		if(!city_county.data('cleared') ){
			errors.push('City or County should not be blank.');
			city_county.css('border-color', '#B70000');	
		}
		
		if(state.val() ==''){
			errors.push('Please select a State.');
			state.css('border-color', '#B70000');	
		}
		
		if(!zip.data('cleared') ){
			errors.push('Zip Code should not be blank.');
			zip.css('border-color', '#B70000');	
		}
		
		if(country.val() ==''){
			errors.push('Please select a Country.');
			country.css('border-color', '#B70000');	
		}
		
		if(!phone.data('cleared') ){
			errors.push('Phone should not be blank.');
			phone.css('border-color', '#B70000');	
		}
		
		
		if(captcha.val() ==''){
			errors.push('Code should not be blank.');
		}
		
		if(errors.length>0){
			alert(errors.join("\n"));	
		} else {
			$('.complete-order label,.complete-order img,.complete-order input').hide();
			$('.complete-order').append('<p style="color:#000000;padding:8px 10px 10px 100px" class="processing">Processing order. Please wait..</p>');
			$.post(dir+"/captcha-check.php", {captcha_val: captcha.val()},
			function(data){
				if(data=='true'){
					//total = parseFloat($('#form-checkout').find('.total .price').html().replace('$',''));
					//$('input[name=amount]').val(total);
					//add item fields
					//var item_count = 0;
					var html = '';
					$.each(cart_items, function(key, value) { 
						//item_count++;
						html += '<input type="hidden" name="item_id[]" value="'+key+'" />'+"\n";
						//html += '<input type="hidden" name="amount[]" value="'+value['price']+'" />'+"\n";
						html += '<input type="hidden" name="quantity[]" value="'+value['count']+'" />'+"\n";
					});
					$('#form-checkout').prepend(html);
					$.cookie('cart_items', '', {path: '/'});//delete cart items in cookie
					
					$('#form-checkout').submit();
				} else {
					$('img.captcha').attr('src',dir+"/captcha.php");
					captcha.val('');
					$('.complete-order label,.complete-order img,.complete-order input').show();
					$('.complete-order .processing').remove();
					alert('Incorrect Code. Please try again.');	
				}
			});	
		}
		return false;							 
	});
	//show items
	$('.store-options li.count').click(function() {
		$('.popup-page').hide();
		var html = '';
		var total = 0;
		var currency_symbol = '';
		$.each(cart_items, function(pid, value) { 
			html += '<div class="item clearfix">';
			html += '	<div class="pid">'+pid+'</div>';
			html += '	<div class="item-photo">'+products[pid]['cart_thumbnail']+'</div>';
			html += '	<div class="item-name">'+value['name']+'</div>';
			html += '	<div><input class="item-qty" maxlength="2" type="text" value="'+value['count']+'" name="item-qty" /></div>';
			html += '	<div class="item-price"><span class="currency_symbol">'+value['currency_symbol']+'</span><span class="amount">'+value['price']+'</span></div>';
			html += '	<a href="#" class="item-delete" href="#">X</a>';
			html += '</div>';
			var str = new String(value['price']);
			currency_symbol = value['currency_symbol'];
			total += parseInt(value['count'])*parseFloat(str.replace(currency_symbol,''));	
		});
		$('#shopping-cart-view div.items').html(html);
		$('input.item-qty').numeric();//alphanumeric plugin. allow only numbers
		$('#shopping-cart-view .total .price').html(money_format(total,currency_symbol));
		$('#shopping-cart-view').css("top", ($(window).scrollTop()+20) + "px").show();
		return false;
	});
	//show checkout
	$('.store-options li.checkout').click(function() {
		$('.popup-page').hide();
		var html = '';
		var total = 0;
		var currency_symbol = '';
		$.each(cart_items, function(pid, value) { 
			html += '<div class="item clearfix">';
			html += '	<div class="pid">'+pid+'</div>';
			html += '	<div class="item-photo">'+products[pid]['cart_thumbnail']+'</div>';
			html += '	<div class="item-name">'+value['name']+'</div>';
			html += '	<div><input readonly="true" class="item-qty" maxlength="2" type="text" value="'+value['count']+'" name="item-qty" /></div>';
			html += '	<div class="item-price"><span class="currency_symbol">'+value['currency_symbol']+'</span><span class="amount">'+value['price']+'</span></div>';
			html += '	<a href="#" class="item-delete" href="#">X</a>';
			html += '</div>';
			var str = new String(value['price']);
			currency_symbol = value['currency_symbol'];
			total += parseInt(value['count'])*parseFloat(str.replace(currency_symbol,''));
		});
		$('#checkout-view div.items').html(html);
		$('input.item-qty').numeric();//alphanumeric plugin. allow only numbers
		$('#checkout-view .total .price').html(money_format(total,currency_symbol));
		$('#checkout-view').css("top", ($(window).scrollTop()+20) + "px").show();
		return false;
	});
	
	
	
	//other popup page
	$('.close').click(function() {
		$('.popup-page').hide();
		return false;
	});
	$('#main-nav ul li a').click(function(){
		page_id = $(this).attr('rel');
		if(page_id != ''){
			$('.popup-page').hide();
			$('#main-nav ul li a').css('color','#C5C5C5');
			$(this).css('color','#FFFFFF');
			$('#popup-page-'+page_id).show();
	
			return false;
		}
	});
	
	$('input[name="wp-email-capture-name"]').click(function(){										  	
		if(!$(this).data('cleared')){
			$(this).data('cleared', true);
			$(this).val('');
		}
	});
	$('input[name="wp-email-capture-email"]').click(function(){									  	
		if(!$(this).data('cleared')){
			$(this).data('cleared', true);
			$(this).val('');
		}
	});

});

