var CreatePopup = {
	info: {
		name: 'CreatePopup',
		version: '1.9',
		author: 'Hoang Tu Nguyen',
		lastEdit: '07/07/2009',
		url: 'http://vn.myblog.yahoo.com/hoangtuera'
	},
	config: {
		// Default Config Show
		popupWidth:500,
		popupHeight:400,
		bgOpacity:60
	},
	Show: function(id, pxwith, pxheight, scroller, fade, opacity){
		this.idObj = id;
		var pxwith = (pxwith) ? pxwith : this.config.popupWidth;
		var pxheight = (pxheight) ? pxheight : this.config.popupHeight;
		var _opacity = (opacity) ? opacity : this.config.bgOpacity;
		var popupEl = document.getElementById(id);
		var _numberIndex = this.generalNumber('999999');
		var _top = this.getTop();
		var _width = this.getWidth();
		var _height = this.getHeight();
		var info = this.info;

		//check exist
		if (document.getElementById('BackgroundMaskLayer')) {
			var maskEl = document.getElementById('BackgroundMaskLayer');
			maskEl.parentNode.removeChild(maskEl);
		}
		//create background mask
		var maskEl = document.createElement("div");
		maskEl.setAttribute('id', 'BackgroundMaskLayer');
		maskEl.style.position = "absolute";
		maskEl.style.zIndex = _numberIndex;
		maskEl.style.background = "#000000";
		maskEl.style.top = _top + "px";
		maskEl.style.left = "0px";
		maskEl.style.width = "100%";
		maskEl.style.height = "100%";

		maskEl.onclick = function(event){
			var event = event || window.event;
			event.cancelBubble = true;
			//CreatePopup.Close();
		};
		maskEl.ondblclick = function(event){
			var event = event || window.event;
			event.cancelBubble = true;
			alert('Name: ' + info.name + '\nVersion: ' + info.version + '\nAuthor: ' + info.author + '\nUrl: ' + info.url);
		};
		document.body.appendChild(maskEl);
		( fade ) ? this.__fadeOjb(0, "BackgroundMaskLayer",_opacity) : this.setOpacity(_opacity,"BackgroundMaskLayer");

		// set popup show
		popupEl.style.width = pxwith + "px";
        popupEl.style.height = pxheight + "px";
        popupEl.style.position = "absolute";
        popupEl.style.zIndex = _numberIndex + 1;
        popupEl.style.display = "block";
        popupEl.style.border = "1px solid #999000";
        popupEl.style.top = (_top + ((_height - popupEl.offsetHeight) / 2)) + "px";
        popupEl.style.left = (_width - popupEl.offsetWidth) / 2 + "px";
        popupEl.style.backgroundColor = "#FFFFFF";

		( fade ) ? this.__fadeOjb(45, id, 100) : function(){
			popupEl.style.display = '';
		};
		(!scroller) ? this.setHiddenScrollBar(true) : this.onReDraw();
		this.onResize();
	},
	onReDraw: function(){
		if (window.onscroll instanceof Function) {
			window.onscroll = function(){
				__reDraw();
			}
		}
		else {
			window.onscroll = __reDraw;
		}
		var id = this.idObj;
		function __reDraw(){
			var _reTop = CreatePopup.getTop();
			var _reWidth = CreatePopup.getWidth();
			var _reHeight = CreatePopup.getHeight();
			var maskEl = document.getElementById('BackgroundMaskLayer');
			maskEl.style.top = _reTop + "px";
			var popupEl = document.getElementById(id);
			popupEl.style.top = (_reTop + ((_reHeight - popupEl.offsetHeight) / 2)) + "px";
		}
	},
	onResize: function(){
		if (window.onresize instanceof Function) {
			window.onresize = function(){
				__reSize();
			}
		}
		else {
			window.onresize = __reSize;
		}
		var id = this.idObj;
		function __reSize(){
			var _reTop = CreatePopup.getTop();
			var _reWidth = CreatePopup.getWidth();
			var _reHeight = CreatePopup.getHeight();
			var popupEl = document.getElementById(id);
			popupEl.style.top = (_reTop + ((_reHeight - popupEl.offsetHeight) / 2)) + "px";
			popupEl.style.left = (_reWidth - popupEl.offsetWidth) / 2 + "px";
		}
	},
	generalNumber: function(num){
		var random = (Math.random() == 0) ? 1 : Math.random();
		random = Math.floor(random * num);
		random = random * 2;
		return random;
	},
	getWidth: function(){
		if (window.innerWidth !== undefined)
			return window.innerWidth;
		else
			return (document.documentElement) ? document.documentElement.clientWidth : document.body.clientWidth;
	},
	getHeight: function(){
		if (window.innerHeight !== undefined)
			return window.innerHeight;
		else
			return (document.documentElement) ? document.documentElement.clientHeight : document.body.clientHeight;
	},
	getTop: function(){
		if (window.pageYOffset !== undefined)
			return window.pageYOffset;
		else
			return (document.documentElement !== undefined) ? document.documentElement.scrollTop : document.body.scrollTop;
	},
	setOpacity: function(value, id){
		var value = (value == 100) ? 99.999 : value;
		var obj = document.getElementById(id);
		obj.style.visibility = "visible";
		obj.style.filter = "alpha(opacity:" + value + ")"; //IE
		obj.style.KHTMLOpacity = value / 100; // Safari<1.2, Konqueror
		obj.style.MozOpacity = value / 100; // Mozilla and Firefox
		obj.style.opacity = value / 100; // Safari 1.2, newer Firefox and Mozilla, CSS3
	},
	setHiddenScrollBar: function(value){
		if (value) {
			document.getElementsByTagName("html")[0].style.overflow = "hidden";
			document.body.style.overflow = "hidden";
		}
		else {
			document.getElementsByTagName("html")[0].style.overflow = "";
			document.body.style.overflow = "";
		}
	},
	Close: function(){
		var maskEl = document.getElementById('BackgroundMaskLayer');
		if (!maskEl)
			return;
		maskEl.parentNode.removeChild(maskEl);
		document.getElementById(this.idObj).style.display = "none";
		this.setHiddenScrollBar(false);
	},
	__fadeOjb: function(value, id, stopFade){
		if (value <= stopFade) {
			this.setOpacity(value, id);
			value += 1;
			setTimeout("CreatePopup.__fadeOjb(" + value + ",'" + id + "'," + stopFade + ")", 1);
		}
	}
};

