// epi_ajax.js
// Ajax script
// www.epivietnam.com

var bustcachevar=1 //bust potential caching of external pages after initial request? (1=yes, 0=no)
var loadedobjects=""
var rootdomain="http://"+window.location.hostname
var bustcacheparameter=""

// Load page using ajax
function ajax_page(page, param, div_load)
{
	var page_request = false
	if (window.XMLHttpRequest) // if Mozilla, Safari etc
	page_request = new XMLHttpRequest()
	else if (window.ActiveXObject){ // if IE
	try {
	page_request = new ActiveXObject("Msxml2.XMLHTTP")
	} 
	catch (e){
	try{
	page_request = new ActiveXObject("Microsoft.XMLHTTP")
	}
	catch (e){}
	}
	}
	else return false
	
	document.getElementById(div_load).style.display = "block";
	preloader(div_load); // preloading image waiting
	
	if (bustcachevar) //if bust caching of external page
		bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
	page_request.open('GET', url+bustcacheparameter, true)
	page_request.onreadystatechange=function(){handleResponse(page_request, div_load)}
	page_request.send(null)
}

// Handle responses
function handleResponse(page_request, div_load)
{
	if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
	document.getElementById(div_load).innerHTML=page_request.responseText
}

// Load external files (CSS, JS) to current page
function load_object()
{
	if (!document.getElementById)
	return
	for (i=0; i<arguments.length; i++){
	var file=arguments[i]
	var fileref=""
	//if (loadedobjects.indexOf(file)==-1){ //Check to see if this object has not already been added to page before proceeding
	if (file.indexOf(".js")!=-1){ //If object is a js file
	fileref=document.createElement('script')
	fileref.setAttribute("type","text/javascript");
	fileref.setAttribute("src", file + '?rand=' + Math.round(100000*Math.random()));
	}
	else if (file.indexOf(".css")!=-1){ //If object is a css file
	fileref=document.createElement("link")
	fileref.setAttribute("rel", "stylesheet");
	fileref.setAttribute("type", "text/css");
	fileref.setAttribute("href", file);
	}
	//}
	if (fileref!=""){
	document.getElementsByTagName("head").item(0).appendChild(fileref)
	loadedobjects+=file+" " //Remember this object as being already added to page
	}
	}
}

// Preload
function preloader(el)
{
	var preloader = document.getElementById(el);
	preloader.innerHTML = "<div align=center style='padding:5px'><img src='images/loading.gif'></div>";
	
}

// Load page ajaxly
function load_page(page, param, div_load)
{
	url = 'module/' + page + '.php?' + param;
	ajax_page(url, param, div_load);
}

function switch_tab(tab_name,id,page,param,location,numtab)
{
	
	var i = 0;
	var tabid = "";	
	for (i = 0; i < numtab; i ++)
	{			
		if ((i + 1) == id)
		{			
			tabid = tab_name + id;	
			document.getElementById(tabid + "_off").style.display = "none";
			document.getElementById(tabid + "_on").style.display = "block";
		}
		else
		{
			tabid = i + 1;				
			tabid = tab_name + tabid;
			document.getElementById(tabid + "_off").style.display = "block";
			document.getElementById(tabid + "_on").style.display = "none";
		}
	}
	// get source
	url = "inc/" + page + ".php?" + param;
	// display on location
	display(url,location);
	
}

function switch_page(page,param,location)
{
	// get source
	url = "module/" + page + ".php?" + param;
	// display on location
	display(url,location);
}

/************************************************************************************************************
Ajax chained select
************************************************************************************************************/
/* Simple AJAX Code-Kit (SACK) v1.6.1 */
/* @2005 Gregory Wild-Smith */
/* www.twilightuniverse.com */
/* Software licenced under a modified X11 licence,
   see documentation or authors website for more details */

