var g_visitorLogged = false;

// Localization
var g_STR_SOME_FIELDS_ARE_EMPTY         = "";
var g_STR_PLEASE_FILL_SHIPPING_ADDRESS  = "";
var g_STR_PWD_AND_CONFIRM_NOT_MATCH     = "";


/* Validation functions */
function toggle_shipping()
{
    var check = $$(".billing_is_shipping_check");
    
    if (check[0].checked) {
        //Copy informations
        $("shipping_addr").value    = $("billing_addr").value;
        $("shipping_city").value    = $("billing_city").value;
        $("shipping_state").value   = $("billing_state").value;
        $("shipping_country").value = $("billing_country").value;
        $("shipping_zip").value     = $("billing_zip").value;
    }
    else {
        // Clear informations
        $("shipping_addr").value    = "";
        $("shipping_city").value    = "";
        $("shipping_state").value   = "1";
        $("shipping_country").value = "1";
        $("shipping_zip").value     = "";
    }
    
}

function create_account()
{
    var params = $("frm_create_account").serialize();
    
    $("img_loader").style.display   = "inline";
    $("img_ok").style.display       = "none";
    
    new Ajax.Request("/app/actions/create_account.php", {
                    method: "post",
					parameters: params,
					onSuccess: function (transport) {
						var res = transport.responseText.evalJSON(true);
						
						if (res["id"] > 0 && $("action").value == "add" && res["auto_login"] == 1) {
							// Login user
							login_user_direct($("email").value, $("password").value);
						}
						
						$("img_loader").style.display   = "none";
                        $("img_ok").style.display       = "inline";
					}
    });
}

function validate_email_exists(obj)
{
	new Ajax.Request("/app/actions/validate_email.php", {
					method: "post",
					parameters: "email="+obj.value+"&field="+obj.id+"&moduleName="+$("moduleName").value+
								"&id="+$("id").value+"&action="+$("action").value,
					onSuccess: function (transport) {
						var res = transport.responseText.evalJSON(true);
						
						if (res["error"] != 0) {
							alert(res["message"]);
							$(res["focus"]).focus();
						}
					}
	});
}

function validate_create_account()
{
    var nInvalid    = 0;
    var bSave       = true;
    var inputs      = $$(".input_mandatory");
    
    inputs.each(function(obj){
        if (obj.value == "") {
            nInvalid++;
        }
    });
    
    if (nInvalid == 0) {
        // Validate the shipping address
        var check = $$(".billing_is_shipping_check");
        
        if (check[0] && !check[0].checked) {
            var inputs      = $$(".input_mandatory_shipping");
    
            inputs.each(function(obj){
                if (obj.value == "") {
                    nInvalid++;
                }
            });
            
            if (nInvalid > 0) {
               // Some fields were left empty
                alert(g_STR_PLEASE_FILL_SHIPPING_ADDRESS);
                $("shipping_addr").focus();
                return;
            }
        }
        
        // Validate the password
        if ($("password").value == $("password_confirm").value) {
            // Everything is fine, save now!
            create_account();
        }
        else {
            alert(g_STR_PWD_AND_CONFIRM_NOT_MATCH);
            $("password").focus();
        }
    }
    else {
        // Some fields were left empty
        alert(g_STR_SOME_FIELDS_ARE_EMPTY);
    }
}

function validate_for_empty(obj)
{
    if (obj) {
        if (obj.value == "") {
            obj.style.backgroundColor = "#ff9999";
        }
        else {
            obj.style.backgroundColor = "#ffffff";
        }
    }
}

/* User functions */
function display_login_form(divId)
{
	Effect.Fade("header_welcome_content", {
				duration: 0.2, 
				afterFinish: function() {
					Effect.Appear("header_welcome_login", {duration: 0.2, afterFinish: function(){$("email_login").focus();}});
				}
	});
}

function display_forgot_form(divId)
{
	Effect.Fade("header_welcome_login", {
				duration: 0.2, 
				afterFinish: function() {
					Effect.Appear("header_forgot_password", {duration: 0.2, afterFinish: function(){$("email_forgot").focus();}});
				}
	});
}

function login_user_direct(email, password)
{
	var params = "email_login="+email+"&password_login="+password;
	
	new Ajax.Request("/app/actions/login_user.php", {
					method: "post",
					parameters: params,
					onSuccess: function (transport) {
						var res = transport.responseText.evalJSON(true);
						
						if (res["error"] != 0) {
							$("header_login_status").innerHTML = res["message"];
							$(res["focus"]).focus();
						}
						else {
							window.location.reload();
						}
					}
	});
}

function login_user(formId)
{
	var params = $(formId).serialize();
	
	new Ajax.Request("/app/actions/login_user.php", {
					method: "post",
					parameters: params,
					onSuccess: function (transport) {
						var res = transport.responseText.evalJSON(true);
						
						if (res["error"] != 0) {
							$("header_login_status").innerHTML = res["message"];
							$(res["focus"]).focus();
						}
						else {
							window.location.reload();
						}
					}
	});
}

