
function isInternetExplorer() 
{
      var userAgent = navigator.userAgent.toLowerCase();
      if (document.all && userAgent.indexOf('msie 6.0')!=-1) {
         return true;
      }
      else 
	  {
         return false;
      }
}

function tapage(varsString,url,datapost){
		showBusyLayer(varsString);
		var ajax = new dle_ajax();
		this.varsString=varsString;
		//ajax.onShow ('');
		ajax.requestFile =url;
		ajax.method = "POST";//ban dau GET moi chuyen san POST
		ajax.execute = true;
		ajax.element = varsString;
		ajax.onCompletion = function(){
			hideBusyLayer();
		};
		ajax.sendAJAX(datapost);
}

function tasubpage1(url,varsString,datapost){
		showBusyLayer(varsString);
		var ajax = new dle_ajax();
		this.varsString=varsString;
		ajax.requestFile =url;
		ajax.method = "POST";//ban dau GET moi chuyen san POST
		ajax.execute = true;
		ajax.element = varsString;
		ajax.onCompletion = function(){
			hideBusyLayer();	
		};
		ajax.sendAJAX(datapost);
}

function ta_menupage(varsString,url,datapost){
	createCookie('path',url);
	createCookie('pos',varsString);
	showBusyLayer(varsString);	
	var ajax = new dle_ajax();
	this.varsString=varsString;
	ajax.requestFile =url;
	ajax.method = "POST";//ban dau GET moi chuyen san POST
	ajax.execute = true;
	ajax.element = varsString;
	ajax.onCompletion = function(){
	hideBusyLayer();	
	};
	ajax.sendAJAX(datapost);
	
}
function showBusyLayer(varsString) {
		
		var busyLayer = document.getElementById("loading-layer")
		if (busyLayer != null) {
			busyLayer.style.visibility = "visible";				
		}
			
}
	
function hideBusyLayer() {
		var busyLayer = document.getElementById("loading-layer")
		if (busyLayer != null) {
			busyLayer.style.visibility = "hidden";
			//busyLayer.style.height = "0px";
		}
}

