// var IMG_URL = '.';
if(typeof(IMG_URL) == "undefined")
	var IMG_URL = '.';
var DEFAULT_ZINDEX = 900;
var SYSTEM_OVERLOAD = "Hệ thống đang quá tải, vui lòng quay lại sau!";
var SYSTEM_LOADING = "Đang tải";
var COMMENT_SENDER = "Vui lòng nhập vào \"Người gửi\"";
var COMMENT_TEXT = "Vui lòng nhập vào \"Lời Bình Luận\"";
var COMMENT_CAPCHA = "Vui lòng nhập Mã Xác Nhận";

var JSON = new (function(){
    var useHasOwn = !!{}.hasOwnProperty;

    // crashes Safari in some instances
    //var validRE = /^("(\\.|[^"\\\n\r])*?"|[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t])+?$/;

    var pad = function(n) {
        return n < 10 ? "0" + n : n;
    };

    var m = {
        "\b": '\\b',
        "\t": '\\t',
        "\n": '\\n',
        "\f": '\\f',
        "\r": '\\r',
        '"' : '\\"',
        "\\": '\\\\'
    };

    var encodeString = function(s){
        if (/["\\\x00-\x1f]/.test(s)) {
            return '"' + s.replace(/([\x00-\x1f\\"])/g, function(a, b) {
                var c = m[b];
                if(c){
                    return c;
                }
                c = b.charCodeAt();
                return "\\u00" +
                    Math.floor(c / 16).toString(16) +
                    (c % 16).toString(16);
            }) + '"';
        }
        return '"' + s + '"';
    };

    var encodeArray = function(o){
        var a = ["["], b, i, l = o.length, v;
            for (i = 0; i < l; i += 1) {
                v = o[i];
                switch (typeof v) {
                    case "undefined":
                    case "function":
                    case "unknown":
                        break;
                    default:
                        if (b) {
                            a.push(',');
                        }
                        a.push(v === null ? "null" : JSON.encode(v));
                        b = true;
                }
            }
            a.push("]");
            return a.join("");
    };

    this.encodeDate = function(o){
        return '"' + o.getFullYear() + "-" +
                pad(o.getMonth() + 1) + "-" +
                pad(o.getDate()) + "T" +
                pad(o.getHours()) + ":" +
                pad(o.getMinutes()) + ":" +
                pad(o.getSeconds()) + '"';
    };

    
    this.encode = function(o){
        if(typeof o == "undefined" || o === null){
            return "null";
        }else if(o.constructor == Array){
            return encodeArray(o);
        }else if(o.constructor == Date){
            return this.encodeDate(o);
        }else if(typeof o == "string"){
            return encodeString(o);
        }else if(typeof o == "number"){
            return isFinite(o) ? String(o) : "null";
        }else if(typeof o == "boolean"){
            return String(o);
        }else {
            var a = ["{"], b, i, v;
            for (i in o) {
                if(!useHasOwn || o.hasOwnProperty(i)) {
                    v = o[i];
                    switch (typeof v) {
                    case "undefined":
                    case "function":
                    case "unknown":
                        break;
                    default:
                        if(b){
                            a.push(',');
                        }
                        a.push(this.encode(i), ":",
                                v === null ? "null" : this.encode(v));
                        b = true;
                    }
                }
            }
            a.push("}");
            return a.join("");
        }
    };
    
    this.decode = function(json){
		try{
			return eval("(" + json + ')');
		}catch(e){
			return {};
		}
    };
})();

function funcErrorRespons(jsonObj){
	// Check error jsonObj
	if( (typeof(jsonObj.errCode)!= 'undefined' && jsonObj.errCode != 0)
		|| (typeof(jsonObj.errorNo)!= 'undefined' && jsonObj.errorNo != 0) ) {
		alert(SYSTEM_OVERLOAD);
		return true;
	}
	return false;
}

function dump(o){
	var html = '<div style="overflow: auto; margin-top: 10px; text-align: left; background-color: white; color: black; height: 200px;"><table width="100%" style="background-color:white; color:red"><tr><th>Properties</th><th>Values</th></tr>';
	for( var p in o ) {
		try{
			html += '<tr><th>"'+p+'"</th><td>"'+o[p]+'"</td></tr>';
		}catch(e){
			html += '<tr><td colspan="2">"'+p+'" not found; Error: "'+e.message+'"</td></tr>';
		}
	}
	html += '</table></div>';
	$(html).appendTo("body");
}

function debugInfo(text) {
	$('#div_debug_info').html(text);
}

function timeoutUpdate() {
	ttt ++;
	setTimeout('timeoutUpdate()', 500);
	$('#div_debug_info').css({
				'left':(getWindowScrollTop()+'px'),
				'top':(getWindowScrollLeft()+'px')
			}
		);
}

function objToString(obj){
	return JSON.encode(obj);
}

function cloneObject(obj){
	var ret = {};
	for( var p in obj ){
		if( typeof(obj[p]) == 'object' ) {
			ret[p] = cloneObject(obj[p]);
		} else {
			ret[p] = obj[p];
		}
	}
	return ret;
}

function extendObject(des, src){
	if(!des || typeof(des) != 'object' ) {
		des = {};
	}
	for( var p in src ){
		if( typeof(src[p]) == 'object' ) {
			extendObject(des[p], src[p]);
		} else {
			des[p] = src[p];
		}
	}
	return des;
}

function getWindowWidth(){
	if (jQuery.browser.webkit || jQuery.browser.mozilla) return window.innerWidth;
	if (jQuery.browser.opera) return document.body.clientWidth;
	return document.documentElement.clientWidth;
}

function intval(v) {
	v = parseInt(v);
	return isNaN(v) ? 0 : v;
}

function getWindowHeight(){
	var height = 0;
	if (jQuery.browser.webkit || jQuery.browser.mozilla) height = window.innerHeight;
	if (jQuery.browser.opera) height = document.body.clientHeight;
	height = document.documentElement.clientHeight;
	return height;
}

function getWindowScrollTop(){
	var de = document.documentElement || document.body;
	return window.pageYOffset || de.scrollTop || 0;
}

function getWindowScrollLeft(){
	var de = document.documentElement || document.body;
	return window.pageXOffset || de.scrollLeft || 0;
}

function getWindowScrollWidth(){
	if (jQuery.browser.msie)
		return Math.max(document.documentElement.offsetWidth, document.documentElement.scrollWidth);
	if (jQuery.browser.webkit || jQuery.browser.mozilla)
		return document.body.scrollWidth;
	return document.documentElement.scrollWidth;
}

function getWindowScrollHeight(){
	var height = 0;
	if (jQuery.browser.msie)
		height = Math.max(document.documentElement.offsetHeight, document.documentElement.scrollHeight);
	if (jQuery.browser.webkit || jQuery.browser.mozilla)
		height = document.body.scrollHeight;
	height = document.documentElement.scrollHeight;
	var divs = $("body > div");
	var newH = 0;
	divs.each(function(){
		var el = $(this);
		try {
			var zIndex = el.css('z-index');
			if( zIndex == 'auto' || zIndex == 0) return;
			var dis = el.css('display');
			var vis = el.css('visibility');
			if(dis == 'none' || vis == 'hidden')
				return;
			var old = el.height() + intval(el.css('marginTop')) + intval(el.css('marginBottom'));
			newH += old;
		}catch(e){
			return;
		}
	});
	return ((newH>height) ? newH : height);
}

function getWindowMarginTop(){
	var de = document.documentElement || document.body;
	var margin = de && de.scrollTop;
	return intval(margin);
}

function getWindowPageSize(){
	var de = document.documentElement || document.body;
	var w = window.innerWidth || self.innerWidth || (de&&de.clientWidth);
	var h = window.innerHeight || self.innerHeight || (de&&de.clientHeight);
	return {'width': w, 'height':h};
}

function stopWindowEvent(e) {
	try {
		var ev = jQuery.Event ? new jQuery.Event(e||window.event||null) : jQuery.event.fix(e||window.event||null);;
		ev.preventDefault();
		ev.stopPropagation();
	}catch(ex){}
	return true;
}

var JThickBox = function(op) {

	var oOptions = {
		sPrefix: 'box',
		nLeft: 0,
		nTop: 0,
		nSpaceTop:0,
		nWidth: 0,
		nHeight: 0,
		oOverlay: {id: '_overlay', bShow: false, bClick: true, css:{
				display:'block', opacity:0.75,
				width:'100%', top:'0px', 'height':'100%',
				left:'0px', backgroundColor: '#000000'
			}, className:''},
		oClose: {id: '_close', bShow: false, css:{}, className:''},
		sContentOffId: '',
		oLoading: {id: '_loading', html:'', bClick: false, css:{}, className:''},
		oContent: {id: '_window', css:{}, className:''},
		nDoneOnce: 0,
		bSimple: true,
		nZIndex: null,
		bCheckError: false
	};

	if(!!op) {
		this.options = extendObject(oOptions, op);
	} else {
		this.options = oOptions;
	}
	this.options.oOverlay.id = this.options.sPrefix + this.options.oOverlay.id;
	this.options.oLoading.id = this.options.sPrefix + this.options.oLoading.id;
	this.options.oClose.id = this.options.sPrefix + this.options.oClose.id;
	this.options.oContent.id = this.options.sPrefix + this.options.oContent.id;
	if( !this.options.nZIndex ) {
		this.options.nZIndex = DEFAULT_ZINDEX;
	}

	var oThis = this;

	this.show = function(obj) {
		try {
			if( oThis.options.bCheckError && ( typeof(obj) == 'object' ) ) {
				if( (typeof(obj.errorNo) != 'undefined' && obj.errorNo != 0) || (typeof(obj.errCode) != 'undefined' && obj.errCode != 0) ){
					alert( SYSTEM_OVERLOAD );
					return this;
				}
			}
			// create overlay and box if non-existent
			if( oThis.options.oOverlay.bShow && !$("#"+oThis.options.oOverlay.id)[0] ) {
				jQuery('<div id="'+oThis.options.oOverlay.id+'" style="position: absolute;left:0px; top:0px"><div>').appendTo("body");
				$('#'+oThis.options.oOverlay.id).css({opacity:0});
				oThis._overlaySize();
				if(oThis.options.oLoading.html != '') {
					jQuery('<div id="'+oThis.options.oLoading.id+'"><div>').appendTo("body");
					$('#'+oThis.options.oLoading.id).html(oThis.options.oLoading.html);
					oThis.load_position();
				}
				$("#"+this.options.oOverlay.id).fadeIn(200);
			}

			if(oThis.options.oLoading.html != '' && !$("#"+oThis.options.oLoading.id)[0]) {
				jQuery('<div id="'+oThis.options.oLoading.id+'"><div>').appendTo("body");
				$('#'+oThis.options.oLoading.id).html(oThis.options.oLoading.html);
				oThis.load_position();
			}

			if( !$("#"+oThis.options.oContent.id)[0] ) {
				$("body").append('<div id="'+oThis.options.oContent.id+'" style="position: absolute;"></div>');
				$("#"+oThis.options.oContent.id).css({opacity: 0});
			}

			if (typeof(document.body.style.maxHeight) === "undefined") {//if IE 6
				$("body","html").css({height: "100%", width: "100%"});
				$("html").css("overflow", "hidden");
			}

			if( oThis.options.oOverlay.bShow && oThis.options.oOverlay.bClick )
				$("#"+oThis.options.oOverlay.id).bind("click", oThis.remove);


			// TODO empty window content instead
			var html = '';
			if( typeof(obj) == 'string' )
				html = obj;
			else if( typeof(obj) == 'object' ) {
				if(typeof(obj.html) != 'undefined')
					html = obj.html;
				else if(typeof(obj.result) != 'undefined')
					html = obj.result;
			}
			$("#"+oThis.options.oContent.id).html(html);

			var child = $("#"+oThis.options.oContent.id).children();
			if(oThis.options.nWidth == 'auto' || oThis.options.nWidth == '100%')
				oThis.options.nWidth = child.width();
			if(oThis.options.nHeight == 'auto' || oThis.options.nHeight == '100%')
				oThis.options.nHeight = child.height();
			
			if(oThis.options.oClose.bShow ) {
				$("#"+oThis.options.oClose.id).bind("click", oThis.remove);
			}
			// TODO don't remove loader etc., just hide and show later
			if( oThis.options.sContentOffId != '' ) {
				$("#"+oThis.options.sContentOffId).bind("click", oThis.remove);
			}

			oThis._showWindow();
			oThis._position();

			$(window).bind("resize", oThis.resizePos);
			$(window).bind("scroll", oThis.scrollPos);
		} catch(ex){
		}
		return oThis;
	}

	this.resizePos = function() {
		oThis._position();
		if(!oThis.options.bSimple) {
			oThis._loadPosition();
			oThis._overlaySize();
		}
	}
	
	this.scrollPos = function() {
		oThis._position();
	}
	
	this.remove = function() {
		
		if (typeof(document.body.style.maxHeight) === "undefined") {//if IE 6
			$("html").css("overflow","scroll");
		}
		
		if($("#"+oThis.options.oOverlay.id)[0])
			$("#"+oThis.options.oOverlay.id).unbind("click", oThis.remove);
		
		if(oThis.options.sContentOffId != '')
			$("#"+oThis.options.sContentOffId).unbind("click", oThis.remove);

		if(oThis.options.oClose.bShow)
			$("#"+oThis.options.oClose.id).unbind("click", oThis.remove);

		var sContentId = "#"+oThis.options.oContent.id;
		$(sContentId).fadeOut(200,function(){
			$(sContentId).trigger("unload").unbind().remove();
			});

		if($("#"+oThis.options.oOverlay.id)[0]) {
			var sOverlayId = "#"+oThis.options.oOverlay.id;
			$(sOverlayId).fadeOut(200,function(){
				$(sOverlayId).trigger("unload").unbind().remove();
			});
		}

		$(window).unbind("scroll", oThis.scrollPos);
		$(window).unbind("resize", oThis.resizePos);
			
		oThis.options.nDoneOnce = 0;
		return oThis;
	}

	this._showWindow = function (){
		var sLoadingId = "#"+oThis.options.oLoading.id;
		var sContentId = "#"+oThis.options.oContent.id;
		if (oThis.options.nDoneOnce == 0) {
			oThis.options.nDoneOnce = 1;
			$(sContentId).fadeIn(250, function(){
				if ($(sLoadingId)[0]) {
					$(sLoadingId).remove();
				}
			}).css({opacity:1});
		} else {
			$(sContentId).css({opacity:1});
			if ($(sLoadingId)[0]) {
				$(sLoadingId).remove();
			}
		}
		$(sContentId).css({'top':'0px', 'left':'0px'});
		var height = $(sContentId).height() + intval($(sContentId).css("marginTop")) + intval($(sContentId).css("marginBottom"));
		var width = $(sContentId).width() + intval($(sContentId).css("marginLeft")) + intval($(sContentId).css("marginRight"));
		oThis.options.nHeight = height;
		oThis.options.nWidth = width;
		height = 0;
		var childs = $(sContentId).children();
		for(var i=0; i< childs.length; i++) {
			if(childs[i].nodeName == "LINK" || 
				childs[i].nodeName == "#text" || 
				childs[i].nodeName == "SCRIPT" || 
				childs[i].nodeName == "NOSCRIPT") continue;
			var val = $(childs[i]);
			if(val.css("display") == "none" || val.css("visibility") == "hidden") continue;
			
			height += val.height() + intval(val.css("marginTop")) + intval(val.css("marginBottom"));
			// width += val.width() + intval(val.css("marginLeft")) + intval(val.css("marginRight"));
		}
		if(height > oThis.options.nHeight)
			oThis.options.nHeight = height;
		/*
		if(width > oThis.options.nWidth) {
			oThis.options.nWidth = width;
		}
		if(oThis.options.nWidth > getWindowWidth() - 17)
			oThis.options.nWidth = getWindowWidth() - 17;
		*/
		$(sContentId).css({"height": oThis.options.nHeight+"px", "width": oThis.options.nWidth+ "px", 'left':'0px'});
		
		return this;
	}

	this._position = function() {
		var size = getWindowPageSize();
		var winHeight = getWindowHeight();
		// oThis.options.nSpaceTop-oThis.options.nTop
		var nTop = $(window).scrollTop();
		if(oThis.options.nHeight <= winHeight - 20)
			nTop += (size.height-oThis.options.nHeight)/2;
		$("#"+oThis.options.oContent.id).css({
					 'width': oThis.options.nWidth+'px',
					 'position': 'absolute',
					 'left': ($(window).scrollLeft()+(size.width-oThis.options.nWidth)/2)+'px',
					 'text-align': 'center',
					 'top': nTop+"px",
					 'z-index': (oThis.options.nZIndex-0),
					 'height': oThis.options.nHeight+'px'});
		return this;
	}

	this._overlaySize = function(){
		// we have to set this to 0px before so we can reduce the size / width of the overflow onresize
		var sOverlayId = "#"+oThis.options.oOverlay.id;
		if(this.options.oOverlay.bShow) {
			oThis.options.oOverlay.css['z-index'] = (oThis.options.nZIndex-2);
			oThis.options.oOverlay.css['display'] = 'block';
			oThis.options.oOverlay.css['position'] = 'absolute';
			oThis.options.oOverlay.css['height'] = getWindowScrollHeight()+'px';
			oThis.options.oOverlay.css['width'] = getWindowScrollWidth()+'px';
			oThis.options.oOverlay.css['left'] = '0px';
			oThis.options.oOverlay.css['top'] = '0px';
			$(sOverlayId).css(oThis.options.oOverlay.css);
		}
		return this;
	}

	this._loadPosition = function() {
		if( oThis.options.oLoading.html != '' ) {
			$("#"+oThis.options.oLoading.id).css({
				'left': (getWindowScrollLeft() + (getWindowWidth())/2)+'px',
				'top': (getWindowScrollTop() + ((getWindowHeight()-10)/2))+'px',
				'display':"block",
				'position': 'absolute',
				'z-index': (oThis.options.nZIndex-1)});
		}
		return oThis;
	}

	return oThis;
};

var oAjaxLoading = {};
var oStartAjax = {isShowLoading: false, isInited: false};

function executeAjaxError(xhr, status, e) {
	if(oStartAjax.isShowLoading == true) {
		oAjaxLoading.remove();
	}
	alert(SYSTEM_OVERLOAD);
}

function loadingAjax(){
	if(oStartAjax.isShowLoading == true) {
		oAjaxLoading.show(oAjaxLoading.options.html);
	}
}

function stopLoadingAjax(){
	if(oStartAjax.isShowLoading == true) {
		oAjaxLoading.remove();
	}
}

function unactiveEventAjax() {
	oStartAjax.isShowLoading = false;
}

function activeEventAjax() {
	if(oStartAjax.isInited == false) {
		oStartAjax.isInited == true;
		oAjaxLoading = new JThickBox({
			sPrefix: 'loading',
			nTop: 0,
			nWidth: 100,
			nHeight: 22,
			html: '<div style="background-color:red;color:white;height:22px; text-align:center; vertical-align:middle; width:100px"><img src="'+IMG_URL+'/images/waitinggreen.gif" border="0"/>&nbsp;&nbsp;'+SYSTEM_LOADING+' ...</div>'
		});
		$("body").ajaxStart(loadingAjax);
		$("body").ajaxStop(stopLoadingAjax);
	}
	$("body").ajaxError(executeAjaxError);
	oStartAjax.isShowLoading = true;
}

/**
	postData: {
		ajax_type:"module", // "block"
		block_name: blockName,
		...
	}

// truong hop 1
PHP
jsonOutput(
	array(
		'id'=>'xyz', //ElementHTML ID:  noi chua doan HTML bao gom Pginging va Content can phan trang
		'html'=>$htmlContent_n_Paging,
		'js'=>''
	)
);
/ *
Ex: <div id="xyz">
	// tat ca cac ROW can phan trang
	Row 1 HTML
	Row 2 HTML
	Paging HTML
 </div>
 * /

// truong hop 2
PHP
jsonOutput(
	array(
		array(
			'id'=>'xyz', //ElementHTML ID:  noi chua doan HTML bao gom Pginging va Content can phan trang
			'html'=>$htmlContent,
			'js'=>''
		),
		array(
			'id'=>'xyz_paging', //ElementHTML ID:  noi chua doan HTML bao gom Pginging va Content can phan trang
			'html'=>$htmlPaging,
			'js'=>''
		),
		...
	)
);

/ *
Ex:
....
<div>
	<div id="xyz">
		// tat ca cac ROW can phan trang
		Row 1 HTML
		Row 2 HTML
	</div>
 </div>
 <div> Some text </div>
<div id="xyz_paging">
	Paging HTML
</div>
 * /


*/
function paging_json(postData, url, e, funcError) {
	stopWindowEvent(e);
	activeEventAjax();
	// unactiveEventAjax();

	var request = $.ajax({
			type: "POST",
			url: url,
			data: 'json='+objToString(postData),
			// username: null,
			// password: null,
			//complete: function(xhr, status),
			success: function(jsonObj, status) {
				if( jsonObj.debug ) {
					$(jsonObj.debug).appendTo("body");
				}
				if( typeof(funcError) == 'function' && funcError(jsonObj) == true) {
					return;
				}
				if( jsonObj.id && jsonObj.html ) {
				// truong hop 1
					try{
						if($('#'+jsonObj.id)[0]) $('#'+jsonObj.id).html(jsonObj.html);
						if( jsonObj.js ) {
							eval(jsonObj.js);
						}
					}catch(ex){}
				} else {
				// truong hop 2
					for( var i = 0; i < jsonObj.length; i++ ) {
						try{
							if($('#'+jsonObj[i].id)[0]) $('#'+jsonObj[i].id).html(jsonObj[i].html);
							if( jsonObj[i].js) {
								eval(jsonObj[i].js);
							}
							if( jsonObj[i].debug ) {
								$(jsonObj[i].debug).appendTo("body");
							}
						}catch(ex){}
					}
				}
			},
			dataType: "json"
		});

	return false;
}

/**
postData: {
	ajax_type:"block", // "module"
	block_name: "tham_do_y_kien",
}

// truong hop 1
PHP
jsonOutput(
	array(
		'id'=>'xyz', //ElementHTML ID:  noi chua doan HTML bao gom Pginging va Content can phan trang
		'html'=>$htmlContent_n_Paging,
		'js'=>''
	)
);
/ *
Ex: <div id="xyz">
	// tat ca cac ROW can phan trang
	Row 1 HTML
	Row 2 HTML
	Paging HTML
 </div>
 * /

// truong hop 2
PHP
jsonOutput(
	array(
		array(
			'id'=>'xyz', //ElementHTML ID:  noi chua doan HTML bao gom Pginging va Content can phan trang
			'html'=>$htmlContent,
			'js'=>''
		),
		array(
			'id'=>'xyz_paging', //ElementHTML ID:  noi chua doan HTML bao gom Pginging va Content can phan trang
			'html'=>$htmlPaging,
			'js'=>''
		),
		...
	)
);

/ *
Ex:
....
<div>
	<div id="xyz">
		// tat ca cac ROW can phan trang
		Row 1 HTML
		Row 2 HTML
	</div>
 </div>
 <div> Some text </div>
<div id="xyz_paging">
	Paging HTML
</div>
 * /
*/
function view_survey(postData, url, e, funcError){
	stopWindowEvent(e);
	activeEventAjax();
	if(typeof(postData.id_prefix) == "undefined")
		postData.id_prefix = 'survey';
	if(typeof(postData.width) == "undefined")
		postData.width = 'auto';
	if(typeof(postData.height) == "undefined")
		postData.height = 'auto';
	if(typeof(postData.top) == "undefined")
		postData.top = 100;
	var oBox = new JThickBox({
		sPrefix: postData.id_prefix,
		nTop: postData.top,
		nWidth: postData.width,
		nHeight: postData.height,
		oOverlay: {id:'_overlay', bShow: true},
		oClose: {id:'_close', bShow: true},
		bSimple: false,
		bCheckError: true
	});
	if( !url )
		url = document.location.href;
	var request = $.ajax({
			type: "POST",
			url: url,
			data: 'json='+objToString(postData),
			success: function(jsonObj, status) {
				if( jsonObj.debug ) {
					$(jsonObj.debug).appendTo("body");
				}
				if( typeof(funcError) == 'function' && funcError(jsonObj) == true) {
					return;
				}
				oAjaxLoading.remove();
				jsonSurvey = jsonObj;
				oBox.show(jsonObj);
			},
			dataType: "json"
		});
	return false;
}

/**
postData: {
	ajax_type:"block", // "module"
	block_name: "tham_do_y_kien",
	vot_mid: "", // Cau Hoi
	vct_mid: "", // Dap An
	afterRespose: function( object) {
		object.id : 
		object.html: 
	}	
}
*/
function post_survey(postData, url, e, funcError){
	stopWindowEvent(e);
	activeEventAjax();
	if(url == '') url = document.location.href;
	if(typeof(postData.id_prefix) == "undefined")
		postData.id_prefix = 'survey';
	if(typeof(postData.width) == "undefined")
		postData.width = 'auto';
	if(typeof(postData.height) == "undefined")
		postData.height = 'auto';
	if(typeof(postData.top) == "undefined")
		postData.top = 100;
	var oBox = new JThickBox({
		sPrefix: postData.id_prefix,
		nTop: postData.top,
		nHeight: postData.height,
		nWidth: postData.width,
		oOverlay: {id:'_overlay', bShow: true},
		oClose: {id:'_close', bShow: true},
		bSimple: false,
		bCheckError: true
	});
	var request = $.ajax({
			type: "POST",
			url: url,
			data: 'json='+objToString(postData),
			success: function(jsonObj, status) {
				if( jsonObj.debug ) {
					$(jsonObj.debug).appendTo("body");
				}
				if( typeof(funcError) == 'function' && funcError(jsonObj) == true) {
					return;
				}
				if( jsonObj.result && jsonObj.result.id ) {
					if( jsonObj.errorNo == 0 ) {
						if(jsonObj.result.al) {
							alert(jsonObj.result.al);
						} else {
							if($('#'+jsonObj.result.id)[0])
								$('#'+jsonObj.result.id).html(jsonObj.result.html);
							var jsonSurvey = {'errorNo': 0, 'html': jsonObj.result.popup};
							oAjaxLoading.remove();
							if(jsonObj.result.popup) {
								if(postData.afterRespose) {
									postData.afterRespose(jsonSurvey);
								}
								oBox.show(jsonSurvey);
							}
						}
					} else {
						alert( "Hiá»‡n táº¡i há»‡ thá»‘ng Ä‘ang bá»‹ quÃ¡ táº£i, vui lÃ²ng quay láº¡i sau!" );
					}
				} else if(jsonObj.popup) {
					var jsonSurvey = {'errorNo': 0, 'html': jsonObj.popup};
					oAjaxLoading.remove();
					oBox.show(jsonSurvey);
				}
			},
			dataType: "json"
		});
	return false;
}

/**
postData = {
	ajax_type:"block", // "module"
	block_name: "thu_vien",
	prev_id:,
	prev_url:
	prev_hide: , //function
	prev_show: , //function
	next_id:
	next_url:
	next_hide: , //function
	next_show: , //function
	current_id:
	current_url:
	download_id:,
	download_url:,
	img_id:
	img_url:
	isFirst:
	isDirect: // { -1: Prev,  	 0: Current, 		1:Next}
	width:
	height:
	top:
	isPostPaging:
	...
}
Ex: viewThumbnail({literal}{{/literal}ajax_type:'{block}',block_name:'{...}',prev_id:'{...}',prev_url:'{...}',prev_hide:{function_hide},prev_show:{function_show},next_id:'{...}',next_url:'{...}',next_hide:{function_hide},next_show:{function_show},current_id:'{...}',current_url:'{...}'{literal}}{/literal}, url, e, width, funcError)
*/
function bindResponse(postData, url, e, funcError, jsonObj) {
	var prevData = cloneObject(postData);
	prevData.isFirst = false;
	prevData.prev_url = jsonObj.prev_url;
	prevData.next_url = url;
	prevData.isDirect = - 1;
	var nextData = cloneObject(postData);
	nextData.isFirst = false;
	nextData.isDirect = 1;
	nextData.next_url = jsonObj.next_url;
	nextData.prev_url = url;
	if(prevData.prev_url == '') {
		prevData.prev_hide(prevData);
	} else {
		prevData.prev_show(prevData);

		var prev = $("#"+postData.prev_id);
		if(prev[0]) {
			prev[0].onclick = function(event) {
				viewThumbnail(prevData, prevData.prev_url, event, funcError);
				return false;
			}
		}		
	}
	
	if(nextData.next_url == '') {
		nextData.next_hide(nextData);
	} else {
		nextData.next_show(nextData);

		var next = $("#"+postData.next_id);
		if(next[0]) {
			next[0].onclick = function(event) {
				viewThumbnail(nextData, nextData.next_url, event, funcError);
				return false;
			}
		}		
	}
}

function empty_function() {
}

function viewThumbnail(postData, url, e, funcError){
	stopWindowEvent(e);
	activeEventAjax();
	if(!url || url == null || url == '') {
		alert("URL not found");
		return false;
	}
	if(typeof(postData.prev_url) == "undefined")
		postData.prev_url = '';
	if(typeof(postData.prev_hide) == "undefined")
		postData.prev_hide = empty_function;
	if(typeof(postData.prev_show) == "undefined")
		postData.prev_show = empty_function;
	if(typeof(postData.next_url) == "undefined")
		postData.next_url = '';
	if(typeof(postData.next_hide) == "undefined")
		postData.next_hide = empty_function;
	if(typeof(postData.next_show) == "undefined")
		postData.next_show = empty_function;
	if(typeof(postData.id_prefix) == "undefined")
		postData.id_prefix = 'thumbnail';
	if(typeof(postData.width) == "undefined")
		postData.width = '700';
	if(typeof(postData.height) == "undefined")
		postData.height = '580';
	if(typeof(postData.top) == "undefined")
		postData.top = 130;
	if(typeof(postData.spaceTop) == "undefined")
		postData.spaceTop = 120;
	if(typeof(postData.isFirst) == "undefined")
		postData.isFirst = true;
	if(typeof(postData.isDirect) == "undefined")
		postData.isDirect = 1;

	//vuna add - start
	if(typeof(postData.rating_html) == "undefined")
		postData.rating_html = '';
	//vuna add - end

	if( postData.isFirst ) {
		var oBox = new JThickBox({
			sPrefix: postData.id_prefix,
			nTop: postData.top,
			nHeight: postData.height,
			nWidth: postData.width,
			nSpaceTop:postData.spaceTop,
			oOverlay: {id:'_overlay', bShow: true},
			oClose: {id:'_close', bShow: true},
			bSimple: false,
			bCheckError: true
		});
	}

	var request = $.ajax({
			type: "POST",
			url: url,
			data: 'json='+objToString(postData),
			success: function(jsonObj, status) {
				try {
					if( jsonObj.debug ) {
						$(jsonObj.debug).appendTo("body");
					}
					if( typeof(funcError) == 'function' && funcError(jsonObj) == true) {
						return;
					}
					oAjaxLoading.remove();
					if( postData.isFirst ) {
						postData.isFirst = false;
						oBox.show(jsonObj);
					}
					$("#"+postData.current_id).attr("href", jsonObj.result.current_url);
					$("#"+postData.download_id).attr("href", jsonObj.result.download_url);

					$("#"+postData.img_id).attr("src", jsonObj.result.img_url);

					//vuna add - start
					var oRating = $("#"+postData.rating_id);
					if( oRating ) {
						oRating.html( jsonObj.result.rating_html );
					}
					//vuna add - end
					if(typeof(postData.afterRespose) == 'function')
						postData.afterRespose(jsonObj, postData);
					bindResponse(postData, url, e, funcError, jsonObj.result);
					if(jsonObj.result.js) {
						eval(jsonObj.result.js);
					}
				}catch(ex) {}
			},
			dataType: "json"
		});
	return false;
}


/**
postData: {
	ajax_type:"block", // "module"
	block_name: "comm",
	func: ,
	capcha_name:,
	send_name:,
	text_name:,
	max_len:,
}
*/
function post_comment(postData, url, e, funcError){
	stopWindowEvent(e);
	activeEventAjax();
	postData.post_comment = 1;

	var capcha = $('#'+postData.capcha_name);
	var sendname = $('#'+postData.send_name);
	var textname = $('#'+postData.text_name);
	postData.capcha_name = capcha.val();
	postData.send_name = sendname.val();
	postData.text_name = textname.val().substr(0, postData.max_len);
	if( sendname[0] && postData.send_name == '') {
		alert(COMMENT_SENDER);
		sendname.focus();
		return false;
	}
	if( textname[0] && postData.text_name == '') {
		alert(COMMENT_TEXT);
		textname.focus();
		return false;
	}
	if(!postData.capcha_name || postData.capcha_name.length < 4) {
		alert(COMMENT_CAPCHA);
		capcha.focus();
		return false;
	}
	var request = $.ajax({
			type: "POST",
			url: url,
			data: 'json='+objToString(postData),
			success: function(jsonObj, status) {
				if( jsonObj.debug ) {
					$(jsonObj.debug).appendTo("body");
				}
				if( typeof(funcError) == 'function' && funcError(jsonObj) == true) {
					return;
				}
				if( typeof(postData.func) == "function" ) {
					postData.func(jsonObj);
				}
				if( jsonObj.id && jsonObj.html ) {
					try{
						if($('#'+jsonObj.id)[0])
							$('#'+jsonObj.id).html(jsonObj.html);
						if( jsonObj.js ) {
							eval(jsonObj.js);
						}
						if(!jsonObj.capcha) {
							$("#"+jsonObj.error_id).css({display:''});
						} else {
							$("#capcha_name").val('');
							$("#send_name").val('');
							$("#text_name").val('');
							$("#"+jsonObj[i].error_id).css({display:'none'});
						}
						if(jsonObj.url) {
							$("#"+jsonObj.img).attr("src", jsonObj.url);
						}
					}catch(ex){}
				} else {
					for( var i = 0; i < jsonObj.length; i++ ) {
						try{
							if($('#'+jsonObj[i].id)[0])
								$('#'+jsonObj[i].id).html(jsonObj[i].html);
							if( jsonObj[i].js) {
								eval(jsonObj[i].js);
							}
							if(!jsonObj[i].capcha) {
								$("#"+jsonObj[i].error_id).css({display:''});
							} else {
								$("#capcha_name").val('');
								$("#send_name").val('');
								$("#text_name").val('');
								$("#"+jsonObj[i].error_id).css({display:'none'});
							}
							if(jsonObj[i].url) {
								$("#"+jsonObj[i].img).attr("src", jsonObj[i].url);
							}
						}catch(ex){alert(ex.message);}
					}
				}
			},
			dataType: "json"
		});
	return false;
}


var over_mouse_rating = [];
function rating_mouse_update(ul, nStar, index, isOver, e){
	var i = 0;
	ul = $('#'+ul)[0];
	if( typeof(ul.mouse_over) == 'undefined' ) {
		ul.mouse_over = [];
		for(i=0; i < nStar; i++) {
			ul.mouse_over[i] = false;
		}
		i = 0;
		ul.li = ul.childNodes[i];
		while( ul.li.nodeName != "LI" ) {
			ul.li = ul.childNodes[++i];
		}
		ul.li._width = ul.li.style.width;
	}
	ul.mouse_over[index] = isOver;
	var _is_over = false;
	for( i=0; i<ul.mouse_over.length;i++ ) {
		if(ul.mouse_over[i] == true)
			_is_over = true;
	}
	if(_is_over == false) {
		ul.li.style.width = ul.li._width;
	} else {
		ul.li.style.width = '0%';
	}
	return false;
}

var is_rating_timeup = {};
/**
postData: {
	ajax_type:"module", // "block"
	block_name:"news", // "block"
	...
}
*/
// rating_json('unit_longnews','',, event, funcErrorRespons)
function rating_json(postData, url, isRate, e, funcError) {
	stopWindowEvent(e);
	activeEventAjax();
	if(typeof(is_rating_timeup[url]) == "undefined") is_rating_timeup[url] = false;
	if(is_rating_timeup[url] || isRate) {
		alert('Bạn đã bình chọn rồi.');
		return false;
	}
	var request = $.ajax({
			type: "POST",
			url: url,
			data: 'json='+objToString(postData),
			error: function(xhr, status, e){
				oAjaxLoading.remove();
				alert(SYSTEM_OVERLOAD);
			},
			success: function(jsonObj, status) {
				if( jsonObj.debug ) {
					$(jsonObj.debug).appendTo("body");
				}
				if( typeof(funcError) == 'function' && funcError(jsonObj) == true) {
					return;
				}
				if( jsonObj.html ) {
					try{
						$("#"+postData.id).html(jsonObj.html);
						if( jsonObj.js ) {
							eval(jsonObj.js);
						}
						//alert('Cảm ơn bạn đã bình chọn.');
					}catch(ex){}
				}
				is_rating_timeup[url] = true;
			},
			dataType: "json"
		});
	return false;
}





/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tooltip
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// <a onmouseover="ddrivetip(text, width);" onmouseout="hideddrivetip();" href=""></a>
var offsetfromcursorX=-150 //Customize x offset of tooltip
var offsetfromcursorY=15 //Customize y offset of tooltip

var offsetdivfrompointerX=1 //Customize x offset of tooltip DIV relative to pointer image
var offsetdivfrompointerY=1 //Customize y offset of tooltip DIV relative to pointer image. Tip: Set it to (height_of_pointer_image-1).

var ie=document.all
var ns6=document.getElementById && !document.all
var enabletip=false

function ietruebody() {
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}

var tipobj = null;

var textTips = [
		{'html':'___CONTENT___', 'width':'372px', 'background':'#FFFFFF'},
		{'html':'<div class="box-tip"><div class="box-top"><div class="box-bt">___CONTENT___</div></div></div>', 'width':'auto', 'background':'#FFFFFF'}
	];

function addTemplate(tpl){
	if(!tpl) return;
	if( tpl.constructor == Array )
		textTips = tpl
	else {
		if(tpl.constructor == String)
			tpl = {'html':tpl, 'width':'auto'};
		textTips[textTips.length] = tpl;
	}
}
//
function ietruebody(){
	if(!window.__initedTooltip) return false;
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body;
}
/*
Example:
<a href="..." onmouseover="ddrivetip('Hello', 0)"; onmouseout="hideddrivetip()">...</a>
<a href="..." onmouseover="ddrivetip($(this).next().innerHTML, 0)"; onmouseout="hideddrivetip()">...</a><p style="display:none">
	fsad fgsd g sdghlkg hjjh
</p>
*/
function ddrivetip(thetext, type, thecolor, thewidth ){
	if(!window.__initedTooltip) return false;
	if(!tipobj)
		tipobj = $('#dhtmltooltip')[0];
	if(!type) type = 0;
	if( type >= textTips.length ) type = textTips.length-1;
	if (ns6||ie){
		if (typeof thewidth!="undefined") {
			if(thewidth != "auto") thewidth += "px";
			tipobj.style.width = thewidth;
		} else {
			tipobj.style.width = textTips[type].width;
		}
		if (typeof thecolor!="undefined" && thecolor!="")
			tipobj.style.backgroundColor = thecolor;
		else
			tipobj.style.backgroundColor = textTips[type].background;
		var html = textTips[type].html.replace( /___CONTENT___/, thetext.replace(/^\s{1,}|\s{1,}$/g, ''));
		tipobj.innerHTML = html;
		enabletip = true;
		tipobj.style.visibility="visible";
		tipobj.style.display="";
		return false;
	}
}

function positiontip(e){
	if(!window.__initedTooltip) return false;
	if(!tipobj)
		tipobj = $('#dhtmltooltip')[0];
	if (enabletip){
		var nondefaultpos=false;
		var curX=(ns6)?e.pageX : event.clientX+ietruebody().scrollLeft;
		var curY=(ns6)?e.pageY : event.clientY+ietruebody().scrollTop;
		//Find out how close the mouse is to the corner of the window
		var winwidth=ie&&!window.opera? ietruebody().clientWidth : window.innerWidth-20;
		var winheight=ie&&!window.opera? ietruebody().clientHeight : window.innerHeight-20;

		var rightedge=ie&&!window.opera? winwidth-event.clientX-offsetfromcursorX : winwidth-e.clientX-offsetfromcursorX;
		var bottomedge=ie&&!window.opera? winheight-event.clientY-offsetfromcursorY : winheight-e.clientY-offsetfromcursorY;

		var leftedge=(offsetfromcursorX<0)? offsetfromcursorX*(-1) : -1000;

		//if the horizontal distance isn't enough to accomodate the width of the context menu
		if ( rightedge<tipobj.offsetWidth){
			//move the horizontal position of the menu to the left by it's width
			tipobj.style.left=curX-tipobj.offsetWidth+"px";
			nondefaultpos=true
		}
		else if (curX<leftedge)
			tipobj.style.left="5px";			
		else{
			//position the horizontal position of the menu where the mouse is positioned -130+
			tipobj.style.left= curX+offsetfromcursorX-offsetdivfrompointerX+"px";			
		}
		//same concept with the vertical position
		if (bottomedge<tipobj.offsetHeight){
			tipobj.style.top=curY-tipobj.offsetHeight-offsetfromcursorY+"px";
			nondefaultpos=true;
		}
		else{
			tipobj.style.top= curY+offsetfromcursorY+offsetdivfrompointerY+"px";
		}
		tipobj.style.visibility="visible";
		tipobj.style.display="";
	}
}

function hideddrivetip() {
	if(!window.__initedTooltip) return false;
	if(!tipobj)
		tipobj = $('#dhtmltooltip')[0];
	if (ns6||ie){
		enabletip=false
		tipobj.style.visibility="hidden";		
		tipobj.style.left="-1000px";
		tipobj.style.backgroundColor='';
		tipobj.style.width='';
	}
}

if( typeof(window.__initedTooltip) == "undefined" )
	window.__initedTooltip = false;
$(window).ready(function(){
	if(window.__initedTooltip) return;
	jQuery('<div id="dhtmltooltip" style="display:none"></div>').appendTo("body");
	tipobj = $("#dhtmltooltip")[0];
	window.__initedTooltip = true;
	$(document).bind("mousemove", positiontip);
	$(window).bind("unload", function(){
		$(document).unbind("mousemove", positiontip);
	});
});

//Open popup
function openWindow(filename, winname, width, height, feature) {
	var features, top, left;
	var reOpera = /opera/i;
	var winnameRequired = ((navigator.appName == "Netscape" && parseInt(navigator.appVersion) == 4) || reOpera.test(navigator.userAgent));

	left = (window.screen.width - width) / 2;
	top = (window.screen.height - height) / 2;
	if( width ) width = 'width='+width+', ';
	else width = '';
	if(height) height = "height=" + height + ", ";
	else height = '';
	if(feature == '')
		features = width + height + "top=" + top + ",left=" + left + ",status=0,location=0";
	else
		features = width + height + "top=" + top + ",left=" + left + "," + feature;
	// if(!winnameRequired) winname = "";
	var newwindow = window.top.open(filename,winname,features);
	if( newwindow )	newwindow.focus();
	return newwindow;
}

function PopUpSong(zing_url) {
    if (window.ActiveXObject) {
        // openWindow("http://mp3.zing.vn/popupsong.php?zing=" + zing, "popupsong", 575, 378, "");
        openWindow(zing_url, "popupsong", 575, 378, "");
    } else {
        // openWindow("http://mp3.zing.vn/popupsong.php?zing=" + zing, "popupsong", 575, 378, "");
        openWindow(zing_url, "popupsong", 575, 378, "");
    }
}


function img_view_full_size(url, width, height){
	if(!width) width = 1024;
	if(!height) height = 768;
	w = window.open('_blank', 'view_image', 'width='+width+', height='+height+', directories=no, status=no, toolbar=no, location=no, resizable=no');// , fullscreen=true
	w.document.write('<div style="overflow:auto; width:100%; height:100%; margin:0px;"><img src="'+url+'"></div>');
	w.document.close();
	b = w.document.getElementsByTagName('body')[0];
	b.style.padding='0px';
	b.style.margin='0px';
}

// img_view_full_size("http://img.zing.vn/volamnew/images/modules/hinhanh/1024x768/desktop.jpg");