/**
 * wishlist
 * 
 * Intializes wishlist dialog when add to wishlist link is clicked
 * amd checks if the product is existing in the user's wishlist
 */
function wishlist(cnt)
{
	var existing = false;
	
	if(cnt > 0) existing = true;

	if(existing)
	{
		$("#info_dialog").html('Product already added to wishlist.');
		displayInfoDialog();
	}
	else
	{
		$("#add_to_wishlist").dialog({
			bgiframe: true,
			resizable: false,
			height: 'auto',
			width: 350,
			modal: true,
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				'No': function() {
					$(this).dialog('destroy');
				},
				'Yes': function() {
					addToWishlist($('#w_product_id').val());
				}
			},
			close: function() {
				$(this).dialog('destroy');
			}
		});
	}
}

/**
 * addToWishlist
 * 
 * Processes adding of product to the user's wishlist
 */
function addToWishlist(productId)
{
	$.ajax({
		type: 'POST',
		url: siteURL + 'home/submit_wishlist/' + productId,
		dataType: 'json',
		cache: false,
		success: function(response) {
			if(response)
			{
				$("#info_dialog").html('Product successfully added to wishlist.');
			}
			else
			{
				$("#info_dialog").html('An error occurred.');
			}
			
			$("#add_to_wishlist").dialog('destroy');
			
			displayInfoDialog(true);
		}
	});
}

/**
 * displayInfoDialog
 * 
 * Intializes and shows information dialog
 */
function displayInfoDialog(from_wishlist)
{
	from_wishlist = from_wishlist || false;

	$("#info_dialog").dialog({
		bgiframe: true,
		resizable: false,
		width: 350,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			'Ok': function() {
				if(from_wishlist) window.location = siteURL + 'home/product_details/' + $('#w_product_id').val();
				else $(this).dialog('destroy');
			}
		},
		close: function() {
			if(from_wishlist) window.location = siteURL + 'home/product_details/' + $('#w_product_id').val();
			else $(this).dialog('destroy');
		}
	});
}

/**
 * confirmDeleteWishlist
 * 
 * Intializes and shows dialog for confirming if the product is to be deleted in the
 * wishlist
 */
function confirmDeleteWishlist(wishlistId)
{
	$('#info_dialog').dialog({
		bgiframe: true,
		resizable: false,
		height: 'auto',
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			'No': function() {
				$('#id').val(0);
				$(this).dialog('destroy');
			},
			'Yes': function() {
				$('#id').val(wishlistId);
				$('#delete').submit();
			}
		},
		close: function() {
			$('#id').val(0);
			$(this).dialog('destroy');
		},
		open: function() {
			$('#No').focus();
		}
	});
}

/**
 * emailFriend
 * 
 * Initializes and shows email to friend dialog
 */
function emailFriend(email)
{
	$("#display_email").html(email);
			
	if(email != "")
	{
		$("#email").val(email);
		$("#txtbox_email").hide();
	}	

	$("#email_to_friend").dialog({
		bgiframe: true,
		resizable: false,
		height: 'auto',
		width: 400,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		},
		buttons: {
			'Cancel': function() {
				resetEmailFriendDialog(false);
				$(this).dialog('destroy');
			},
			'Send': function() {
				$('#email_form').submit();
			}
		},
		close: function() {
			resetEmailFriendDialog(false);
			$(this).dialog('destroy');
		}
	});
}

/**
 * emailFriendRules
 * 
 * Setup email to friend form rules
 */