function dle_ajax(file){
	this.AjaxFailedAlert = "Your browser does not support the extended control capability of site, we imperatively recommend the replacing of browser.\n";
	this.requestFile = file;
	this.method = "POST";
	this.URLString = "";
	this.encodeURIString = true;
	this.execute = false;
	this.add_html = false;
	this.loading_fired		= 0;
	this.centerdiv          = null;
	this.onLoading = function() { };
	this.onLoaded = function() { };
	this.onInteractive = function() { };
	this.onCompletion = function() { };
	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP.5.0");
		} catch (e) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (err) {
				this.xmlhttp = null;
			}
		}
		if(!this.xmlhttp && typeof XMLHttpRequest != "undefined")
			this.xmlhttp = new XMLHttpRequest();
		if (!this.xmlhttp){
			this.failed = true; 
		}
	};
	
	this.setVar = function(name, value){
		if (this.URLString.length < 3){
			this.URLString = name + "=" + value;
		} else {
			this.URLString += "&" + name + "=" + value;
		}
	}
	
	this.encVar = function(name, value){
		var varString = encodeURIComponent(name) + "=" + encodeURIComponent(value);
	return varString;
	}
	
	this.encodeURLString = function(string){
		varArray = string.split('&');
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split('=');
			if (urlVars[0].indexOf('amp;') != -1){
				urlVars[0] = urlVars[0].substring(4);
			}
			varArray[i] = this.encVar(urlVars[0],urlVars[1]);
		}
	return varArray.join('&');
	}

	this.encodeVAR = function(url){
	
	url = url.toString();

	var regcheck = url.match(/[\x90-\xFF]/g);
	
	if ( regcheck )
	{
		for (var i = 0; i < i.length; i++)
		{
			url = url.replace(regcheck[i], '%u00' + (regcheck[i].charCodeAt(0) & 0xFF).toString(16).toUpperCase());
		}
	}

	return escape(url).replace(/\+/g, "%2B");
	}
	
	this.runResponse = function(){

                        var milisec = new Date;
                        var jsfound = false;
                        milisec = milisec.getTime();

                        var js_reg = /<script.*?>(.|[\r\n])*?<\/script>/ig;

                        var js_str = js_reg.exec(this.response);
                        if (js_str != null) {

						var js_arr = new Array(js_str.shift());
                        var jsfound = true;
        
                        while(js_str) {
                                js_str = js_reg.exec(this.response);
                                if (js_str != null) js_arr.push(js_str.shift());
                        }

                          for(var i=0; i<js_arr.length;i++) {
                                this.response = this.response.replace(js_arr[i],'<span id="'+milisec+i+'" style="display:none;"></span>');
                          }
						}
                            if ( this.add_html ) {
                                this.elementObj.innerHTML += this.response; 
                            } else {
                                this.elementObj.innerHTML = this.response; 
                            }

                        if (jsfound) {

                        var js_content_reg = /<script.*?>((.|[\r\n])*?)<\/script>/ig;

                        for (i = 0; i < js_arr.length; i++) {
                                var mark_node = document.getElementById(milisec+''+i);
                                var mark_parent_node = mark_node.parentNode;
                                mark_parent_node.removeChild(mark_node);
                                
                                js_content_reg.lastIndex = 0;
                                var js_content = js_content_reg.exec(js_arr[i]);
                                var script_node = mark_parent_node.appendChild(document.createElement('script'));
							    script_node.text = js_content[1];  

                                var script_params_str = js_arr[i].substring(js_arr[i].indexOf(' ',0),js_arr[i].indexOf('>',0));
                                var params_arr = script_params_str.split(' ');

								if (params_arr.length > 1) {
                                   for (var j=0;j< params_arr.length; j++ )        {
                                        
                                        if(params_arr[j].length > 0){
                                                var param_arr = params_arr[j].split('=');
                                                param_arr[1] = param_arr[1].substr(1,(param_arr[1].length-2));
                                                script_node.setAttribute(param_arr[0],param_arr[1]);
                                        }

                                  }
								}

                          }
                        }
	}


	
	this.sendAJAX = function(urlstring){
		this.responseStatus = new Array(2);
		if(this.failed && this.AjaxFailedAlert){ 
			alert(this.AjaxFailedAlert); 
		} else {
			if (urlstring){ 
				if (this.URLString.length){
					this.URLString = this.URLString + "&" + urlstring; 
				} else {
					this.URLString = urlstring; 
				}
			}
			
			if (this.encodeURIString){
				var timeval = new Date().getTime(); 
				this.URLString = this.encodeURLString(this.URLString);
				this.setVar("rndval", timeval);
			}
			
			if (this.element) { this.elementObj = document.getElementById(this.element); }
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					var totalurlstring = this.requestFile;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					
					this.xmlhttp.open(this.method, this.requestFile, true);
				}
				if (this.method == "POST"){
  					try {
						this.xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
					} catch (e) {}
				}
				this.xmlhttp.send(this.URLString);
				this.xmlhttp.onreadystatechange = function() {
					switch (self.xmlhttp.readyState){
						case 1:
							self.onLoading();
						break;
						case 2:
							self.onLoaded();
						break;
						case 3:
							self.onInteractive();
						break;
						case 4:
							self.response = self.xmlhttp.responseText;
							self.responseXML = self.xmlhttp.responseXML;
							self.responseStatus[0] = self.xmlhttp.status;
							self.responseStatus[1] = self.xmlhttp.statusText;
							self.onCompletion();
							if (self.elementObj) {
								var elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input" || elemNodeName == "select" || elemNodeName == "option" || elemNodeName == "textarea"){
									if (self.response == 'error') { alert('Access Denied!'); } else {
                                    if ( self.add_html ) {
									self.elementObj.value += self.response;
                                    } else { self.elementObj.value = self.response; }
									}
								} else {
									if (self.response == 'error') { alert('Access Denied!'); } 
									else {
										if(self.execute)
											{ self.runResponse(); }
										else 
										{
                                        	if ( self.add_html ) 
											{

                                           self.elementObj.innerHTML += self.response;

                                        	} 
											else
											{ self.elementObj.innerHTML = self.response; }
                                     }
									}
								}
							}
							self.URLString = "";
						break;
					}
				};
			}
		}
	};