/**
 * Define the Nhtu instance.
 */
var NHTU={version:'1.0',author:'Hoang Tu Nguyen',email:'hoangtuera@gmail.com'};
//--------------------------------------------------------------------
NHTU.Ajax=function(){
	var ojb = new Object();
    var xmlhttp = new Object();
	switch (arguments.length) {
		case 0:
			alert('Please insert the parameters for function.');
			return ;
			break;
		case 1:
			this.options = new function(){
				this.server = 'server.php';
				this.method = "POST";
				this.param = null;
				this.onRequest = function(){
					alert('Loading, please wait ...');
				};
				this.onSuccess = null;
				this.onError = function(){
					alert("There was a problem with the request: " + this.statusText);
				};
			};
			// get default options
			for (var i in this.options) {
				ojb[i] = this.options[i];
			}
			// set new options
			for (var i in arguments[0]) {
				ojb[i] = arguments[0][i];
			}
			break;
		default:
			alert('This function support only one object. Please check again.');
			return ;
	}
    function getXmlHttpRequest(){
		// code for IE7+, Firefox, Chrome, Opera, Safari
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
            if (xmlhttp.overrideMimeType) {
                // set type accordingly to anticipated content type
                xmlhttp.overrideMimeType('text/html');
            }
        }
        else
		// code for IE5, IE6
            if (window.ActiveXObject) {
                try {
                    xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch (e) {
                    try {
                        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    catch (e) {
                    }
                }
            }
    }
    function isReady(){
        return (xmlhttp.readyState == 4 || xmlhttp.readyState == 0);
    }
    function isComplete(){
        return xmlhttp.readyState == 4;
    }
    function isSuccess(){
        return ((xmlhttp.status >= 200) && (xmlhttp.status < 300));
    }
    function setHeader(){
        if (ojb.method.toUpperCase() == "POST") {
            xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=UTF-8");
            xmlhttp.setRequestHeader("Content-length", ojb.param.length);
            xmlhttp.setRequestHeader("Connection", "close");
        }
    }
    function processRequest(){
        if (isComplete()) {
            if (isSuccess()) {
                if (typeof ojb.onSuccess == "function") {
                    ojb.onSuccess.call(xmlhttp);
                }
                else {
                    eval(ojb.onSuccess);
                }
            }
            else {
                if (typeof ojb.onError == "function") {
                    ojb.onError.call(xmlhttp);
                }
                else {
                    eval(ojb.onError);
                }
            }
        }
    }

	// Run ajax
    NHTU.Ajax.prototype.run = function(){
		getXmlHttpRequest();
        if (isReady()) {
			if (typeof ojb.onRequest == "function") {
                ojb.onRequest.call(xmlhttp);
            }
            else {
                eval(ojb.onRequest);
            }
            var __url = null;
            if (ojb.param != null && ojb.method.toUpperCase() == "POST" && ojb.param != "") {
                __url = ojb.param;
                __url = encodeURI(__url);
                xmlhttp.open("POST", ojb.server, true);
                setHeader();
            }
            else {
                __url = ojb.server + "?" + ojb.param + "&sid=" + __jsid();
                __url = encodeURI(__url);
                xmlhttp.open("GET", __url, true);
                __url = null;
            }
			xmlhttp.send(__url);
        }
        xmlhttp.onreadystatechange = processRequest;
        // private function
        function __jsid(){
            return Math.random() * 10000;
        }
    }
	NHTU.Ajax.prototype.stop = function(){
		if (xmlhttp && xmlhttp.readyState != 0){
			xmlhttp.abort();
		}
	}
}
function autoParser(url){

	if(url.indexOf('http://')==-1){
		url = "http://" + url;
	}
	//url = encodeURIComponent(url);

	var content = document.getElementById('txt_content');

	var param = "modules=ajax&task=parserdescription&url=" + url;
	var paser = new NHTU.Ajax({
		server: "index.php",
		method: "GET",
		param: param,
		onRequest: function() {
			content.innerHTML = 'Loading ...';
		},
		onSuccess: function() {
			content.innerHTML = this.responseText;
		}
	});
	paser.run();
};

function logOut(msg){
	html = document.getElementsByTagName("html");
	html[0].style.filter = "progid:DXImageTransform.Microsoft.BasicImage(grayscale=1)";
	if (confirm(msg))
	{
		return true;
	}
	else
	{
		html[0].style.filter = "";
		return false;
	}
};
function txtLimit(fieldID, limit, countID){
	var countID = document.getElementById(countID);
	if (fieldID.value.length > limit) {
	    fieldID.value = fieldID.value.substring(0, limit);
	}
	countID.innerHTML = "Max charater "+ limit +", current: "+ fieldID.value.length;
};
function reLoadCaptcha(){
	var img = document.getElementById('captcha');
    var reload = document.getElementById('reloadcaptcha');
	var param = "SID="+ Math.random()*1000;
	var captcha = new NHTU.Ajax({
		server: "captcha.php",
		method: "POST",
		param: param,
		onRequest: function() {
			reload.innerHTML = 'Loading ....';
		},
		onSuccess: function() {
			img.src = 'captcha.php?'+ Math.random()*1000;
			reload.innerHTML = '<a href="javascript:reLoadCaptcha();">Refresh Image</a>';
		}
	});
	captcha.run();
}

/*****************************************
 * function check string, allow A-Za-z0-9
 * @param string s
 * return boolean.
 */
function isValidFromSearch(s){
	if(s.search("'") !== -1) return false;
	return true;
}
/*****************************************
 * function trim string
 * return string.
 */
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, "");
}
/*****************************************
 * function searchForm
 *
 */