function emailFriendRules()
{
	//checks for invalid email format
	$.validator.addMethod('checkEmail', function() {
		var valid = false;
		
		$.ajax({
			url: siteURL + 'home/check_valid_email',
			type: 'POST',
			data: 'emails=' + $('#friend_email').val(),
			dataType: 'json',
			success: function(response)	{
				valid = response;
			},
			async: false
		});
		
		return valid;
	}, 'Friend\'s Email Address must not contain invalid email address(es).');

	$('#email_form').validate({
		debug: true,
		rules: {
			friend_email:
			{
				required: true,
				checkEmail: true
			},
			txtbox_email: {
				required: function(){
					var valid = false;
					
					//required if the user is not logged in
					if($('#email').val() == '') valid = true;
					
					return valid;
				},
				email: true
			},
			message: 'required'
		},
		messages: {
			friend_email: {
				required: $.Msgs('required', 'Friend\'s Email Address')
			},
			txtbox_email: {
				required: $.Msgs('required', 'Your Email Address'),
				email: $.Msgs('validEmail', 'Your Email Address')
			},
			message: {
				required: $.Msgs('required', 'Message')
			}
		},
		focusInvalid: true,
		errorElement: 'span',
		errorPlacement: function(error, element) {
			$.appendError(error, element, $('#err_div2'));
		},
		highlight: function(element, errorClass) {
			$.highlightFormElement(element, '#err_div2');
		},
		unhighlight: function(element, errorClass) {
			$.unhighlightFormElement(element, $('#err_div2'));
		},
		submitHandler: function(form) {
			sendEmail();
		}
	});
}

/**
 * resetEmailFriendDialog
 * 
 * Resets email to friend form
 */
function resetEmailFriendDialog(hide)
{
	$('#friend_email').val('');
	$('#invalid_email').val('');
	$('#txtbox_email').val('');
	$('#message').val('');
	
	$.unhighlightAll($('#email_form'), $('#err_div2'));
	$.unhighlightAll($('#email_form'), $('#msg_div2'));
	
	if (hide)
	{
		$('#email_to_friend').dialog('hide');
		$('#email_to_friend').dialog('destroy');
	}
}

/**
 * sendEmail
 * 
 * Processes sending of email to user's friend
 */
function sendEmail()
{
	if($('#email').val() == '') $('#email').val($('#txtbox_email').val());

	$.ajax({
		url: siteURL + 'home/send',
		type: 'POST',
		dataType: 'json',
		data:  $("#email_form").serialize(),
		success: function(response) {
			if(response)
			{
				$("#info_dialog").html('Your message has been sent.');
			}
			else
			{
				$("#info_dialog").html('An error occurred.');
			}
			
			resetEmailFriendDialog(true);
			
			displayInfoDialog();
		}
	});
}

/**
 * editProfileRules
 * 
 * Setup edit profile form rules
 */
function editProfileRules()
{
	// unique email
	$.validator.addMethod('checkEmail', function() {
		var valid = false;
		
		$.ajax({
			url: siteURL + 'home/check_email',
			type: 'POST',
			data: 'email=' + $('#email').val() + '&registered_user_id=' + $('#registered_user_id').val(),
			dataType: 'json',
			success: function(response)	{
				valid = response;
			},
			async: false
		});
		
		return valid;
	}, $.Msgs('unique', 'Email Address'));

	$('#user_registration').validate({
		debug: true,
		rules: {
			email: {
				required: true,
				email: true,
				checkEmail: true
			},
			last_name: 'required',
			first_name: 'required'
		},
		messages: {
			email: {
				required: $.Msgs('required', 'Email Address'),
				validEmail: $.Msgs('validEmail', 'Email Address')
			},
			last_name: {
				required: $.Msgs('required', 'Last Name')
			},
			first_name: {
				required: $.Msgs('required', 'First Name')
			}
		},
		focusInvalid: true,
		errorElement: 'span',
		errorPlacement: function(error, element) {
			$.appendError(error, element, $('#err_div'));
		},
		highlight: function(element, errorClass) {
			$.highlightFormElement(element, '#err_div');
		},
		unhighlight: function(element, errorClass) {
			$.unhighlightFormElement(element, $('#err_div'));
		},
		submitHandler: function(form) {
			form.submit();
		}
	});
}

/**
 * setupChangePassRules
 * 
 * Setup change password form rules
 */
