var xmlHttpAddItem;
var xmlHttpEditItem;
var xmlHttpRemoveItem;
var xmlHttpCheckEmail;
var xmlHttpUserNoteChange;
var xmlHttpDeleteFile;

function GetXmlHttpObject()
{ 
	var objXMLHttp = null;
	
	if (window.XMLHttpRequest)
	{
		objXMLHttp=new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	return objXMLHttp;
}

function addItem(productId)
{	
	xmlHttpAddItem = GetXmlHttpObject();
	
	if (xmlHttpAddItem == null)
	{
		alert ("Browser does not support HTTP Request");
		return;
	}
	
	var option = base64Encode(document.getElementById("option_" + productId).value);
	var quantity = parseInt(document.getElementById("quantity_" + productId).value);
	var price = parseFloat(document.getElementById("price_" + productId).value);
	
	xmlHttpAddItem.onreadystatechange = addItemCallback;
	xmlHttpAddItem.open("GET", "ajax/additem.php?productId=" + productId + "&option=" + option + "&quantity=" + quantity + "&price=" + price, true);
	xmlHttpAddItem.send(null);
}

function addItemCallback() 
{
	if (xmlHttpAddItem.readyState == 4 || xmlHttpAddItem.readyState == "complete")
	{
		//alert(xmlHttpAddItem.responseText);
		
		var response = xmlHttpAddItem.responseText;
		if (response.substr(0,2) == "OK")
		{
			document.getElementById("nbItemsCart").innerHTML = response.substr(3);
			//alert("Item ajouté au panier!");
			tb_show('', 'client/alert.php?message=' + base64Encode("Item ajouté au panier!") + '&KeepThis=true&modal=false&TB_iframe=true&height=150&width=400', '')
		}
		else
		{
			alert(response);
		}
	} 
}

function editItem(itemIndex)
{	
	xmlHttpEditItem = GetXmlHttpObject();
	
	if (xmlHttpEditItem == null)
	{
		alert ("Browser does not support HTTP Request");
		return;
	}
	
	var quantity = parseInt(document.getElementById("quantity_" + itemIndex).value);
	var price = parseFloat(document.getElementById("price_" + itemIndex).value);
	
	xmlHttpEditItem.onreadystatechange = editItemCallback;
	xmlHttpEditItem.open("GET", "ajax/edititem.php?itemIndex=" + itemIndex + "&quantity=" + quantity + "&price=" + price, true);
	xmlHttpEditItem.send(null);
}

function editItemCallback() 
{
	if (xmlHttpEditItem.readyState == 4 || xmlHttpEditItem.readyState == "complete")
	{
		//alert(xmlHttpEditItem.responseText);
		
		var response = xmlHttpEditItem.responseText;
		if (response.substr(0,2) == "OK")
		{
			// Refresh page
			window.location = window.location;
		}
		else
		{
			alert(response);
		}
	} 
}

function removeItem(itemIndex)
{
	var str = "removeItem2(" + itemIndex + ")";
	str = base64Encode(str);
	tb_show('', 'client/confirm.php?message=' + base64Encode("Voulez-vous vraiment retirer cet item?") + '&return=' + str + '&KeepThis=true&modal=false&TB_iframe=true&height=150&width=400', '')
}

function removeItem2(itemIndex)
{
	/*if (confirm("Voulez-vous vraiment retirer cet item?") == false)
	{
		return;
	}*/
	
	xmlHttpRemoveItem = GetXmlHttpObject();
	
	if (xmlHttpRemoveItem == null)
	{
		alert ("Browser does not support HTTP Request");
		return;
	}
	
	xmlHttpRemoveItem.onreadystatechange = removeItemCallback;
	xmlHttpRemoveItem.open("GET", "ajax/removeitem.php?itemIndex=" + itemIndex, true);
	xmlHttpRemoveItem.send(null);
}

function removeItemCallback(element)
{
	if (xmlHttpRemoveItem.readyState == 4 || xmlHttpRemoveItem.readyState == "complete")
	{
		var response = xmlHttpRemoveItem.responseText;
		if (response.substr(0,2) == "OK")
		{
			// Refresh page
			window.location = window.location;
		}
		else
		{
			alert(response);
		}
	}
}

function checkEmail(email)
{
	xmlHttpCheckEmail = GetXmlHttpObject();
	
	if (xmlHttpCheckEmail == null)
	{
		alert("Browser does not support HTTP Request");
		return;
	}
	
	xmlHttpCheckEmail.onreadystatechange = checkEmailCallback;
	xmlHttpCheckEmail.open("GET", "ajax/checkemail.php?email=" + email, true);
	xmlHttpCheckEmail.send(null);
}

function checkEmailCallback()
{
	if (xmlHttpCheckEmail.readyState == 4 || xmlHttpCheckEmail.readyState == "complete")
	{
		//alert(xmlHttpCheckEmail.responseText);
		
		if (xmlHttpCheckEmail.responseText == "OK")
		{
			// Submit
			document.getElementById("formNouveauProfil").submit();
		}
		else
		{
			// Show error message
			//alert("Le courriel est déjà utilisé dans un autre compte!");
			tb_show('', 'client/alert.php?message=' + base64Encode("Le courriel est déjà utilisé dans un autre compte!") + '&KeepThis=true&modal=false&TB_iframe=true&height=150&width=400', '')
		}
	}
}

function userNoteChange(userNote)
{
	xmlHttpUserNoteChange = GetXmlHttpObject();
	
	if (xmlHttpUserNoteChange == null)
	{
		alert ("Browser does not support HTTP Request");
		return;
	}
	
	var queryString = "userNote=" + userNote;
	
	xmlHttpUserNoteChange.onreadystatechange = userNoteChangeCallback;
	xmlHttpUserNoteChange.open("POST", "ajax/usernotechange.php", true);
	xmlHttpUserNoteChange.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	xmlHttpUserNoteChange.setRequestHeader("Content-length", queryString.length);
	xmlHttpUserNoteChange.send(queryString);
}

function userNoteChangeCallback(element)
{
	if (xmlHttpUserNoteChange.readyState == 4 || xmlHttpUserNoteChange.readyState == "complete")
	{
		if (xmlHttpUserNoteChange.responseText != "")
		{
			alert(xmlHttpUserNoteChange.responseText);
		}
	}
}

function checkMandatoryField(id)
{
	var element = document.getElementById(id);
	
	if (element.value == "")
	{
		element.style.backgroundColor = "red";
		return 1;
	}
	else
	{
		element.style.backgroundColor = "";
	}
	
	return 0;
}

function checkConfirmation()
{
	var password = document.getElementById("password");
	var confirmation = document.getElementById("confirmation");
	
	if (password.value != confirmation.value)
	{
		confirmation.style.backgroundColor = "red";
		return 1;
	}
	else
	{
	}
	
	return 0;
}

function checkCreditCardNumber(id)
{
	var element = document.getElementById(id);
	
	if (element.value != "")
	{
		var re = new RegExp("\\d{16}");
		if (re.test(element.value) == false)
		{
			element.style.backgroundColor = "red";
			return 1;
		}
	}
	
	return 0;
}

function showErrorMessage(msg)
{
	var element = document.getElementById("errorMessage");
	
	element.style.visibility = "visible";
	element.innerHTML = msg;
}

function hideErrorMessage()
{
	var element = document.getElementById("errorMessage");
	
	element.style.visibility = "hidden";
}

function getQuantityPrice(productId, quantity)
{
	var price = parseFloat(document.getElementById("price_" + productId + "_" + quantity).value);
	
	document.getElementById("price_" + productId).value = formatPrice(price);
}

function getCartQuantityPrice(itemIndex, quantity)
{
	var price = parseFloat(document.getElementById("price_" + itemIndex + "_" + quantity).value);
	
	document.getElementById("price_" + itemIndex).value = formatPrice(price);
	
	editItem(itemIndex);
}

function getPromotionCode()
{
	document.getElementById("formPromotion").submit();
}

function getCrediz()
{
	document.getElementById("formCrediz").submit();
}

function formatPrice(price)
{
	return price.toFixed(2).toString();
}

function nouveauProfilSave()
{
	var errors = 0;
	var message = "";
	
	// Hide previous error message
	hideErrorMessage();
	
	// Check mandatory fields
	errors += checkMandatoryField("email");
	errors += checkMandatoryField("password");
	errors += checkMandatoryField("confirmation");
	errors += checkMandatoryField("name");
	
	if (errors > 0)
	{
		message += "Certains champs sont obligatoires!";
	}

	// Check email
	var emailCheck = 0
	if (validateEmail(document.getElementById("email").value) == false)
	{
		emailCheck = 1;
	}
	errors += emailCheck;
	
	if (emailCheck > 0)
	{
		if (message != "") message += "<br/>";
		message += "Le courriel n'est pas valide!";
	}
	
	// Check confirmation
	var confirmationCheck = checkConfirmation();
	errors += confirmationCheck;
	
	if (confirmationCheck > 0)
	{
		if (message != "") message += "<br/>";
		message += "La confirmation ne corespond pas!";
	}
	
	if (errors > 0)
	{
		// Show error message
		showErrorMessage(message);
	}
	else
	{
		// Check email availability
		checkEmail(document.getElementById("email").value);
	}
}

function profilSave()
{
	var errors = 0;
	var message = "";
	
	// Hide previous error message
	hideErrorMessage();
	
	// Check mandatory fields
	errors += checkMandatoryField("password");
	errors += checkMandatoryField("confirmation");
	errors += checkMandatoryField("name");
	
	if (errors > 0)
	{
		message += "Certains champs sont obligatoires!";
	}
	
	// Check confirmation
	var confirmationCheck = checkConfirmation();
	errors += confirmationCheck;
	
	if (confirmationCheck > 0)
	{
		if (message != "") message += "<br/>";
		message += "La confirmation ne corespond pas!";
	}
	
	if (errors > 0)
	{
		// Show error message
		showErrorMessage(message);
	}
	else
	{
		document.getElementById("formProfil").submit();
	}
}

function pack()
{
	var errors = 0;
	var message = "";
	
	// Hide previous error message
	hideErrorMessage();
	
	// Check mandatory fields
	errors += checkMandatoryField("c_nom");
	errors += checkMandatoryField("c_prenom");
	errors += checkMandatoryField("c_mail");
	
	if (errors > 0)
	{
		message += "Certains champs sont obligatoires!";
	}

	// Check email
	var emailCheck = 0
	if (validateEmail(document.getElementById("c_mail").value) == false)
	{
		emailCheck = 1;
	}
	errors += emailCheck;
	
	if (emailCheck > 0)
	{
		if (message != "") message += "<br/>";
		message += "Le courriel n'est pas valide!";
	}
	
	if (errors > 0)
	{
		// Show error message
		showErrorMessage(message);
	}
	else
	{
		// Submit
		document.getElementById("form1").submit();
	}
}

function checkCountry(country)
{
	if (country == "CA")
	{
		document.getElementById("province").style.display = "none";
		document.getElementById("provinceSelect").style.display = "";
		document.getElementById("province").name = "province2";
		document.getElementById("provinceSelect").name = "province";
	}
	else
	{
		document.getElementById("province").style.display = "";
		document.getElementById("provinceSelect").style.display = "none";
		document.getElementById("province").name = "province";
		document.getElementById("provinceSelect").name = "province2";
	}
}

function checkShippingCountry(country)
{
	if (country == "CA")
	{
		document.getElementById("shippingProvince").style.display = "none";
		document.getElementById("shippingProvinceSelect").style.display = "";
		document.getElementById("shippingProvince").name = "shippingProvince2";
		document.getElementById("shippingProvinceSelect").name = "shippingProvince";
	}
	else
	{
		document.getElementById("shippingProvince").style.display = "";
		document.getElementById("shippingProvinceSelect").style.display = "none";
		document.getElementById("shippingProvince").name = "shippingProvince";
		document.getElementById("shippingProvinceSelect").name = "shippingProvince2";
	}
}

function profilShippingSave()
{
	var errors = 0;
	var message = "";
	
	// Hide previous error message
	hideErrorMessage();
	
	// Check mandatory fields
	errors += checkMandatoryField("shippingName");
	errors += checkMandatoryField("name");
	errors += checkMandatoryField("company");
	errors += checkMandatoryField("address");
	errors += checkMandatoryField("city");
	errors += checkMandatoryField("postalCode");
	errors += checkMandatoryField("phone");
	
	if (errors > 0)
	{
		message += "Certains champs sont obligatoires!";
	}
	
	if (errors > 0)
	{
		// Show error message
		showErrorMessage(message);
	}
	else
	{
		document.getElementById("formProfilShippingSave").submit();
	}
}

function profilShippingDelete()
{
	var str = "profilShippingDelete2()";
	str = base64Encode(str);
	tb_show('', 'client/confirm.php?message=' + base64Encode("Voulez-vous vraiment effacer cette adresse d'expédition?") + '&return=' + str + '&KeepThis=true&modal=false&TB_iframe=true&height=150&width=400', '')
}

function profilShippingDelete2()
{
	/*if (confirm("Voulez-vous vraiment effacer cette adresse d'expédition?") == true)
	{
		document.getElementById("formProfilShippingDelete").submit();
	}*/
	
	document.getElementById("formProfilShippingDelete").submit();
}

function profilChangeShipping(usersShippingId)
{
	window.location = "index.php?page=mesExpeditions&usersShippingId=" + usersShippingId;
}

function facturationLogin()
{
	document.getElementById("formFacturationLogin").submit();
}

function facturationNouveauSave()
{
	var errors = 0;
	var message = "";
	
	// Hide previous error message
	hideErrorMessage();
	
	// Check mandatory fields
	errors += checkMandatoryField("email");
	errors += checkMandatoryField("password");
	errors += checkMandatoryField("confirmation");
	errors += checkMandatoryField("name");
	
	if (errors > 0)
	{
		message += "Certains champs sont obligatoires!";
	}
	
	// Check confirmation
	var confirmationCheck = checkConfirmation();
	errors += confirmationCheck;
	
	if (confirmationCheck > 0)
	{
		if (message != "") message += "<br/>";
		message += "La confirmation ne corespond pas!";
	}
	
	if (errors > 0)
	{
		// Show error message
		showErrorMessage(message);
	}
	else
	{
		// Check email availability
		checkEmail(document.getElementById("email").value);
	}
}

function expeditionChangeShipping(usersShippingId)
{
	window.location = "index.php?page=expedition&usersShippingId=" + usersShippingId;
}

function expeditionShippingSave()
{
	var errors = 0;
	var message = "";
	
	// Hide previous error message
	hideErrorMessage();
	
	// Check mandatory fields
	errors += checkMandatoryField("shippingName");
	errors += checkMandatoryField("name");
	errors += checkMandatoryField("company");
	errors += checkMandatoryField("address");
	errors += checkMandatoryField("city");
	errors += checkMandatoryField("postalCode");
	errors += checkMandatoryField("phone");
	
	if (errors > 0)
	{
		message += "Certains champs sont obligatoires!";
	}
	
	if (errors > 0)
	{
		// Show error message
		showErrorMessage(message);
	}
	else
	{
		document.getElementById("formExpeditionShippingSave").submit();
	}
}

function resumeChangeShipping(usersShippingId)
{
	window.location = "index.php?page=resume&usersShippingId=" + usersShippingId;
}

function pay()
{
	if (document.getElementById("conditions").checked == false)
	{
		//alert("Vous devez accepter les conditions d'utilisations!");
		tb_show('', 'client/alert.php?message=' + base64Encode("Vous devez accepter les conditions d'utilisations!") + '&KeepThis=true&modal=false&TB_iframe=true&height=150&width=400', '')
	}
	else
	{
		window.location = "index.php?page=process"
	}
}

function base64Encode(data)
{
	var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var out = "", c1, c2, c3, e1, e2, e3, e4;
	
	for (var i = 0; i < data.length; )
	{
		c1 = data.charCodeAt(i++);
		c2 = data.charCodeAt(i++);
		c3 = data.charCodeAt(i++);
		e1 = c1 >> 2;
		e2 = ((c1 & 3) << 4) + (c2 >> 4);
		e3 = ((c2 & 15) << 2) + (c3 >> 6);
		e4 = c3 & 63;
		if (isNaN(c2))
		{
			e3 = e4 = 64;
		}
		else if (isNaN(c3))
		{
			e4 = 64;
		}
		out += tab.charAt(e1) + tab.charAt(e2) + tab.charAt(e3) + tab.charAt(e4);
	}
	
	return out;
}

function base64Decode(data)
{
	var tab = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	var out = "", c1, c2, c3, e1, e2, e3, e4;

	for (var i = 0; i < data.length; )
	{
		e1 = tab.indexOf(data.charAt(i++));
		e2 = tab.indexOf(data.charAt(i++));
		e3 = tab.indexOf(data.charAt(i++));
		e4 = tab.indexOf(data.charAt(i++));
		c1 = (e1 << 2) + (e2 >> 4);
		c2 = ((e2 & 15) << 4) + (e3 >> 2);
		c3 = ((e3 & 3) << 6) + e4;
		out += String.fromCharCode(c1);
		if (e3 != 64)
		{
			out += String.fromCharCode(c2);
		}
		if (e4 != 64)
		{
			out += String.fromCharCode(c3);
		}
	}
	
	return out;
}

function urlQueryStringReplace(url, key, value)
{
	// if not query string
	if (url.indexOf("?") == -1 && value != null)
	{
		url += "?" + key + "=" + value;
	}
	else
	{
		// if key is there
		if (url.indexOf("?" + key + "=") != -1 || url.indexOf("&" + key + "=") != -1)
		{
			urlPage = url.substr(0, url.indexOf("?"));
			queryString = url.substr(url.indexOf("?") + 1);
			keys = queryString.split("&");
			
			// Loop through keys
			for (var i = 0; i < keys.length; i++)
			{
				// if key to change
				if (keys[i].indexOf(key + "=") != -1)
				{
					if (value != null)
					{
						// Change key
						keys[i] = key + "=" + value;
					}
					else
					{
						// Remove key
						keys.splice(i, 1);
					}
					
					break;
				}
			}
			
			if (keys.length > 0)
			{
				queryString = keys.toString().replace(",", "&");
				url = urlPage + "?" + queryString;
			}
			else
			{
				url = urlPage;
			}
		}
		else if (value != null)
		{
			// Add key
			url += "&" + key + "=" + value;
		}
	}
	
	return url;

}

function orderBy(field)
{
	var url = window.location.toString();
	
	if (url.indexOf("orderBy=" + field) != -1)
	{
		if (url.indexOf("desc=true") != -1)
		{
			url = urlQueryStringReplace(url, "orderBy", field);
			url = urlQueryStringReplace(url, "desc", null);
		}
		else
		{
			url = urlQueryStringReplace(url, "orderBy", field);
			url = urlQueryStringReplace(url, "desc", "true");
		}
	}
	else
	{
		url = urlQueryStringReplace(url, "orderBy", field);
		url = urlQueryStringReplace(url, "desc", null);
	}
	
	window.location = url;
}

function validateEmail(email)
{
	var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
	
	return emailPattern.test(email);
}

function newsletterAdd()
{
	var email = document.getElementById("newsletterAddEmail").value;
	
	if (validateEmail(email) == true)
	{
		document.getElementById("formNewsletterAdd").submit();
	}
	else
	{
		var element = document.getElementById("newsletterErrorMessage");
		
		element.innerHTML = "Le courriel n'est pas valide!";
		element.style.display = "";
		
		document.getElementById("newsletterAddEmail").style.backgroundColor = "red";
	}
}

function addFile(orderId, ordersItemId)
{
	window.open("client/upload.php?orderId=" + orderId + "&ordersItemId=" + ordersItemId, "", "width=282,height=165");
}

function deleteFile(orderId, ordersItemId, filename)
{
	var str = "deleteFile2(" + orderId + "," + ordersItemId + ",'" + filename + "')";
	str = base64Encode(str);
	tb_show('', 'client/confirm.php?message=' + base64Encode("Voulez-vous vraiment retirer ce fichier?") + '&return=' + str + '&KeepThis=true&modal=false&TB_iframe=true&height=150&width=400', '')	
}

function deleteFile2(orderId, ordersItemId, filename)
{	
	xmlHttpDeleteFile = GetXmlHttpObject();
	
	if (xmlHttpDeleteFile == null)
	{
		alert ("Browser does not support HTTP Request");
		return;
	}
	
	xmlHttpDeleteFile.onreadystatechange = deleteFileCallback;
	xmlHttpDeleteFile.open("GET", "ajax/deletefile.php?orderId=" + orderId + "&ordersItemId=" + ordersItemId + "&filename=" + filename, true);
	xmlHttpDeleteFile.send(null);
}

function deleteFileCallback() 
{
	if (xmlHttpDeleteFile.readyState == 4 || xmlHttpDeleteFile.readyState == "complete")
	{
		// Refresh page
		window.location = window.location;
	} 
}