function sack(file) {
	this.xmlhttp = null;

	this.resetData = function() {
		this.method = "POST";
  		this.queryStringSeparator = "?";
		this.argumentSeparator = "&";
		this.URLString = "";
		this.encodeURIString = true;
  		this.execute = false;
  		this.element = null;
		this.elementObj = null;
		this.requestFile = file;
		this.vars = new Object();
		this.responseStatus = new Array(2);
  	};

	this.resetFunctions = function() {
  		this.onLoading = function() { };
  		this.onLoaded = function() { };
  		this.onInteractive = function() { };
  		this.onCompletion = function() { };
  		this.onError = function() { };
		this.onFail = function() { };
	};

	this.reset = function() {
		this.resetFunctions();
		this.resetData();
	};

	this.createAJAX = function() {
		try {
			this.xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			try {
				this.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				this.xmlhttp = null;
			}
		}

		if (! this.xmlhttp) {
			if (typeof XMLHttpRequest != "undefined") {
				this.xmlhttp = new XMLHttpRequest();
			} else {
				this.failed = true;
			}
		}
	};

	this.setVar = function(name, value){
		this.vars[name] = Array(value, false);
	};

	this.encVar = function(name, value, returnvars) {
		if (true == returnvars) {
			return Array(encodeURIComponent(name), encodeURIComponent(value));
		} else {
			this.vars[encodeURIComponent(name)] = Array(encodeURIComponent(value), true);
		}
	}

	this.processURLString = function(string, encode) {
		encoded = encodeURIComponent(this.argumentSeparator);
		regexp = new RegExp(this.argumentSeparator + "|" + encoded);
		varArray = string.split(regexp);
		for (i = 0; i < varArray.length; i++){
			urlVars = varArray[i].split("=");
			if (true == encode){
				this.encVar(urlVars[0], urlVars[1]);
			} else {
				this.setVar(urlVars[0], urlVars[1]);
			}
		}
	}

	this.createURLString = function(urlstring) {
		if (this.encodeURIString && this.URLString.length) {
			this.processURLString(this.URLString, true);
		}

		if (urlstring) {
			if (this.URLString.length) {
				this.URLString += this.argumentSeparator + urlstring;
			} else {
				this.URLString = urlstring;
			}
		}

		// prevents caching of URLString
		this.setVar("rndval", new Date().getTime());

		urlstringtemp = new Array();
		for (key in this.vars) {
			if (false == this.vars[key][1] && true == this.encodeURIString) {
				encoded = this.encVar(key, this.vars[key][0], true);
				delete this.vars[key];
				this.vars[encoded[0]] = Array(encoded[1], true);
				key = encoded[0];
			}

			urlstringtemp[urlstringtemp.length] = key + "=" + this.vars[key][0];
		}
		if (urlstring){
			this.URLString += this.argumentSeparator + urlstringtemp.join(this.argumentSeparator);
		} else {
			this.URLString += urlstringtemp.join(this.argumentSeparator);
		}
	}

	this.runResponse = function() {
		eval(this.response);
	}

	this.runAJAX = function(urlstring) {
		if (this.failed) {
			this.onFail();
		} else {
			this.createURLString(urlstring);
			if (this.element) {
				this.elementObj = document.getElementById(this.element);
			}
			if (this.xmlhttp) {
				var self = this;
				if (this.method == "GET") {
					totalurlstring = this.requestFile + this.queryStringSeparator + this.URLString;
					this.xmlhttp.open(this.method, totalurlstring, true);
				} else {
					this.xmlhttp.open(this.method, this.requestFile, true);
					try {
						this.xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
					} catch (e) { }
				}

				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;

							if (self.execute) {
								self.runResponse();
							}

							if (self.elementObj) {
								elemNodeName = self.elementObj.nodeName;
								elemNodeName.toLowerCase();
								if (elemNodeName == "input"
								|| elemNodeName == "select"
								|| elemNodeName == "option"
								|| elemNodeName == "textarea") {
									self.elementObj.value = self.response;
								} else {
									self.elementObj.innerHTML = self.response;
								}
							}
							if (self.responseStatus[0] == "200") {
								self.onCompletion();
							} else {
								self.onError();
							}

							self.URLString = "";
							break;
					}
				};

				this.xmlhttp.send(this.URLString);
			}
		}
	};

	this.reset();
	this.createAJAX();
}

var ajax = new Array();

function job_register(frm) {
    var ho_ten = frm.Ho_ten.value;
    var trinh_do = frm.Trinh_do[frm.Trinh_do.selectedIndex].value;
    var dien_thoai = frm.Dien_thoai.value;
    var email = frm.Email.value;
    var vi_tri = frm.Vi_tri.value;
    var session_id = frm.session_id.value;
    if (ho_ten.length > 0 && trinh_do.length > 0 && trinh_do.length > 0 && dien_thoai.length > 0
            && email.length > 0 && vi_tri.length > 0 && session_id.length > 0) {
        var index = ajax.length;
        ajax[index] = new sack();
		//ajax[index].requestFile = 'include/recruit/recruit.action.php?Ho_ten='+ho_ten+'&Trinh_do='+trinh_do+'&Dien_thoai='+dien_thoai+'&Email='+email+'&Vi_tri='+vi_tri+'&session_id='+session_id;	// Specifying which file to get
        ajax[index].method = 'POST';
        ajax[index].setVar('Ho_ten', ho_ten);
        ajax[index].setVar('Trinh_do', trinh_do);
        ajax[index].setVar('Dien_thoai', dien_thoai);
        ajax[index].setVar('Email', email);
        ajax[index].setVar('Vi_tri', vi_tri);
        ajax[index].setVar('session_id', session_id);
        ajax[index].requestFile = 'include/ajax/recruit.action.php';
		ajax[index].onCompletion = function(){ recruit_result(index) };	// Specify function that will be executed after file has been found
		ajax[index].runAJAX();		// Execute AJAX function
    }
    return false;
}

function vote_newvote(frm) {
   var value = getCheckedValue(frm.vote);
   var session_id = frm.session_id.value;
   var cat = frm.cat.value;
   if (value != '' && session_id.length > 0) {
        var index = ajax.length;
        ajax[index] = new sack();
        ajax[index].method = 'POST';
        ajax[index].setVar('vote', value);
        ajax[index].setVar('cat', cat);
        ajax[index].setVar('session_id', session_id);
        ajax[index].requestFile = 'include/ajax/vote.action.php';
		ajax[index].onCompletion = function(){ vote_result(index) };	// Specify function that will be executed after file has been found
		ajax[index].runAJAX();		// Execute AJAX function
    }
    return false;
}

function recruit_result(index)
{
    //alert("Complete");
	var obj = document.getElementById('tttd');
    eval(ajax[index].response);	// Executing the response from Ajax as Javascript code
}

function vote_result(index)
{
    //alert("Complete");
	var obj = document.getElementById('myvote');
    eval(ajax[index].response);	// Executing the response from Ajax as Javascript code
}

// return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}