function setupChangePassRules()
{
	// check valid old password
	$.validator.addMethod('checkOldPass', function() {
		var valid = false;
		
		$.ajax({
			url: siteURL + 'home/check_password',
			type: 'POST',
			data: 'password=' + $('#old_password').val() + '&registered_user_id=' + $('#registered_user_id').val(),
			dataType: 'json',
			success: function(response)	{
				valid = response;
			},
			async: false
		});
		
		return valid;
	}, 'Old Password is invalid.');

	// check if new password and confirm new password match
	$.validator.addMethod('checkNewPass', function() {
		var valid = true;
		
		if($('#new_password').val() != $('#confirm_password').val()) valid = false;
		
		( ! valid ? $.highlightFormElement($('#new_password')) : $.unhighlightFormElement($('#new_password')));
		
		return valid;
	}, $.Msgs('match', 'New Password', 'Confirm New Password'));
	
	$('#user_login').validate({
		debug: true,
		rules: {
			old_password: {
				required: true,
				checkOldPass: true
			},
			new_password: {
				required: true
			},
			confirm_password: {
				required: true,
				checkNewPass: true
			}
		},
		messages: {
			old_password: {
				required: $.Msgs('required', 'Old Password')
			},
			new_password: {
				required: $.Msgs('required', 'New Password')
			},
			confirm_password: {
				required: $.Msgs('required', 'Confirm New Password')
			}
		},
		focusInvalid: true,
		errorElement: 'span',
		errorPlacement: function(error, element) {
			$.appendError(error, element, $('#err_div'));
		},
		highlight: function(element, errorClass) {
			$.highlightFormElement(element, '#err_div');
		},
		unhighlight: function(element, errorClass) {
			$.unhighlightFormElement(element, $('#err_div'));
		},
		submitHandler: function(form) {
			form.submit();
		}
	});
}

/**
 * userRegistrationRules
 * 
 * Setup user registration form rules
 */
function userRegistrationRules()
{
	//$('#submit_form').click(function() {
	//	$('#submit_form').val("processing registration...");
	//	$('#submit_form').attr('disabled', 'disabled');
	//});	
	
	// unique username
	$.validator.addMethod('checkUsername', function() {
		var valid = false;
		
		$.ajax({
			url: siteURL + 'home/check_username',
			type: 'GET',
			data: 'username=' + $('#reg_username').val(),
			dataType: 'json',
			success: function(response)	{
				valid = response;
			},
			async: false
		});
		
		return valid;
	}, $.Msgs('unique', 'User Name'));
	
	// unique email
	$.validator.addMethod('checkEmail', function() {
		var valid = false;
		
		$.ajax({
			url: siteURL + 'home/check_email',
			type: 'GET',
			data: 'email=' + $('#email').val(),
			dataType: 'json',
			success: function(response)	{
				valid = response;
			},
			async: false
		});
		
		return valid;
	}, $.Msgs('unique', 'Email Address'));
	
	// check if password and confirm password match
	$.validator.addMethod('checkPassword', function() {
		var valid = true;
		
		if($('#reg_password').val() != $('#reg_confirm_password').val()) valid = false;
		
		( ! valid ? $.highlightFormElement($('#reg_password')) : $.unhighlightFormElement($('#reg_password')));
		
		return valid;
	}, $.Msgs('match', 'Password', 'Confirm Password'));
	
	$('#user_registration').validate({
		debug: true,
		rules: {
			reg_username: {
				required: true,
				checkUsername: true
			},
			reg_password: {
				required: true
			},
			reg_confirm_password: {
				required: true,
				checkPassword: true
			},
			email: {
				required: true,
				email: true,
				checkEmail: true
			},
			last_name: 'required',
			first_name: 'required'
		},
		messages: {
			reg_username: {
				required: $.Msgs('required', 'Username')
			},
			reg_password: {
				required: $.Msgs('required', 'Password')
			},
			reg_confirm_password: {
				required: $.Msgs('required', 'Confirm Password')
			},
			email: {
				required: $.Msgs('required', 'Email Address'),
				validEmail: $.Msgs('validEmail', 'Email Address')
			},
			last_name: {
				required: $.Msgs('required', 'Last Name')
			},
			first_name: {
				required: $.Msgs('required', 'First Name')
			}
		},
		focusInvalid: true,
		errorElement: 'span',
		errorPlacement: function(error, element) {
			$.appendError(error, element, $('#err_div'));
		},
		highlight: function(element, errorClass) {
			$.highlightFormElement(element, '#err_div');
		},
		unhighlight: function(element, errorClass) {
			$.unhighlightFormElement(element, $('#err_div'));
		},
	    //invalidHandler: function(form, validator) {
		//	$('#submit_form').val("submit");
		//	$('#submit_form').removeAttr('disabled');
	    //},
		submitHandler: function(form) {
			$('#submit_form').val("processing registration...");
			$('#submit_form').attr('disabled', 'disabled');
			form.submit();
		}
	});
}