this.createAJAX();
}
/*
// get URL paramater with Javascript
	function gup( name )
	{
	  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	  var regexS = "[\\?&]"+name+"=([^&#]*)";
	  var regex = new RegExp( regexS );
	  var results = regex.exec( window.location.href );
	  if( results == null )
		return "";
	  else
		return results[1];
	}

//	back and refresh with ajax
	var expectedHash = "";
	function makeHistory(newHash,div)
	{
		if (isInternetExplorer() == false)
		{
			window.location.hash = newHash;
			tasubpage1("process.php"+newHash,div);
			document.title="Cai luong";
		}
		else
			document.location="index.php"+newHash;
	}
	
	function makeHistory_new(div,newHash)
	{
		if (isInternetExplorer() == false)
		{
			window.location.hash = newHash;
			tasubpage1("process.php"+newHash,div);
			document.title="Cai luong";
		}
		else
			document.location="index.php"+newHash;
	}
	
	function handleHistory()
	{
	  if ( window.location.hash != expectedHash )
	  {
		var cid= gup('cid');
		if(cid == 5 || cid==67 || cid==61)
			div = 'noidung';	
		else
			div = 'phan_giua';
		div = 'noidung';	

		expectedHash = window.location.hash;
		var newHash = expectedHash.replace(/#/, "");
		makeHistory(newHash,div);
		makeHistory_new(div,newHash);
	  }
	  return true;
	}
	
	function pollHash() {
	  	
	  handleHistory();
	  window.setInterval("handleHistory()", 1000);
	  return true;
	}	
*/
	
//*********** login script

function cllogin(url,varsString,datapost){
	showBusyLayer_login(varsString);
	var ajax = new dle_ajax();
	this.varsString=varsString;
	ajax.requestFile =url;
	ajax.method = "POST";//ban dau GET moi chuyen san POST
	ajax.execute = true;
	ajax.element = varsString;
	ajax.onCompletion = function(){
		hideBusyLayer_login();	
	};
	ajax.sendAJAX(datapost);
}

function showBusyLayer_login(varsString) {
		
		var busyLayer1 = document.getElementById("loading-layer-login")
		if (busyLayer1 != null) {
			busyLayer1.style.visibility = "visible";				
		}
			
}
	
function hideBusyLayer_login() {
		var busyLayer1 = document.getElementById("loading-layer-login")
		if (busyLayer1 != null) {
			busyLayer1.style.visibility = "hidden";
		}
}

function logins()
{
	var poststr = "txtusername="+document.getElementById("txtusername").value+"&txtpassword="+document.getElementById("txtpassword").value+"&cmd=cl_login";
//	cllogin("process.php?cid=3","main_menu");
	cllogin("process.php?cid=56","logins",poststr);
//	cllogin("process.php","phan_giua");
//	timeload = (((new Date()).getTime() - began_loading))+ 2000;
//	setTimeout('cllogin("process.php?cid=58","logins");',timeload);
}

function logouts()
{
	if( ! confirm("Do you really want to logout ?"))	
		return false;
	var began_loading = (new Date()).getTime();
	cllogin("process.php?cid=57","infos");
	timeload = (((new Date()).getTime() - began_loading))+ 2000;
	setTimeout('document.location="index.php"',timeload);
}

// end login script

function show_product_category($id)
	{
			if(document.getElementById($id).style.display == 'none')
				document.getElementById($id).style.display = '';
			else	
				document.getElementById($id).style.display = 'none';
	
			makeHistory("cid=54&product_category_id="+$id,"noidung");
	}

