/**
* thuyqt script v.1.0
* Content code
* @package script
* @Copyright (C) 2005-2008 Lulo
* @ All rights reserved
* @ thuyqt script Component is Free Software
* @ Released under GNU/GPL License : http://www.gnu.org/copyleft/gpl.html
* @version 1.0
**/

// get object by id
function getObjectById( id ) {
	var obj = null;
	
	if( document.getElementById ) {
		obj = document.getElementById( id );
	}
	else if( document.all ) {
		obj = document.all[id];
	}
	else {
		obj = document.layer[id];
	}
	
	return obj;
}
function $(id) {
	var obj = null;
	
	if( typeof(id) == 'object' ) {
		obj = id;
	}
	else if( document.getElementById ) {
		obj = document.getElementById( id );
	}
	else if( document.all ) {
		obj = document.all[id];
	}
	else {
		obj = document.layer[id];
	}
	
	return obj;
}

// show hide object
function ShowHideObject( id ) {
	var obj = getObjectById( id );
	if( obj ) {
		if( obj.style.display == 'none' ) {
			obj.style.display = '';
		}
		else {
			obj.style.display = 'none';
		}	
	}
	return;
}

// show hide object
function ShowHideObjectExtend( id, img ) {
	var obj = getObjectById( id );
	var image = eval( "document.images." + img );
	if( obj ) {
		if( obj.style.display == 'block' ) {
			obj.style.display = 'none';
			if( image ) {
				image.src = "images/expandall.png";
			}
		}
		else {
			obj.style.display = 'block';
			if( image ) {
				image.src = "images/collapseall.png";
			}
		}	
	}
	return;
}

// all checkbox of one Node will be checked or uncheck
function checkedAllNode( node, checked ) {
	if( typeof node == 'string' ) {
		node = getObjectById( node );
	}
	if( !checked ) {
		checked = false;
	}
	
	for( var i=0; i < node.childNodes.length; i++ ) {
		if( node.childNodes[i].nodeName == 'INPUT' ) {
			if( node.childNodes[i].type == 'checkbox' ) {
				node.childNodes[i].checked = checked;
			}
		}
		checkedAllNode( node.childNodes[i], checked );
	}
}

function preloadImages() {
	var d = document;
	if( d.images ) {
		if( !d.MM_p ) {
			d.MM_p = new Array();
		}
		var i, j = d.MM_p.length, a = preloadImages.arguments;
		if( a.length == 1 && typeof(a[0]) == 'object' ) {
			a = a[0];
			//alert( a.join('\n') );
		}
		for( i=0; i < a.length; i++ ) {
			if ( a[i].indexOf("#") != 0 ) {
				d.MM_p[j] = new Image;
				d.MM_p[j].src = a[i];
				d.MM_p[j].onload = function() {};
				j++;
			}
		}
	}
}

function openImageWin( src ) {
	disableBody( true );
	
	var imgPreloader = new Image();
	imgPreloader.src = src;
	imgPreloader.onload = function() {
		var width 	= imgPreloader.width;
		var height 	= imgPreloader.height;
		
		viewOpenImage(imgPreloader.src, width, height);
		
		imgPreloader.onload = function(){};	//	clear onLoad, IE behaves irratically with animated gifs otherwise
	};
	
	// for IE
	if( imgPreloader.complete ) {
		var width 	= imgPreloader.width;
		var height 	= imgPreloader.height;
		
		viewOpenImage(imgPreloader.src, width, height);
	}
	
	return false;
}
function viewOpenImage(src, width, height) {
	if( !$('luloOpenImage') ) {
		var objBody = document.getElementsByTagName("body").item(0);
		
		var objOpenImage = document.createElement("div");
		objOpenImage.id = 'luloOpenImage';
		objOpenImage.className = 'absolute';
		objOpenImage.style.display = 'none';
		objBody.appendChild(objOpenImage);
	}
	var objOpenImage = $('luloOpenImage');
	var arrayPageSize = getPageSize();
	
	var left 	= (arrayPageSize[2] - width) / 2;
	var top 	= (arrayPageSize[3] - height) / 2 - 10;
	
	left 	= (left < 0)? 1 : left;
	top 	= (top < 0)? 3 : top;
	
	objOpenImage.innerHTML = '<a style="position:absolute; top:0px; left:'+ (width-18) +'px; z-index:1000; background-color:#FFFFFF; padding:3px; filter:alpha(opacity=80); -moz-opacity:0.8; opacity: 0.8;"'
	+ ' href="javascript:closeOpenPage(\'luloOpenImage\')" title="close">'
	+ '<img border="0" src="images/icon_close.gif" />'
	+ '</a>'
	+ '<img border="0" src="'+ src +'" />'
	;
	
	objOpenImage.style.left 		= left +'px';
	objOpenImage.style.top 			= top +'px';
	objOpenImage.style.width 		= width +'px';
	objOpenImage.style.height 	= height +'px';
	
	objOpenImage.style.display = '';
	window.scroll(0, 0);
}
function closeOpenPage(id) {
	disableBody( false );
	
	var obj = (typeof(id) == 'string')? $(id) : id;
	if( obj ) {
		obj.style.display 	= 'none';
		obj.style.width 		= '1px';
		obj.style.height 		= '1px';
		obj.style.left 			= '-1000px';
		obj.style.top 			= '-1000px';
	}
}