/**
 * submitUser
 * 
 * Submits user form
 */
function submitUser()
{
	var msg = 'You have successfully registered in Blackwater website.';
	
	$.ajax({
		url: siteURL + 'home/submit_registration',
		type: 'POST',
		dataType: 'json',
		data: $('#user_registration').serialize(),
		success: function(response) {
			if (response != false) listUsers(msg);
			else $.showError();
		}
	});
}

/**
 * checkLogin
 * 
 * Checks registered users log in form and submits the form if it is valid
 */
function checkLogin() 
{
	var msg = '';
	
	if($('#username').val() == null || $('#username').val() == '') msg = '<span class="ui-icon ui-icon-alert" style="float: left; vertical-align: top; margin-right: .3em;"></span>User name is required.<br />';
	if($('#password').val() == null || $('#password').val() == '') msg = msg + '<span class="ui-icon ui-icon-alert" style="float: left; vertical-align: top; margin-right: .3em;"></span>Password is required.';
	
	if($('#username').val() != null && $('#username').val() != '' && 
	$('#password').val() != null && $('#password').val() != '')
	{
		$.ajax({
			url: siteURL + 'home/check_login',
			type: 'POST',
			data: 'username=' + $('#username').val() + '&password=' + $('#password').val(),
			dataType: 'json',
			success: function(response)	{
				if( ! response) msg = '<span class="ui-icon ui-icon-alert" style="float: left; vertical-align: top; margin-right: .3em;"></span>Invalid user name and/or password.';
			},
			async: false
		});
	}
	
	if(msg != '')
	{
		$("#err_div_dialog").html(msg);

		$("#err_div_dialog").dialog({
			bgiframe: true,
			resizable: false,
			width: 350,
			modal: true,
			title: 'Login Error',
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			buttons: {
				'Ok': function() {
					$(this).dialog('destroy');
				}
			},
			close: function() {
				$(this).dialog('destroy');
			}
		});
	}
	else
	{
		$('#userlogin').submit();
	}
}

/**
 * logoutUser
 * 
 * Destroys session data and redirects to login page
 */
function logoutUser()
{
	$.ajax({
		type: 'GET',
		url: siteURL + 'home/logout/',
		dataType: 'json',
		success: function(response) {
			window.location = siteURL + 'admin/show_login/logout/' + new Date().getTime();
		}
	});
}

/**
 * setupForgotPassRules
 * 
 * Setup forgor password form rules
 */
function setupForgotPassRules()
{
	// check if email is existing
	$.validator.addMethod('checkEmail', function() {
		var valid = false;
		
		$.ajax({
			url: siteURL + 'home/check_email',
			type: 'POST',
			data: 'email=' + $('#email').val(),
			dataType: 'json',
			success: function(response)	{
				valid = (response ? false : true);
			},
			async: false
		});

		return valid;
	}, 'Email Address is not registered in hotpink lingerie website.');
	
	$('#user_login').validate({
		debug: true,
		rules: {
			email: {
				required: true,
				email: true,
				checkEmail: true
			}
		},
		messages: {
			email: {
				required: $.Msgs('required', 'Email Address'),
				validEmail: $.Msgs('validEmail', 'Email Address')
			}
		},
		focusInvalid: true,
		errorElement: 'span',
		errorPlacement: function(error, element) {
			$.appendError(error, element, $('#err_div'));
		},
		highlight: function(element, errorClass) {
			$.highlightFormElement(element, '#err_div');
		},
		unhighlight: function(element, errorClass) {
			$.unhighlightFormElement(element, $('#err_div'));
		},
		submitHandler: function(form) {
			form.submit();
		}
	});
}

/**
 * menu
 * 
 * Shows categories and sub-categories menu if the product page is loaded
 * and hides the main menu
 */
function menu()
{
	$('.list').show(2000);
	$('.main_menu').hide(2000); 
}