function show_location(value,language)
	{
		tasubpage1('process.php?cid=60&language="+language+"&countrys='+value,'location');		
	}
	
function registers(language)
	{
		tasubpage1("process.php?cid=59&language="+language,"phan_giua");	
	}

function forget_pass()
	{
		tasubpage1("process.php?cid=63","logins");	
	}
	
function add_contact(language)
	{
		var began_loading = (new Date()).getTime();	
		var poststr = "submit=1&fullname="+document.getElementById("fullname").value+"&email="+document.getElementById("email").value+"&phone="+document.getElementById("phone").value+"&content="+document.getElementById("content").value+"&department="+document.getElementById("department").value+"&code="+document.getElementById("code").value;
		tasubpage1("process.php?cid=61&language="+language,"phan_giua",poststr);
		timeload = (((new Date()).getTime() - began_loading))+ 2000;
	}
function check_username(username)
	{
		tasubpage1("process.php?cid=62&username="+username,"error");	
	}
	
function check_email(email)
	{
		tasubpage1("process.php?cid=62&email="+email,"error");	
	}	
	
function view_news_detail(news_id,language)
	{
		makeHistory("cid=69&news_id="+news_id,"noidung");	
	}
	
function view_news_category(news_category_id,language)
	{
		if(news_category_id == 0)
			makeHistory("cid=67","noidung");
		else
			makeHistory("cid=67&news_category_id="+news_category_id,"noidung");
	}	
	
function add_to_cart(b) // cid=74 , ticket_id
   {
		var began_loading = (new Date()).getTime();
		tasubpage1("process.php?cid=74&ticket_id="+b+"&count=1","noidung");
		timeload = (((new Date()).getTime() - began_loading))+ 2000;
		setTimeout('tasubpage1("process.php?cid=75","noidung")',timeload);
   }

function cancel_cart()
   {
	   	var began_loading = (new Date()).getTime();
		tasubpage1("process.php?cid=76","noidung");	
		timeload = (((new Date()).getTime() - began_loading))+ 2000;
		setTimeout('window.document.location="index.php?cid=31"',timeload);
   }

function change_ticket_count(ticket_id,count,stt)
	{
		tasubpage1("process.php?cid=75&ticket_id="+ticket_id+"&count="+count+"&id_count="+stt,"noidung");
	}
	
function show_shipping(i)
	{
		if(document.getElementById(i).style.display == 'none')
			document.getElementById(i).style.display='';
		else
			document.getElementById(i).style.display = 'none';
	}
		
function change_product_shipping(shipping,product_id)
	{	
		if(isNumeric(shipping))	
			tasubpage1("process.php?cid=75&shipping="+shipping+"&edit_product_id="+product_id,"phan_giua");
//		get_dulieu('emarket/index.php?cid=12&shipping='+shipping+'&edit_product_id='+product_id);
	}

function delete_cart(id)
   {
	   	var began_loading = (new Date()).getTime();
		tasubpage1("process.php?cid=77&delete_id="+id,"noidung");	
		timeload = (((new Date()).getTime() - began_loading))+ 2000;
		setTimeout('tasubpage1("process.php?cid=75","noidung")',timeload);
   }

function show_check_out($id)
	{
		if($id == 1)
		{
			document.getElementById('payment_method').style.display = "";
			document.getElementById('firstform').action = "sendmail.php?method=chuyenkhoan";
		}
		else if($id == 2)
		{
			document.getElementById('payment_method').style.display = "";
			document.getElementById('firstform').action = "sendmail.php?method=buudien";
		}
		else if($id == 3)
		{
			document.getElementById('payment_method').style.display = "";
			document.getElementById('firstform').action = "sendmail.php?method=hcm";
		}
	}
	
