// shop js file
$().ready(function() {


	//Activate FancyBox
	$(".productDetails").fancybox({
		'frameWidth': 905,
		'frameHeight' : 540,
		'zoomSpeedOut' : 0,
	     'hideOnContentClick': false,
        'hideOnOverlayClick': false

	});

	
	
	
	
	$("#update_cart").click(function(){

	   $.ajax({
				url: base+"cart?shop=manage",
				type: 'POST',
				data: $("#formCart").serialize(),
				dataType: 'json',
				success: function(response){
				   $().find("input[type=checkbox]").filter(":checked").each(function(){
                        $('#row_'+this.value).remove();
                    });

					$(".total").text(response.cart.total)
					$(".total_items").text(response.cart.total_items)					
					
					
					$.each(response.cart.items,function(i,item) {
						$("#price_"+item.product_id).text(item.price*item.items)
		            });

					
				}
		});
		return false;
	});

		
	$("#payment_method").change(function(){
		$(".payments").hide();
		$("#"+$(this).val()).show();
	});
	
	geo();
	
	if($("#bill_country").val() == "") {
		$("#bill_country").val(15);
		$(".form_country").change()
	}
	
	  $("#checkoutForm").validate({
            invalidHandler: function(form, validator) {
                  var errors = validator.numberOfInvalids();
                  if (errors) {
                    var message = errors == 1
                      ? 'You missed <em class="error">1 field</em>. It has been highlighted'
                      : 'You missed <em class="error">' + errors + '</em> fields. They have been highlighted';
//                    alert(message,function(){
                                    //$("#applyjobForm").submit();
  //                          });

                  } else {
                    $("div.error").hide();
                  }
                },
                        ignore: ':not(:visible)',
                onclick: false,
                rules: {
                            password1: {
                                required:true,
                                minlength:5
                            },
                            password12: {
                              equalTo: "#password1"
                            }
                    }
      });



	$("#account_loged_process").click(function(){
	
		window.location=base+"checkout/billing";
	});
	
   $(".account").change(function(){
            $(".panels").hide();
            if($(this).val() == "login") {
                    $("#login").show();
            }else if($(this).val() == "register") {
                    $("#register").show();
            }else if($(this).val() == "skip") {
                    $("#skip").show();
            }
    });
	 // click on login or register
    $(".loginbutton").click(function(){

            if($("#checkoutForm").valid()) {
                // check email ? if password is empty
                        if($(".account").val() == "login") {
                                saveCheckout();
                        }else if($(".account").val() == "register") {
                                $.ajax({
                                url: base+"?shop=email",
                                type: 'POST',
                                data: "username="+$("#username1").val(),
                                dataType: 'json',
                                success: function(response){
                                        if(response.exists) {
                                                $("#username1").focus().select();
                                                alert("This email address is already in system,choose another one");
                                        }

                                        if(response.isnew) {

                                                // log them in  + create 
                                                //saveCheckout();                                       
                                        }

                                }
                        });

                        }else if($(".account").val() == "skip") {
                                $("#skip").show();
                        }



                    // try to log them if the password exists


            }
    });


	
	// make sure billing is copied to shipping if not checked
	
	$("#step2 input").keyup(function(i){
		
		if(!$("#ship_notsame").is(":checked")) {
			var name = $(this).attr('id').split("_")[1]
			$("#ship_"+name).val($(this).val());
		}
	});

	$("#ship_notsame").click(function(){
		if($(this).is(":checked")) {
			$("#step3").show("slow");
		} else {
			$("#step3").hide("slow");		
		}
		
	});
	

	$(".submit_checkout").click(function(){
		if($("#checkoutForm").valid()) {
			saveCheckout();
		}
	});


	$("#order_ok").click(function(){
		saveCheckout('buy');	
	});
	
	// main form submit
	$("#checkoutForm").submit(function(){
		return false;
	});
	


	// add product
	$(".products").click(function(){
		id=$(this).attr('id').split("_")[1]
		link = $(this)
		$.ajax({
					url: base+"?shop=add",
					type: 'POST',
					data: "productid="+id,
					dataType: 'json',
					success: function(response){
						if(response.messages) {
							showMessage("Product not saved!",response.messages[1]);						
						}

						if(response.carthtml) {
							$("#shop_cart").html(response.carthtml);
						}

						if(response.cart[id] && $("#removeproduct_"+id).length <= 0) {
							var r = '<a href="#rem" id="removeproduct_'+id+'" class="remove_products"  title=remove from cart">remove from cart</a>';
							link.after(r);						
						}
					
					}
				});
	
	
	
	})
	


	$(".remove_products").click(function(){
		id=$(this).attr('id').split("_")[1]
		$.ajax({
					url: base+"?shop=del",
					type: 'POST',
					data: "productid="+id,
					dataType: 'json',
					success: function(response){
						if(response.messages) {
							showMessage("Product not removed!",response.messages[1]);						
						}
						
						if(response.carthtml) {
							$("#shop_cart").html(response.carthtml);
						}

					}
				});
	
	
	})


	$("#cart_empty").click(function(){
		$.ajax({
					url: base+"?shop=clean",
					type: 'POST',
					dataType: 'json',
					success: function(response){
						if(response.messages) {
							showMessage("Cart not empty!",response.messages[1]);						
						}
						
						if(response.carthtml) {
							$("#shop_cart").html(response.carthtml);
						}
						
						

					}
				});
	
	});

});


// add to shopping cart
function addToCart(id, buy) {

	$.ajax({
		url: base+"cart?shop=add",
		type: 'POST',
		data: $("#product_form_"+id).serialize(),
		dataType: 'json',
		timeout: 2000,
		success: function(response){
			if (buy) {
				window.location=base+'cart';
			} else if(response.carthtml) {
				$(".total").text(response.cart.total)
				$(".total_items").text(response.cart.total_items)				
				$('#shopping_cart').html(response.carthtml);
			}
		}
	});
}



function geo() {
	// load states based on country
	$(".form_country").change(function(){
		if($(this).val() > 0) {
			out = 	$(this).parent().siblings().find(".form_state");
			$.get(base+"checkout?shop=state&country_id=" + $(this).val(), function(data) {
				$(out).html(data);
			});
		}
	});
}


function saveCheckout(what,callback) {

		if(what == null) {
			what = "account";
		}



		$.ajax({
					url: base+"checkout?shop="+what,
					type: 'POST',
					data: $("#checkoutForm").serialize(),
					dataType: 'json',
					success: function(response){
						if(response.error) {
							alert(response.error);
							return false;
						}

						if(response.postage) {
							$("#ch_postage").html(response.postage);
							// init postage button
							// postage 
							$("#postage").click(function(){
								// move to next secction - payment (no saving needed)
						
							});
						}

						if(response.payment) {
							$("#payform").html(response.payment);
						}


						if(response.paypal) {
							$("#paypalform").html(response.paypal);
							$("#paypal_form").submit();
						}
						if(response.forward) {
							window.location=response.forward;
						}
						
						if(response.ship) {
							$("#shipping_form").html(response.ship);
						}

						if(response.bill) {
							$("#billing_form").html(response.bill);
						}
						geo();
						if(callback != null && typeof callback == 'function' ) {
							callback();
						}
						
						
					}
				});
}