function luloBookmarkSite( title, url ) {
	if ( document.all )
		window.external.AddFavorite(url, title);
	else if ( window.sidebar )
		window.sidebar.addPanel(title, url, "")
}

function validDMY( dateStr, space ) {	
	if( !space ) {
		space = "-";
	}
	var dateFormat = /^\d{2}\-\d{2}\-\d{4}$/;
	
	return dateFormat.test(dateStr);
}

function validPhone( phoneStr ) {
	if( phoneStr.length == 0 ) {
		return true;
	}
	
	var format = /^[0-9\-\(\)\. ]+$/;
	if( !format.test(phoneStr) || phoneStr.length < 6 )
		return false;
	
	return true;
}

// valid input email
function validEmail( emailStr ) {
	var filter = /^(\w+(?:\.\w+)*)@((?:\w+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	return filter.test(emailStr);
}

// open new window with no menu
function openNewWindow( url, width, height, arg, full ) {		
	var screenX = screen.width;
	var screenY = screen.height;
	
	if( !width )
		width 	= 600;
		
	if( !height )
		height 	= 500;
	
	width 	= width + 30;
	height 	= height + 20;
	
	var left 	= parseInt(screenX/2 - width/2);
	var top 	= parseInt(screenY/2 - height/2);
	
	var _arg = '';
	if( !full ) {
		_arg = 'status=no,toolbar=no,location=no,directories=no,menubar=no,scrollbars=yes,resizable=yes,width='+ width +',height='+ height +',top='+ top +',left='+ left;
		
		if( arg ) {
			_arg += arg;
		}
	}
	var obj = window.open( url, 'win2', _arg );	
	obj.focus();
	
	return obj;
}

// LocationLink
function locationLink( url ) {
	if( url ) {
		window.location.href = url;
	}
	else {
		window.location.href = "index.php";
	}
}

// LTrim(string) : Returns a copy of a string without leading spaces.
function ltrim(str) {
	var whitespace = new String(" \t\n\r");
	var s = new String(str);
	if (whitespace.indexOf(s.charAt(0)) != -1) {
		var j=0, i = s.length;
		while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
			j++;
		s = s.substring(j, i);
	}
	return s;
}

//RTrim(string) : Returns a copy of a string without trailing spaces.
function rtrim(str) {
	var whitespace = new String(" \t\n\r");
	var s = new String(str);
	if( whitespace.indexOf(s.charAt(s.length-1)) != -1 ) {
		var i = s.length - 1;       // Get length of string
		while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
			i--;
		s = s.substring(0, i+1);
	}
	return s;
}

// Trim(string) : Returns a copy of a string without leading or trailing spaces
function trim(str) {
	return rtrim(ltrim(str));
}

// check value in array
function in_array( value, array ) {
	if( array.length < 1 )
		return false;
	
	for( var i=0, n=array.length; i < n; i++ ) {
		if( value == array[i] ) {
			return true;
		}
	}
	return false;
}

function array_pop( array, value ) {
	var retval = new Array();
	var length = array.length;
	
	for( var i=0; i < length; i++ ) {
		if( array[i] != value ) {
			retval.push( array[i] );
		}
	}
	
	return retval;
}

function isInteger( intStr, allow ) {
	if( intStr.length == 0 && allow ) {
		return true;
	}
	
	var intFormat = /^[0-9]+$/;
	if( !intFormat.test(intStr) ) {
		return false;
	}
	return true	;
}

function isFloat( floatStr, allow ) {
	if( floatStr.length == 0 && allow ) {
		return true;
	}
	
	var floatFormat = /^[0-9\.]+$/;
	if( !floatFormat.test(floatStr) ) {
		return false;
	}
	return true	;
}

function validDateYYYYmmdd( strInput, space ) {	
	if( !space ) {
		space = "-";
	}
	var dateFormat = /^\d{4}\-\d{2}\-\d{2}$/;
	
	return dateFormat.test(strInput);
}

function copyValue( form, fieldFrom, fieldTo, always ) {
	if( typeof always == 'undefined' ) {
		always = false;
	}
	if( typeof form == 'string' ) {
		form = eval( 'document.' + form );
	}
	var srcFrom = eval( 'form.' + fieldFrom );
	var srcTo 	= eval( 'form.' + fieldTo );
	if( srcFrom && srcTo ) {
		if( always || trim(srcTo.value) == '' ) {
			srcTo.value = srcFrom.value;
		}
		else {
			if( confirm('Are you overight old value ?') ) {
				srcTo.value = srcFrom.value;
			}
		}
	}
}

// check input value is float or interger
function blockNonNumbers( obj, e, allowDecimal ) {
	var key;
	var isCtrl = false;
	var keychar;
	var reg;
		
	if( window.event ) {
		key = e.keyCode;
		isCtrl = window.event.ctrlKey
	}
	else if( e.which ) {
		key = e.which;
		isCtrl = e.ctrlKey;
	}
	
	if( isNaN(key) )
		return true;
	
	keychar = String.fromCharCode( key );
	
	// check for backspace or delete, or if Ctrl was pressed
	if (key == 8 || isCtrl ) {
		return true;
	}
		
	var isFirstD = allowDecimal ? ( (keychar == '.') && (obj.value.indexOf('.') == -1) && (obj.value.length > 0) ) : false;
	if( (keychar == '0') && (obj.value.length == 0) ) {
		return false;
	}
														 
	reg = /\d/;
	return ( isFirstD || reg.test(keychar) );
}

function convertForm( formId ) {
	var oForm;
	if( typeof formId == 'string' ) {
		oForm = (getObjectById(formId) || document.forms[formId]);
	}
	else if( typeof formId == 'object' ) {
		oForm = formId;
	}
	
	if( !oForm ) {
		return false;
	}
	
	var oElement, oName, oValue, oDisabled;
	var hasSubmit = false;
	var _sFormData = "";
	
	for( var i=0; i < oForm.elements.length; i++ ){
		oElement = oForm.elements[i];
		oDisabled = oForm.elements[i].disabled;
		oName = oForm.elements[i].name;
		oValue = oForm.elements[i].value;

		// Do not submit fields that are disabled or
		// do not have a name attribute value.
		if(!oDisabled && oName) {
			switch (oElement.type) {
				case 'select-one':
				case 'select-multiple':
					for(var j=0; j<oElement.options.length; j++){
						if(oElement.options[j].selected){
							if(window.ActiveXObject) {
								_sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oElement.options[j].attributes['value'].specified?oElement.options[j].value:oElement.options[j].text) + '&';
							}
							else {
								_sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oElement.options[j].hasAttribute('value')?oElement.options[j].value:oElement.options[j].text) + '&';
							}

						}
					}
					break;
				case 'radio':
				case 'checkbox':
					if(oElement.checked){
						_sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oValue) + '&';
					}
					break;
				case 'file':
					// stub case as XMLHttpRequest will only send the file path as a string.
				case undefined:
					// stub case for fieldset element which returns undefined.
				case 'reset':
					// stub case for input type reset button.
				case 'button':
					// stub case for input type button elements.
					break;
				case 'submit':
					if(hasSubmit == false){
						_sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oValue) + '&';
						hasSubmit = true;
					}
					break;
				default:
					_sFormData += encodeURIComponent(oName) + '=' + encodeURIComponent(oValue) + '&';
					break;
			}
		}
	}

	_isFormSubmit = true;
	_sFormData = _sFormData.substr(0, _sFormData.length - 1);
	
	return _sFormData;
}

