// methods for shopping cart support	
function toggle_cart(){
	if (jQ('#cart_panel:visible').length) {
		jQ('#cart_content').height(jQ('#cart_content').height()).css('overflow', 'hidden');
		jQ('#cart_panel').fadeOut(100, function(){
			var cart_stat = jQ('#cart_panel').css('display');
			jQ.post('/cart.php?action=toggle_cart', {cart_visible: cart_stat});
		});
	} else {
		jQ('#cart_panel').fadeIn(100, function(){
			jQ('#cart_content').css({'overflow': 'auto', 'height':'80%'});
			var cart_stat = jQ('#cart_panel').css('display');
			jQ.post('/cart.php?action=toggle_cart', {cart_visible: cart_stat});
		});
	}
}

function checkout_cart() {
	cartQueue.add({
		url:'/cart.php?action=checkout',
		success:function(data) {
			if (data) {
				jQ('body').append(data);
			} else {
				alert('There was an error proceeding to PayPal checkout. Please try again later.');
			}
		},
		error: function(x, t, e) {
			alert('There was an error proceeding to PayPal chekout. Please try again later.');
		}
	});
}
/*
//deprecated (6/7/10) for checkout_cart
var valid_for_paypal = false;
function verify_paypal(){
	// gather info into json to validate

	var cart = {};

	cart.custom = jQ('#paypal_custom').attr('value');
	
	jQ('input[name=discount_rate_cart]').each(function() {
		cart.discount_rate_cart = this.value;
	});
	
	jQ('input[name=discount_amount_cart]').each(function() {
		cart.discount_amount_cart = this.value;
	});

	//items = [{
	//	no: iteration,
	//	name: title,
	//	quantity: quantity,
	//	amount: price
	//}, ...]
	cart.items = [];

	jQ('.paypalbuttonitem').each(function(i){
		i = i+1;
		cart.items.push({
			no: i,
			name: jQ('input[name=item_name_'+i+']').val(),
			quantity: jQ('input[name=quantity_'+i+']').val(),
			amount: jQ('input[name=amount_'+i+']').val(),
			id: jQ('input[name=item_number_'+i+']').val()
		});
	});

	JSONcart = jQ.toJSON(cart);

	if(valid_for_paypal){
		return true;
	}else{
		
		jQ.post('/cart.php?action=validate', {cart: JSONcart}, function(data){
			if(data == '1'){
				valid_for_paypal = true;
				jQ('#paypalform').submit();
			}else{
				alert('It looks like your shopping cart has been tampered with.  Please clear your cache and readd items to your cart');
			}

		});
		return false;		
		
	}
}*/

function addbundle_to_cart(json_data, callbackfunc) {
	woof('Adding product bundle...');
	var json_string = jQ.toJSON(json_data);
	cartQueue.add({
		url:'/cart.php?action=update',
		type:'post',
		data:{type:'bundle',user_id: userId, data:json_string},
		success:function(data) {
			if(data) {
				callbackfunc(true);
				refresh_cart(data);
				woof('Bundle successfully added to cart');
				refreshQty();
			} else {
				callbackfunc(false);
			}
		}
	});
}

function add_to_cart(json_data, callbackfun){
	cart_status_update('working...');
	var json_string = jQ.toJSON(json_data);
	cartQueue.add({
		url: '/cart.php?action=update', 
		data: {user_id: userId ,data: json_string},
		success: function(data){
			cart_status_update('Cart Updated');
			if (data) {
				callbackfun(true);
				refresh_cart(data);
				woof('Item successfully added to cart');
				refreshQty();
			}else{
				callbackfun(false);
			}
		}
	});
}

function apply_coupon(coupon_code) {
	coupon_code = coupon_code.replace(/[^a-zA-Z0-9]/g, '');
	cart_status_update('working...');
	cartQueue.add({
		url: '/cart.php?action=apply_coupon', 
		data: {code: coupon_code, user_id: userId},
		success: function(data){
			if (data) {
				refresh_cart(data);
				woof('Coupon successfully added to cart');
			} else {
				cart_status_update('There was an error');
			}
		},
		error: function(x, t, e) {
			cb.console(t);
		}
	});
}

function buyer_signup_start(){
	var username = jQ('#email').attr('value');
	var pass1 = jQ('#password1').attr('value');
	var pass2 = jQ('#password2').attr('value');
	
	if(username == ''){
		alert('Please provide an e-mail address');
		return false;
	}
	
	if(pass1 == ''){
		alert('Please supply a password');
		return false;
	}
	
	if(pass2 == ''){
		alert('Please retype your password');
		return false;
	}
	
	if(pass1 != pass2){
		alert('The passwords you have provide do not match');
		return false;
	}
	
	jQ.post('/cart.php?action=buyer_signup', {email: username, password1: pass1, password2: pass2}, function(data){
		if(data == '1'){
			refresh_cart();
		}else{
			jQ('#cart_content').empty().append(data);
		}
	});
}