function send_pwd(formId)
{
	var params = $(formId).serialize();
	
	new Ajax.Request("/app/actions/send_pwd.php", {
					method: "post",
					parameters: params,
					onSuccess: function (transport) {
						var res = transport.responseText.evalJSON(true);
						
						$("header_forgot_status").innerHTML = res["message"];
						
						if (res["error"] != 0) {
							$(res["focus"]).focus();
						}
					}
	});
}


/* Order functions */
function updateOrderStatus(id, new_status)
{
	var params = "moduleName=orders&action=edit&id="+id+"&status="+new_status;
	
	$("img_loader_"+id).style.display   = "inline";
    $("img_ok_"+id).style.display       = "none";
    
    new Ajax.Request("/app/actions/update_order_status.php", {
					method: "post",
					parameters: params,
					onSuccess: function (transport) {
						var res 	= transport.responseText.evalJSON(true);
						$("img_loader_"+id).style.display   = "none";
    					$("img_ok_"+id).style.display       = "inline";
					}
	});
}

/* Cart functions */
function order(formId)
{
    if (!g_visitorLogged) {
        display_login_form("header_welcome_login");
        new Effect.ScrollTo("header_welcome_login", {
            afterFinish: function() {
                new Effect.Highlight("email_login", {duration: 2.0});
            }
        });
    }
    else {
        //Order!
        window.location = "/process_order/";
    }
}

function update_cart_quantities(newQt)
{

}

function update_cart_totals()
{
    new Ajax.Request("/app/actions/update_cart_totals.php", {
					method: "post",
					onSuccess: function (transport) {
						var res = transport.responseText.evalJSON(true);
						
						$("cart_subtotal_amount").innerHTML = res["sub_total"]+"$";
						new Effect.Highlight("cart_subtotal_amount", {duration: 2.0});
						
						$("shipping").innerHTML = res["shipping"]+"$";
						new Effect.Highlight("shipping", {duration: 2.0});
						
						$("GST").innerHTML = res["gst"]+"$";
						new Effect.Highlight("GST", {duration: 2.0});
						
						$("PST").innerHTML = res["pst"]+"$";
						new Effect.Highlight("PST", {duration: 2.0});
						
						$("timbre").innerHTML = res["timbre_regie"]+"$";
						new Effect.Highlight("timbre", {duration: 2.0});
						
						$("cart_total_amount_span").innerHTML = "* "+res["total"]+"$";
						new Effect.Highlight("cart_total_amount_span", {duration: 2.0});
					}
	});
}

function update_cart(formId)
{
    var params = $(formId).serialize();
    
    new Ajax.Request("/app/actions/update_cart.php", {
					method: "post",
					parameters: params,
					onSuccess: function (transport) {
						var res = transport.responseText.evalJSON(true);
						
						// Highlight all the qt fields
						$(formId).getInputs().each(function(s){
						          var id = s.id;
						          new Effect.Highlight(id, {duration: 2.0});
				        });
				        
				        // Update the totals
				        update_cart_totals();
					}
	});
}

function remove_from_cart(itemId)
{
    new Ajax.Request("/app/actions/remove_from_cart.php", {
					method: "post",
					parameters: "id="+itemId,
					onSuccess: function (transport) {
						Effect.BlindUp("cart_item_"+itemId, {
						              duration: 0.5,
						              afterFinish: function() {
						                  var value   = $("cart_nb_items").innerHTML.replace(/\(/, "");
						                  value       = value.replace(/\)/, "");
						                  var nbItems = parseInt(value) - 1;
						                  $("cart_item_"+itemId).remove();
						                  $("cart_nb_items").innerHTML = "("+nbItems+")";
						                  $("cart_intro_count").innerHTML = "("+nbItems+")";
						                  new Effect.Highlight("header_menu_item_cart", {duration: 2.0});
						                  
						                  if (nbItems == 0) {
						                      Effect.BlindUp("frm_cart", {duration: 0.3});
						                  }
						                  
						                  // Update the totals
                                          update_cart_totals();
						              }
						});
					}
	});
}

function add_to_cart(formId)
{
	var params = $(formId).serialize();
	
	$("img_loader").style.display   = "inline";
    $("img_ok").style.display       = "none";
    //alert(params);
	new Ajax.Request("/app/actions/add_to_cart.php", {
					method: "post",
					parameters: params,
					onComplete: function (transport) {
						var res 	= transport.responseText.evalJSON(true);
						var nbItems	= res["total_items"];
						
						if (res["error"] == 0) {
							$("cart_nb_items").innerHTML = "("+nbItems+")";
							new Effect.Highlight("header_menu_item_cart", {duration: 2.0});
						}
						else {
							alert(res["message"]);
							$(res["focus"]).focus();
						}
						$("img_loader").style.display   = "none";
                        $("img_ok").style.display       = "inline";
					}
	});
}