function isEmail(email) 
{   
	if (email == "")
		return false;
	if (email.indexOf(" ") > 0)	
		return false;
	if (email.indexOf("@") == -1)	
		return false;
	if (email.indexOf(".") == -1)	
		return false;
	if (email.indexOf("..") != -1)	
		return false;
	if (email.indexOf("@") != email.lastIndexOf("@"))		
		return false;
		
	var len = email.length;
	
	if (email.lastIndexOf(".") == len-1)
		return false;
	
	var str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghikjlmnopqrstuvwxyz-@._";
	
	for (var index = 0; index < len; index++)
		if (str.indexOf(email.charAt(index)) == -1)
			return false;
			
	var indexDot = 	email.indexOf(".");
	var indexAcsign = email.indexOf("@");
	
	if ((indexDot == indexAcsign-1) || (indexDot-1 == indexAcsign))
		return false;
					
	return true;
}

///////////////////////////////////////////////////////////////////
//-------popup window --------------------------
var popUpWin=0;
function popup(URLStr, width, height)
{
  var left = 100;
  var top = 100;
  if(popUpWin)
  {
    if(!popUpWin.closed) popUpWin.close();
  }
  popUpWin = open(URLStr, '', 'toolbar=no,location=no,directories=yes,status=yes,menubar=yes,scrollbars=yes,resizable=no,copyhistory=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
}

function show_category(id)
{
	if(document.getElementById(id).style.display == 'none')
		document.getElementById(id).style.display = '';
	else	
		document.getElementById(id).style.display = 'none';

	makeHistory("cid=67&news_category_id="+id,"noidung");
}

function show_logins()
{
	if(document.getElementById("logins").style.display == "none")	
		document.getElementById("logins").style.display = "";	
	else
		document.getElementById("logins").style.display = "none";
}

function show_info(user_id)
{
	if(document.getElementById("infos").style.display == "none")	
		document.getElementById("infos").style.display = "";	
	else
		document.getElementById("infos").style.display = "none";
}

function clear_keyword()
{
	if (document.getElementById("txt_keyword").value == 'Tìm kiếm')
		document.getElementById("txt_keyword").value = '';
}

function show_keyword()
{
	if(document.getElementById("txt_keyword").value == "")	
		document.getElementById("txt_keyword").value = 'Tìm kiếm';	
}

function ht_search(keyword)
{
	if(keyword == "" || keyword == 'Từ khóa' || keyword == 'keyword')	
		alert('Bạn chưa nhập vào điều kiện tìm kiếm ');	
	else
	{
		var poststr = "keyword="+keyword+"&cmd=ht_search";	
		tapage("noidung","process.php?cid=87",poststr);
//		tapage("ht_search","process.php?cid=92");
	}
}

function load_video(id)
{
	document.getElementById('player').style.display='';
	makeHistory_new('player','cid=88&id='+id);
	window.scrollTo(100,120);
}

function show_video_category(id)
{
	makeHistory_new('video_list','cid=89&video_category_id='+id);
	window.scrollTo(100,720);
}

function show_sub_category(value)
{
	if (value == 1)	//tin tuc	
	{
		document.getElementById('news_category').style.display = "";
		document.getElementById('news_category1').style.display = "";
		document.getElementById('video_category').style.display = "none";
		document.getElementById('video_category1').style.display = "none";
	}
	else if(value == 3)	// video
	{
		document.getElementById('news_category').style.display = "none";
		document.getElementById('news_category1').style.display = "none";
		document.getElementById('video_category').style.display = "";
		document.getElementById('video_category1').style.display = "";
	}
	else	// none
	{
		document.getElementById('news_category').style.display = "none";
		document.getElementById('news_category1').style.display = "none";
		document.getElementById('video_category').style.display = "none";
		document.getElementById('video_category1').style.display = "none";
	}
}

function cl_advance_search(keyword,fcategory,txt_date_from,txt_date_to)
{
	if(keyword == "")	
		alert('Bạn chưa nhập vào điều kiện tìm kiếm ');	
	else
	{
		var poststr = "keyword="+keyword+"&cmd=cl_search";	
		if(fcategory == 0)	// all
		{
			if(txt_date_from != "")
			{	if(txt_date_to != "")
					poststr = poststr+"&txt_date_from="+txt_date_from+"&txt_date_to="+txt_date_to;
				else
				{
					alert('Thời gian tìm kiếm không chính xác ');	
					return false;	
				}
			}
			if(txt_date_to != "")
			{
				if(txt_date_from == "")	
				{
					alert('Thời gian tìm kiếm không chính xác ');
					return false;	
				}
			}
//			alert(poststr)	
			tapage("noidung","process.php?cid=87",poststr);	
		}
		else if(fcategory == 1)	// news
		{
			var news_category_id = frmsearch1.news_category.value;	
			if(news_category_id > 0)
				poststr = poststr+"&news_category_id="+news_category_id;
			if(txt_date_from != "")
			{	if(txt_date_to != "")
					poststr = poststr+"&txt_date_from="+txt_date_from+"&txt_date_to="+txt_date_to;
				else
					alert('Thời gian tìm kiếm không chính xác ');
			}
			if(txt_date_to != "")
			{
				if(txt_date_from == "")	
					alert('Thời gian tìm kiếm không chính xác ');
			}
//			alert(poststr)
			tapage("cl_searchs","process.php?cid=91",poststr);			
		}
		else if(fcategory == 2)	// lichdien
		{
			if(txt_date_from != "")
			{	if(txt_date_to != "")
					poststr = poststr+"&txt_date_from="+txt_date_from+"&txt_date_to="+txt_date_to;
				else
					alert('Thời gian tìm kiếm không chính xác ');	
			}
			if(txt_date_to != "")
			{
				if(txt_date_from == "")	
					alert('Thời gian tìm kiếm không chính xác ');
			}
//			alert(poststr)			
			tapage("cl_searchs","process.php?cid=93",poststr);
		}
		else if(fcategory == 3)	// video
		{
			var video_category_id = frmsearch1.video_category.value;
			if(video_category_id > 0)
				poststr = poststr+"&video_category_id="+video_category_id;
			if(txt_date_from != "")
			{	if(txt_date_to != "")
					poststr = poststr+"&txt_date_from="+txt_date_from+"&txt_date_to="+txt_date_to;
				else
					alert('Thời gian tìm kiếm không chính xác ');	
			}
			if(txt_date_to != "")
			{
				if(txt_date_from == "")	
					alert('Thời gian tìm kiếm không chính xác ');
			}
//			alert(poststr)	
			tapage("cl_searchs","process.php?cid=94",poststr);
		}
//		tapage("cl_search","process.php?cid=92");
	}

}

function shownewsletter()
{
	if(document.getElementById('newsletter').style.display == 'none')
		document.getElementById('newsletter').style.display = '';
	else
		document.getElementById('newsletter').style.display = 'none';
}

function clear_textbox(text,id)
{
	if(document.getElementById(id).value == text)
		document.getElementById(id).value = '';
}

function show_textbox(text,id)
{
	if(document.getElementById(id).value == "")	
		document.getElementById(id).value = text;	
}

function newsletter(email)
{
	if(email == 'Địa chỉ email' || email == 'Email Address')
		alert('Bạn chưa nhập email. ');
	else
	{
		var poststr = "email="+email+"&cmd=ht_newsletter";	
		tapage("newsletter","process.php?cid=95",poststr);
	}
}

function view_product_detail(product_id)
{
	if(product_id == 0)
		alert('Product id is not null. ');	
	else
		makeHistory_('cid=70&action=new&product_id='+product_id,'noidung');	
}

function view_product_detail_new(product_id)
{
//	alert(product_id)	
	if(product_id == 0)
		alert('Product id is not null. ');	
	else
		makeHistory_('cid=70&action=new&product_id='+product_id,'noidung');	
}

function close_this_tab(tab)
{
	if(tab == 0)
		alert('Tab product is not null. ');	
	else
		makeHistory_('cid=104&tab='+tab,'noidung');		
}