function cart_logout(){
	jQ.post('/cart.php?action=buyer_logout', function(data){
		jQ('#cart_panel').parent().remove();
	});
	
}

function buyer_signup(){
	jQ.get('/cart.php?action=buyer_signup', {cart_create_buyer: '1'}, function(data){
		jQ('#cart_content').empty().append(data);
	});
}

// clears out everying inside the shopping cart
function clear_cart(){
	cart_status_update('working...');
	cartQueue.add({
		type:'post',
		url:'/cart.php?action=clear',
		success:function(data) {
			refresh_cart(data);
			woof('Cart Cleared');
		}
	});
}

// used to add or update items in cart
function update_quantity(pid)
{
	var quant = parseInt(jQ('#quantity_'+pid).val());
	var item_id = jQ('#quantity_'+pid).attr('item_id');
	if(quant != NaN) {
		cart_status_update('working...');
		cartQueue.add({
			type:'post',
			url:'/cart.php?action=quantity',
			data:{invoiceitem_id:item_id, quantity:quant},
			success:function(data) {
				refresh_cart(data);
				woof('Quantity Updated');
			}
		});
	}
}

function update_quantity_sub(pid)
{
	var quant = parseInt(jQ('#quantitysub_'+pid).val());
	var item_id = jQ('#quantitysub_'+pid).attr('item_id');
	if(quant != NaN) {
		cart_status_update('working...');
		cartQueue.add({
			type:'post',
			url:'/cart.php?action=quantity',
			data:{invoiceitem_id:item_id, quantity:quant},
			success:function(data) {
				refresh_cart(data);
				woof('Quantity Updated');
			}
		});
	}
}

function refresh_cart(data){
	if (typeof(data) == 'undefined') {
		jQ.get('cart.php?action=showcart', function(data) {
			refresh_cart(data);
		});
	} else {
		if (jQ('#cart_panel').length) {
			jQ('#cart_panel').parent().html(data);
		} else {
			jQ('body').append('<div id="cart_container"></div>');
			jQ('#cart_container').html(data);
		}
	}
}

function remove_item(pid) {
	cartQueue.add({
		type:'post',
		url:'/cart.php?action=remove',
		data:{product_id: pid},
		success:function(data) {
			refresh_cart(data);
			woof('Item removed from cart')
			refreshQty();
		}
	});
}

function calculate_shipping(id) {
	var post = {};
	jQ('#item_shipping_wrapper_'+id).find('input, select').each(function(){
		var name = jQ(this).attr('name');
		post[name] = jQ(this).val();
	});
	jQ.ajax({
		type:'post',
		url:'/cart.php?action=shippincalc',
		success:function(data){
			//alert(data);
		}
	});
}

function cart_login(){
	if(arguments[0] == 'guest'){
			cart_login_type = 'guest';
	}else{
		cart_login_type = 'buyer';
		
	}
		
		var username = jQ('#cart_username').attr('value');
		var pwd = jQ('#cart_pwd').attr('value');
		if(username == '' && cart_login_type != 'guest'){
			if(cart_login_type == 'buyer'){
				alert('Please provide your email');
			}else{
				alert('Please provide a username');
			}
			return false;
		}
		
		if(pwd == '' && cart_login_type != 'guest'){
			alert('Please provide a password');
			return false;
		}
		
		jQ.post('/cart.php?action=buyer_login', {uname: username, pass: pwd, cart_login_type: cart_login_type}, function(data){
			var response = parseInt(data);
			if(response == 0) {
				if (jQ('#buyer_login_error').length > 0) {
					jQ('#buyer_login_error')
				}
				jQ('#cart_content > h2').after('<span id="buyer_login_error">Email or Password are incorrect</span>');
			} else {
				// SUCCESS!!
				refresh_cart(data);

			}
		});
}

function cart_status_update(status) {
	jQ('#cart_panel_top_gradient').append('<div class="cart_status_update_space">'+status+'</div>');
	setTimeout("jQ('.cart_status_update_space:first').fadeOut(100)", 3000);
}

function woof(message){
	if (!jQ('#woof').is(':visible')){
	jQ('#woof_text').append('<p>'+message+'</p>');
	jQ('#woof').fadeIn(400).fadeTo(1500, 1).fadeOut(400, function(){jQ('#woof_text').html('');});
	}
}

function refreshQty(){
	var qty = 0;
	jQ('.num').each(function() {
    	qty += parseInt(jQ(this).html());
	});
	jQ('.qty_total').html(qty);
	return qty;
};
