var xmlHttp
var inObj
var outObj
function GetXmlHttpObject()
{
	var xmlHttp=null;
	try
	  {
	  // Firefox, Opera 8.0+, Safari
	  xmlHttp=new XMLHttpRequest();
	  }
	catch (e)
	  {
	  // Internet Explorer
	  try
		{
		xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
	  catch (e)
		{
		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	  }
	return xmlHttp;
}
//Shoping Cart
function addToCart( pid, cartid) {
	document.getElementById(cartid).innerHTML="<img src='images/indicator.gif'></img>";
	var xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null){
	  alert ("Your browser does not support AJAX!");
	  return;
	} 
	var url="ajax/cartProcess.aspx?act=add&id="+pid;
	url=url+"&sid="+Math.random();
	xmlHttp.onreadystatechange=function (){
		if (xmlHttp.readyState==4) { 
			var product = xmlHttp.responseXML.getElementsByTagName('product');
			document.getElementById(cartid).innerHTML=product.length;
			xmlHttp = null;
			delete(xmlHttp);
		}
	}
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}
function removeFromCart(pos, pid, cartid) {
	document.getElementById(cartid).innerHTML="<img src='images/indicator.gif'></img>";
	var xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null){
	  alert ("Your browser does not support AJAX!");
	  return;
	} 
	var url="ajax/cartProcess.aspx?act=remove&id="+pid;
	url=url+"&sid="+Math.random();
	xmlHttp.onreadystatechange=function (){
		if (xmlHttp.readyState==4) { 
			var product = xmlHttp.responseXML.getElementsByTagName('product');
			document.getElementById(cartid).innerHTML=product.length;
			var tobj = document.getElementById("tbcart");
			var tmpLength = tobj.tBodies[0].rows.length;
			for (var i=0; i<tmpLength; i++) {
				tobj.tBodies[0].deleteRow(0);
			}
			var tmpTotal = 0;
			for (i=0; i<product.length; i++) {
				tmpTotal += getNodeValue(product[i],'price') * getNodeValue(product[i],'quantity');
				var newrow = tobj.tBodies[0].insertRow(0);
				
				var cell1 = document.createElement('td');
				var cell1_a = document.createElement('a');
				cell1_a.setAttribute('href', "javascript: removeFromCart(\'"+i+"\',\'"+getNodeValue(product[i],'id')+"\',\'m-cart\');");
				cell1_a.setAttribute('title', getNodeValue(product[i],'name'));
				cell1_a.innerHTML = "<img src=\"images/assets/bullet_delete.gif\" alt=\"remove item\" width=\"16\" height=\"16\" /></a></td><td><a href=\"ProductDetail.aspx?catid="+getNodeValue(product[i],'id')+"&amp;productid="+getNodeValue(product[i],'id');
				
				var cell2 = document.createElement('td');
				var cell2_a = document.createElement('a');
				cell2_a.setAttribute('href', "ProductDetail.aspx?productid="+getNodeValue(product[i],'id'));
				cell2_a.setAttribute('title', getNodeValue(product[i],'name'));
				cell2_a.innerHTML = getNodeValue(product[i],'name');
				
				var cell3 = document.createElement('td');
				
				var cell4 = document.createElement('td');
				var cell4_text = document.createElement('input');
				cell4_text.setAttribute('type', "input");
				cell4_text.setAttribute('id', getNodeValue(product[i],'id'));
				cell4_text.setAttribute('name', getNodeValue(product[i],'id'));
				cell4_text.setAttribute('value', getNodeValue(product[i],'quantity'));
				cell4_text.className = "txtqty";
				
				var cell5 = document.createElement('td');
				var cell5_text = document.createTextNode("$");
				var cell5_span = document.createElement('span');
				cell5_span.setAttribute('id', "t_"+getNodeValue(product[i],'id'));
				cell5_span.innerHTML = formatCurrency(getNodeValue(product[i],'price') * getNodeValue(product[i],'quantity'));
				
				cell1.appendChild(cell1_a);
				cell2.appendChild(cell2_a);
				cell3.appendChild(document.createTextNode("$ " + formatCurrency(getNodeValue(product[i],'price'))));
				cell4.appendChild(cell4_text);
				cell5.appendChild(cell5_text);
				cell5.appendChild(cell5_span);
				newrow.appendChild(cell1);
				newrow.appendChild(cell2);
				newrow.appendChild(cell3);
				newrow.appendChild(cell4);
				newrow.appendChild(cell5);
			}
			document.getElementById("overtotal").innerHTML = formatCurrency(tmpTotal);
			document.getElementById("myspan").innerHTML="";
			xmlHttp = null;
			delete(xmlHttp);
		}
	}
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}
function updateCart(obj, cartid) {
	var xmlStr = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>"
	xmlStr += "<root>"
  	var inputList = obj.getElementsByTagName("input");
	for (i=0; i<inputList.length; i++) {
		if (inputList[i].type == "text") {
			xmlStr += "<product>"
			xmlStr += "<id>"+inputList[i].id+"</id>"
			xmlStr += "<quantity>"+inputList[i].value+"</quantity>"
			xmlStr += "</product>"
			document.getElementById("p_"+inputList[i].id)
		}
	}
	xmlStr += "</root>"
	document.getElementById(cartid).innerHTML="<img src='images/indicator.gif'></img>";
	document.getElementById("myspan").innerHTML="<img src='images/indicator.gif'></img>";
	var xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null){
	  alert ("Your browser does not support AJAX!");
	  return;
	} 
	var url="ajax/cartProcess.aspx?act=update&xml="+xmlStr;
	url=url+"&sid="+Math.random();
	xmlHttp.onreadystatechange=function (){
		if (xmlHttp.readyState==4) { 
			var product = xmlHttp.responseXML.getElementsByTagName('product');
			document.getElementById(cartid).innerHTML=product.length;
			var tmpTotal = 0;
			for (i=0; i<product.length; i++) {
				document.getElementById("t_"+getNodeValue(product[i],'id')).innerHTML = parseFloat((getNodeValue(product[i],'price') * getNodeValue(product[i],'quantity'))).toFixed(2)
				tmpTotal += getNodeValue(product[i],'price') * getNodeValue(product[i],'quantity');
			}
			document.getElementById("overtotal").innerHTML = tmpTotal.toFixed(2);
			document.getElementById("myspan").innerHTML="";
			xmlHttp = null;
			delete(xmlHttp);
		}
	}
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}
function getNodeValue(obj,tag)
{
	return obj.getElementsByTagName(tag)[0].firstChild.nodeValue;
}
function sendOrder(stt) {
	if (eval(stt)) {
		document.getElementById("myspan").innerHTML="<img src='images/indicator.gif'></img> Processing...";
		var xmlHttp=GetXmlHttpObject()
		if (xmlHttp==null){
		  alert ("Your browser does not support AJAX!");
		  return;
		} 
		var url="ajax/cartProcess.aspx?act=commit"
		url=url+"&sid="+Math.random();
		xmlHttp.onreadystatechange=function (){
			if (xmlHttp.readyState==4) { 
				document.getElementById("myspan").innerHTML=xmlHttp.responseText;
				xmlHttp = null;
				delete(xmlHttp);
			}
		}
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);
	}
	else {
		document.getElementById("myspan").innerHTML="Bạn chưa khai báo thông tin cá nhân trước khi đặt hàng. Click <a href=\"Login.aspx\">vào đây</a> để thực hiện.";
	}
}
//End Shoping Cart
function checkEmail(pre, sinObj, soutObj)
{
	if (document.getElementById(sinObj).value.length==0) { 
		document.getElementById(soutObj).innerHTML="";
		return;
	}
	if (document.getElementById(sinObj).value == pre) {
		return;
	}
	document.getElementById(soutObj).innerHTML="<img src='images/indicator.gif'></img> Processing...";
	var xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null)
	  {
	  alert ("Your browser does not support AJAX!");
	  return;
	  } 
	var url="Ajax/Check_Email.aspx";
	url=url+"?email="+document.getElementById(sinObj).value;
	url=url+"&sid="+Math.random();
	xmlHttp.onreadystatechange=function (){
		if (xmlHttp.readyState==4)
		{ 
			document.getElementById(soutObj).innerHTML=xmlHttp.responseText;
		}
	}
	xmlHttp.open("GET",url,true);
	xmlHttp.send(null);
}
function sendContact(obj) {
  var getstr = "?";
  var inputList = obj.getElementsByTagName("input");
  for (i=0; i<inputList.length; i++) {
	 if (inputList[i].type == "text" || inputList[i].type == "password" || inputList[i].type == "hidden") {
		   getstr += inputList[i].name + "=" + encodeURI(inputList[i].value) + "&";
		   inputList[i].value = "";
	 }   
  }
  var textareaList = obj.getElementsByTagName("textarea");
  for (i=0; i<textareaList.length; i++) {
	   getstr += textareaList[i].name + "=" + encodeURI(textareaList[i].innerText) + "&";
	   textareaList[i].innerText = "";
  }
  makePOSTRequest('Ajax/Contact_Send.aspx', getstr);
}
function requestPassword(obj) {
  var getstr = "?";
  var inputList = obj.getElementsByTagName("input");
  for (i=0; i<inputList.length; i++) {
	 if (inputList[i].type == "text" || inputList[i].type == "password" || inputList[i].type == "hidden") {
		   getstr += "&" + inputList[i].name + "=" + encodeURI(inputList[i].value);
		   inputList[i].value = "";
	 }   
  }
  makePOSTRequest('Ajax/Request_Password.aspx', getstr);
}
function login(obj) {
  var getstr = "?";
  var inputList = obj.getElementsByTagName("input");
  for (i=0; i<inputList.length; i++) {
	 if (inputList[i].type == "text" || inputList[i].type == "password" || inputList[i].type == "hidden") {
		   getstr += inputList[i].name + "=" + encodeURI(inputList[i].value) + "&";
	 }   
  }
  makeLoginRequest('Ajax/Login.aspx', getstr);
}
function updateAccInfo(obj) {
  var getstr = "?";
  var inputList = obj.getElementsByTagName("input");
  for (i=0; i<inputList.length; i++) {
	 if (inputList[i].type == "text" || inputList[i].type == "password" || inputList[i].type == "hidden") {
		getstr +=  "&" + inputList[i].name + "=" + encodeURI(inputList[i].value);
	 }
	 if (inputList[i].type == "checkbox" && inputList[i].checked) {
		getstr +=  "&" + inputList[i].name + "=" + encodeURI(inputList[i].value);
	 }
  }	
	document.getElementById("myspan").innerHTML="<img src='images/indicator.gif'></img> Processing...";
	var xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null) {
		  alert ("Your browser does not support AJAX!");
		  return;
	} 
    xmlHttp.onreadystatechange = function () {
	  if (xmlHttp.readyState == 4) {
		document.getElementById('myspan').innerHTML = xmlHttp.responseText;
		if (xmlHttp.responseText == "Đăng ký thành công.") window.location = "Cart.aspx";
	  }
	}
    xmlHttp.open('POST', 'Ajax/Account_Update.aspx', true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", getstr.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.send(getstr);
}
function makePOSTRequest(url, parameters) {
	document.getElementById("myspan").innerHTML="<img src='images/indicator.gif'></img> Processing...";
	var xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null) {
		  alert ("Your browser does not support AJAX!");
		  return;
	} 
    xmlHttp.onreadystatechange = function () {
	  if (xmlHttp.readyState == 4) {
		document.getElementById('myspan').innerHTML = xmlHttp.responseText;
	  }
	}
    xmlHttp.open('POST', url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", parameters.length);
    xmlHttp.setRequestHeader("Connection", "close");
	parameters += "&sid="+Math.random();
    xmlHttp.send(parameters);
}
function makeLoginRequest(url, parameters) {
	document.getElementById("myspan").innerHTML="<img src='images/indicator.gif'></img> Processing...";
	var xmlHttp=GetXmlHttpObject()
	if (xmlHttp==null) {
		  alert ("Your browser does not support AJAX!");
		  return;
	} 
    xmlHttp.onreadystatechange = function () {
	  if (xmlHttp.readyState == 4) {
		if (xmlHttp.responseText == "Đăng nhập thành công.")
			window.location = "Account_Info.aspx"
		document.getElementById('myspan').innerHTML = xmlHttp.responseText;
	  }
	}
    xmlHttp.open('POST', url, true);
    xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("Content-length", parameters.length);
    xmlHttp.setRequestHeader("Connection", "close");
    xmlHttp.send(parameters);
}