function addOnloadEvent( funcName ) {
	if( typeof(window.addEventListener) != "undefined" )
		eval( 'window.addEventListener( "load", '+ funcName +', false )' );
	else if( typeof window.attachEvent != "undefined" ) {
		eval( 'window.attachEvent( "onload", '+ funcName +' )' );
	}
	else{
		if( window.onload != null ) {
			var oldOnload = window.onload;
			window.onload = function ( e ) {
				oldOnload( e );
				eval( funcName +'()' );
			}
		}
		else {
			eval( 'window.onload = '+ funcName +'()' );
		}
	}
}

function getPageSize() {
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}
	
	var windowWidth, windowHeight;
	
//	console.log(self.innerWidth);
//	console.log(document.documentElement.clientWidth);

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
	
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

//	console.log("xScroll " + xScroll)
//	console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
//	console.log("pageWidth " + pageWidth)

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}

function disableBody( status ) {
	if( typeof(status) == 'undefined' ) {
		status = true;
	}
	
	if( !$('lulo_overlay') ) {
		var objBody = document.getElementsByTagName("body").item(0);
		
		var objOverlay = document.createElement("div");
		objOverlay.id = 'lulo_overlay';
		objOverlay.className = 'overlay';
		objOverlay.style.display = 'none';
		objBody.appendChild(objOverlay);
	}
	
	var objOverlay = $('lulo_overlay');
	
	if( status == true ) {
		var arrayPageSize = getPageSize();
		
		objOverlay.style.width = arrayPageSize[0] +'px';
		objOverlay.style.height = arrayPageSize[1] +'px';
		
		objOverlay.style.display = 'block';
	}
	else {
		objOverlay.style.display = 'none';
		
		objOverlay.style.width = '0px';
		objOverlay.style.height = '0px';
	}
}