/**
 * setupMenu
 * 
 * Setup category and sub-category menu and its functionalities
 */
function setupMenu(catId, fromCategory)
{
	var cntr = 0;
	
	//iterate through all div with category_ id
	$('div[id^="category_"]').each(function() {
		cntr = cntr + 1;

		var id = $(this).attr('id');
		id = id.replace('category', 'cat_ul');

		$('#' + id).hide();
		
		$('#sub_category_name').html('');
		$('#breadcrums_sub_cat').html('');
		
		//checks if the specific category should be initially opened
		if(catId == '')
		{
			if(cntr == 1)
			{
				$('#' + id).show();
				$('#category_name').html($('#' + $(this).attr('id')).text() + '&nbsp;>');
				
				id = id.replace('cat_ul_', '');
				
				$('#products').load(siteURL + 'home/product_content/' + id + '/' + true);
			}
		}
		else
		{
			id = id.replace('cat_ul_', '');
			
			if(catId == id && fromCategory)
			{
				$('#cat_ul_' + id).show();
				$('#category_name').html($('#' + $(this).attr('id')).text() + '&nbsp;>');
				$('#products').load(siteURL + 'home/product_content/' + catId + '/' + true);
			}
		}
		
		//if the a specific category is clicked the sub-menu should be showed
		//and the products under it should be displayed in the page
		$(this).click(function() {
			$('#sub_category_name').html('');
			$('#breadcrums_sub_cat').html('');
		
			var id = $(this).attr('id');
			id = id.replace('category', 'cat_ul');
			
			if( ! $('#' + id).is(":visible"))
			{
				$('ul[id^="cat_ul"]').hide(1000);
				$('#' + id).show(1000);
			}

			$('#category_name').html($('#' + $(this).attr('id')).text() + '&nbsp;>');

			id = id.replace('cat_ul_', '');
			$('#products').load(siteURL + 'home/product_content/' + id + '/' + true);
		});
	});
	
	//iterate through all div with sub_category_ id
	$('li[id^="sub_category_"]').each(function() {
		var id = $(this).attr('id');
		id = id.replace('sub_category_', '');
		
		if(catId == id && ! fromCategory)
		{
			$('#cat_ul_' + $('#sub_category_id_' + id).val()).show(1000);
			$('#category_name').html($('#category_' + $('#sub_category_id_' + id).val()).text() + '&nbsp;>');
			$('#sub_category_name').html($('#' + $(this).attr('id')).text());
			$('#breadcrums_sub_cat').html('&nbsp;' + $('#sub_category_name').html());
			$('#products').load(siteURL + 'home/product_content/' + catId);
		}
		
		//if the a specific sub-category is clicked the products under it 
		//should be displayed in the page
		$(this).click(function() {
			$('#sub_category_name').html($('#' + $(this).attr('id')).text());
			$('#breadcrums_sub_cat').html('&nbsp;' + $('#sub_category_name').html());
			
			var id = $(this).attr('id');
			id = id.replace('sub_category_', '');
			
			$('#products').load(siteURL + 'home/product_content/' + id);
		});
	});
}

/**
 * setupContactUsRules
 * 
 * Setup contact us form rules
 */
function setupContactUsRules()
{
	$('#email_form').validate({
		debug: true,
		rules: {
			name: 'required',
			email: {
				required: true,
				email: true
			},
			feedback: 'required'
		},
		messages: {
			name: {
				required: $.Msgs('required', 'Name')
			},
			email: {
				required: $.Msgs('required', 'Email Address'),
				validEmail: $.Msgs('validEmail', 'Email Address')
			},
			feedback: {
				required: $.Msgs('required', 'Feedback')
			}
		},
		focusInvalid: true,
		errorElement: 'span',
		errorPlacement: function(error, element) {
			$.appendError(error, element, $('#err_div'));
		},
		highlight: function(element, errorClass) {
			$.highlightFormElement(element, '#err_div');
		},
		unhighlight: function(element, errorClass) {
			$.unhighlightFormElement(element, $('#err_div'));
		},
		submitHandler: function(form) {
			form.submit();
		}
	});
}