//===========================================================================
//	Form Validation
//===========================================================================
function validate_ex(theForm, _ErrMsg, arrNotRequired) {
	validForm = true;
	firstError = null;
	errorstring = '';
	var x = document.forms[theForm].elements;
	var arr = ','+arrNotRequired.toString()+ ',';
	for (var i=0;i<x.length;i++) {
		if (arr.indexOf(','+x[i].name+',')==-1) {
			if (!x[i].value)
			{
				if (x[i].type != "undefined" && x[i].type != "button" && x[i].type != "submit" && x[i].type != "reset" && x[i].type != "hidden")
				{
					writeError(x[i], _ErrMsg);
					if (firstError ==null)
					firstError = x[i];
				}
			}
			if (x[i].name == 'email')
			{
				var strEmail = /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
				if(!strEmail.test(x[i].value))
					writeError(x[i],'Email không hợp lệ.');
			}
			if (x[i].name == 'confirm')
			{
				if (x[i].value != x['password'].value)
					writeError(x[i], '**');
			}
		}
	}
	
	if (!W3CDOM)
		alert(errorstring);
	if (firstError)
		firstError.focus();
	if (validForm)
		return true;
		
	return false; // I return false anyway to prevent actual form submission. Don't do this at home!
}
function validate(theForm, _ErrMsg ) {
	validForm = true;
	firstError = null;
	errorstring = '';
	var x = document.forms[theForm].elements;
	for (var i=0;i<x.length;i++) {
		if (!x[i].value)
		{
			var str="";
			str = "".concat(x[i].type);
			if (str.toString() != "undefined")
			{
				writeError(x[i], _ErrMsg);
				if (firstError ==null)
				firstError = x[i];
			}
		}
		if (x[i].name == 'txtEmail')
		{
			var strEmail = /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
				if(!strEmail.test(x['txtEmail'].value))
					writeError(x['txtEmail'],'**');
		}
		if (x[i].name == 'txtReNewPassword')
		{
			if (x[i].value != x['txtNewPassword'].value)
				writeError(x[i], '**');
		}
	}
	
	if (!W3CDOM)
		alert(errorstring);
	if (firstError)
		firstError.focus();
	if (validForm)
		return true;
		
	return false; // I return false anyway to prevent actual form submission. Don't do this at home!
}