function findElementPosX(el) {
	curleft = 0;
	if (el.offsetParent) {
		while (el.offsetParent) {
			curleft += el.offsetLeft;
			el = el.offsetParent;
		}
	}//if offsetParent exists
	else if (el.x)
		curleft += el.x;
		
	return curleft;
}

function findElementPosY(el) {
	curtop = 0;
	if (el.offsetParent) {
		while (el.offsetParent) {
			curtop += el.offsetTop;
			el = el.offsetParent;
		}
	}//if offsetParent exists
	else if (el.y)
		curtop += el.y;
		
	return curtop;
}

document.getElementsByClassName = function(cl, tagName) {
	var retnode = [];
	var myclass = new RegExp('\\b'+cl+'\\b');
	var elem = this.getElementsByTagName('*');
	for( var i = 0; i < elem.length; i++ ) {
		var classes = elem[i].className;
		if( typeof(tagName) != 'undefined' ) {
			if( myclass.test(classes) && elem[i].nodeName.toLowerCase() == tagName.toLowerCase() )
				retnode.push(elem[i]);
		}
		else {
			if( myclass.test(classes) )
				retnode.push(elem[i]);
		}
	}
	return retnode;
};

function correctUrlAjax( url ) {
	var pos = url.indexOf('?');
	if( pos > -1 )
		url = 'index2.php?'+ url.substr(pos+1);
	else
		url = 'index2.php?'+ url;
	
	if( url.indexOf('no_html=') == -1 )
		url += '&no_html=1';
	if( url.indexOf('ajax=') == -1 )
		url += '&ajax=1';
	
	return url;
}

function getAjaxContent(url, id, status) {
	// status loading
	if( typeof(status) != 'undefined' )
		disableBody(true);
	else
		ajaxStatus.showStatus();
	
	var sLink = correctUrlAjax(url);	
	AjaxRequest.get(
		{
			'url': sLink,
			'onSuccess': function(req) {
				if( req.responseText ) {
					var el = (typeof(id) == 'string')? $(id) : id;
					el.innerHTML = req.responseText;
					
					// status loading
					if( status )
						disableBody(false);
					else
						ajaxStatus.hideStatus();
				}
			},
			'onError': function(req) {
				alert('Could not response data');
				// status loading
				if( status )
					disableBody(false);
				else
					ajaxStatus.hideStatus();
			}
		}
	);
	return false;
}

// change css of header
function changeCssClassHeading( cl ) {
	if( typeof(cl) != 'string' )
		cl = 'componentheading';
	
	var html = '', text = '';
	var elem = document.getElementsByClassName( cl );
	
	if( elem.length > 0 ) {
		
		var align, k = 0;
		for( var i = 0; i < elem.length; i++ ) {
			text = elem[i].innerHTML;
			
			if( trim(text) ) {
				align = '';
				if( (k % 2) == 1 )
					align = ' align="right"';
				
				html = '<table'+ align +' class="header-title" border="0" cellspacing="0" cellpadding="0"><tr>'
				+ '	<td class="h-left">&nbsp;</td>'
				+ '	<td class="h-center">'+ text +'</td>'
				+ '	<td class="h-right">&nbsp;</td>'
				+ '</tr></table>'
				;
				elem[i].className = '';
				elem[i].innerHTML = html;
				
				k++;
			}
		}
	}
}