/**
 * setupCartRules
 * 
 * Setup shopping cart form rules
 */
function setupCartRules()
{
	$('#cart_form').validate({
		debug: true,
		rules: {
			color_id: 'required',
			size_id: 'required',
			qty: 'required'
		},
		messages: {
			color_id: {
				required: $.Msgs('required', 'Color')
			},
			size_id: {
				required: $.Msgs('required', 'Size')
			},
			qty: {
				required: $.Msgs('required', 'Quantity')
			}
		},
		focusInvalid: true,
		errorElement: 'span',
		errorPlacement: function(error, element) {
			$.appendError(error, element, $('#err_div'));
		},
		highlight: function(element, errorClass) {
			$.highlightFormElement(element, '#err_div');
		},
		unhighlight: function(element, errorClass) {
			$.unhighlightFormElement(element, $('#err_div'));
		},
		submitHandler: function(form) {
			checkCart();
		}
	});
}

/**
 * checkCart
 * 
 * Processes cart if it should be added or updated in the current session
 */
function checkCart()
{
	$.ajax({
		url: siteURL + 'home/check_cart',
		type: 'POST',
		dataType: 'json',
		data: $('#cart_form').serialize(),
		success: function(response) {
			if(Number(response) > 0) window.location = siteURL + 'home/shopping_cart';
			else window.location = siteURL + 'home/user_registration';
		}
	});
}

/**
 * deleteItem
 * 
 * Processes deleting of an item from the cart
 */
function deleteItem(rowId)
{
	$.ajax({
		url: siteURL + 'home/delete_item',
		type: 'POST',
		dataType: 'json',
		data: 'rowid=' + rowId,
		success: function(response) {
			window.location = siteURL + 'home/shopping_cart';
		}
	});
}

/**
 * checkCartQty
 * 
 * Checks qty inputted of the user is not zero 
 * and returns the number of items with error
 */
function checkCartQty()
{
	$('#rowids').val('');
	var err_cnt = 0;
	var rowids = '';

	$('input[id^="qty_"]').each(function() {
		if(rowids == '') rowids = $(this).attr('id');
		else rowids += '|' + $(this).attr('id');
		
		if($(this).val() == '' || Number($(this).val()) == 0)
		{
			$.highlightFormElement($('#' + $(this).attr('id')));
			err_cnt += 1;
		}
		else
		{
			$.unhighlightFormElement($('#' + $(this).attr('id')));
		}
	});
	
	$('#rowids').val(rowids);
	
	return err_cnt;
}

/**
 * submitCartQty
 * 
 * Submits cart form if there are no errors else show error
 */
function submitCartQty()
{
	var err_cnt = checkCartQty();

	if(err_cnt > 0)
	{
		$.showError('Quantity is required and should be greater than 0.');
	}
	else
	{
		$.unhighlightAll($('#cart_form'), $('#err_div'));
		$.unhighlightAll($('#cart_form'), $('#msg_div'));
		
		$('#cart_form').submit();
	}
}

/**
 * checkOut
 * 
 * Checks qty inputted of the user per item against the current stock in the inventory
 * and submits the cart for checkout
 */
function checkOut(userId)
{
	if(Number(userId) > 0)
	{
		var err_cnt = checkCartQty();
		
		if(err_cnt > 0)
		{
			$.showError('Quantity is required and should be greater than 0.');
		}
		else
		{
			$.unhighlightAll($('#cart_form'), $('#err_div'));
			$.unhighlightAll($('#cart_form'), $('#msg_div'));
			
			$.ajax({
				url: siteURL + 'home/update_cart/0',
				type: 'POST',
				dataType: 'json',
				data: $('#cart_form').serialize(),
				async: false
			});
			
			var err_cnt1 = 0;

			$('input[id^="qty_"]').each(function() {
				var id = $(this).attr('id');
				var rowid = id.split('_');
				rowid = rowid.slice(1);
				var value = $(this).val();

				$.ajax({
					url: siteURL + 'home/check_inventory',
					type: 'POST',
					dataType: 'json',
					data: 'product_id=' + $('#product_id_' + rowid).val() + '&color_id=' + $('#color_id_' + rowid).val() + '&size_id=' + $('#size_id_' + rowid).val(),
					success: function(response) {
						if(value > response)
						{
							$('#td_stock_' + rowid).html(response);
							$.highlightFormElement($('#' + id));
							err_cnt1 += 1;
						}
						else
						{
							$('#td_stock_' + rowid).html('');
							$.unhighlightFormElement($('#' + id));
						}
					},
					async: false
				});
			});
			
			if(err_cnt1 > 0)
			{
				$('td[id^="td_stock"]').show();
				$.showError('Some items have insufficient stocks.');
			}
			else
			{
				$('td[id^="td_stock"]').hide();
				
				$.unhighlightAll($('#cart_form'), $('#err_div'));
				$.unhighlightAll($('#cart_form'), $('#msg_div'));
				
				//SUCCESSFUL CHECKOUT CODE GOES HERE
				
				window.location = siteURL + 'home/checkout';
				
			}
		}
	}
	else
	{
		window.location = siteURL + 'home/user_registration';
	}
}