function search(frm){	var keyform = frm.keywords;
    var key = keyform.value.trim();
    if(key.length == 0 || key=='Enter keywords ...'){
    	alert('Keyword(s) not null. Please try again.');
    	keyform.focus();
    	return false;
    }
    if(! isValidFromSearch(key)){
    	alert('Keyword(s) contains special characters.');
    	keyform.focus();
    	return false;
    }
    window.location.href='?modules=search&task=normal&keyword='+ encodeURIComponent(key);
    return false;
}

function checkAnnouncement(){	if(window.name == 'closePopup') return;
	var checkAnnouncement = new NHTU.Ajax({
		server: "webdirectory/announcements_popup.php",
		method: "POST",
		param: "mode=guest&action=check",
		onRequest: function() {
		},
		onSuccess: function() {
			eval(this.responseText);
		}
	});
	checkAnnouncement.run();
}
function loadAnnouncement(){
	var loadAnnouncement = new NHTU.Ajax({
		server: "webdirectory/announcements_popup.php",
		method: "POST",
		param: "mode=guest&action=load",
		onRequest: function() {
		},
		onSuccess: function() {
			document.getElementById("showpopup_content").innerHTML = this.responseText;
		}
	});
	loadAnnouncement.run();
}
function closePopup(){
	if(window.name == '' || window.name == null){		window.name = 'closePopup';	}	CreatePopup.Close();}