function writeError(obj,message) {
	validForm = false;
	if (obj.hasError) return;
	if (W3CDOM) {
		obj.className += ' error';
		obj.onchange = removeError;
		var sp = document.createElement('span');
		sp.className = 'error';
		sp.appendChild(document.createTextNode(message));
		obj.parentNode.appendChild(sp);
		obj.hasError = sp;
	}
	else {
		errorstring += obj.name + ': ' + message + '\n';
		obj.hasError = true;
	}
	if (!firstError)
		firstError = obj;
}

function removeError() {
	this.className = this.className.substring(0,this.className.lastIndexOf(' '));
	this.parentNode.removeChild(this.hasError);
	this.hasError = null;
	this.onchange = null;
}
//===========================================================================
function formatCurrency(strValue)
{
	strValue = strValue.toString().replace(/\$|\,/g,'');
	dblValue = parseFloat(strValue);

	blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
	dblValue = Math.floor(dblValue*100+0.50000000001);
	intCents = dblValue%100;
	strCents = intCents.toString();
	dblValue = Math.floor(dblValue/100).toString();
	if(intCents<10)
		strCents = "0" + strCents;
	for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
		dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+
		dblValue.substring(dblValue.length-(4*i+3));
	return (((blnSign)?'':'-') + dblValue + '.' + strCents);
}