function checkoutRules()
{

	$.validator.addMethod('checkDeclared', function() {
		if ($('#shipping_declared').val() < "500") {
			return false;
		}
		return true;
	}, "Declared value must be greater than Php 500.00.");
	
	$('#shipping_form').validate({
		rules: {
			shipping_email: {
				email: true
			},
			shipping_last_name: 'required',
			shipping_first_name: 'required',
			shipping_address1: 'required',
			shipping_city: 'required',
			shipping_postal_code: 'required',
			shipping_declared: 'checkDeclared'
		},
		messages: {
			shipping_email: {
				required: $.Msgs('required', 'Email Address')
			},
			shipping_last_name: {
				required: $.Msgs('required', 'Last Name')
			},
			shipping_first_name: {
				required: $.Msgs('required', 'First Name')
			},
			shipping_address1: {
				required: $.Msgs('required', 'Address 1')
			},
			shipping_city: {
				required: $.Msgs('required', 'City')
			},
			shipping_postal_code: {
				required: $.Msgs('required', 'Postal Code')
			}
		},
		focusInvalid: true,
		errorElement: 'span',
		errorPlacement: function(error, element) {
			$.appendError(error, element, $('#err_div'));
		},
		highlight: function(element, errorClass) {
			$.highlightFormElement(element, '#err_div');
		},
		unhighlight: function(element, errorClass) {
			$.unhighlightFormElement(element, $('#err_div'));
		},
		submitHandler: function(form) {
			set_shipping_details();
		}
	});
}

function set_shipping_details()
{
	$.ajax({
		url: siteURL + 'home/set_shipping_details',
		type: 'POST',
		dataType: 'json',
		data: $('#shipping_form').serialize(),
		success: function(response) {
			if (response != false) window.location = siteURL + "home/review_order";
			else $.showError();
		}
	});
}

function activateCouponCode()
{

	var error = "The coupon code you entered is invalid, expired, or ineligible for the items you are purchasing.";

	if ($.trim($('#coupon_code').val()) == "") {
		$.showError(error);
		return;
	}

	$('#btn_coupon').val('Processing request...');
	$('#btn_coupon').attr('disabled', 'disabled');
	
	$.ajax({
		url: siteURL + 'home/check_coupon/' + $('#coupon_code').val(),
		type: 'GET',
		dataType: 'json',
		success: function(response) {
			if (response != false) {
				//window.location.reload(true);
				window.location = siteURL + 'home/shopping_cart';
			} else {
				$.showError(error);
				$('#btn_coupon').val('Activate Coupon Code');
				$('#btn_coupon').removeAttr('disabled');
			}	
		}
	});
}

function removeCouponCode()
{
	$('#btn_coupon').val('Processing request...');
	$('#btn_coupon').attr('disabled', 'disabled');

	$.ajax({
		url: siteURL + 'home/remove_coupon/',
		type: 'GET',
		dataType: 'json',
		success: function(response) {
			//window.location.reload(true);
			window.location = siteURL + 'home/shopping_cart';
			//$('#btn_coupon').val('Activate Coupon Code');
			//$('#btn_coupon').removeAttr('disabled');
		}
	});
}



