/**
* @package script
* @Author: thuyqt <thuy.tranquan@gmail.com>
* @Copyright (C) 2005-2008 Lulo
* @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( 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;
}

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;
		var url = '';
		
		// get path to image
		if( a.length == 2 && typeof(a[1]) == 'string' ) {
			url = a[1];
		}
		else if( typeof(a[0]) == 'object' ) {
			a = a[0];
		}
		
		for( i=0; i < a.length; i++ )
		{
			if( a[i] && a[i].indexOf("#") != 0 )
			{
				src = a[i];
				if( url != null )
					src = url + a[i];
				
				d.MM_p[j] = new Image;
				d.MM_p[j].src = src;
				d.MM_p[j].onload = function() {};
				j++;
			}
		}
	}
}

// open new window with no menu
function popupWindow( url, width, height, arg, full )
{		
	var size = getPageSize();
	if( !width ) width = 700;
	if( !height ) height = 450;
	
	width 	= width + 30;
	height 	= height + 20;
	
	var left 	= parseInt(size[2] - width)/2;
	var top 	= parseInt(size[3] - 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;
	}
}

// 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 in array )
	{
		if( value == array[i] ) {
			return true;
		}
	}
	return false;
}

function array_pop( array, value ) {
	var retval = new Array();
	
	for( var i in array )
	{
		if( array[i] != value ) {
			retval.push( array[i] );
		}
	}
	
	return retval;
}

function parseValue(value) {
	if( isNaN(parseFloat(value)) ) {
		return 0.00;
	}
	return parseFloat(value);
}

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 validYMD( strInput, space ) {	
	if( !space ) {
		space = "-";
	}
	var dateFormat = /^\d{4}\-\d{2}\-\d{2}/;
	
	return dateFormat.test(strInput);
}

function validDMY( dateStr, space ) {	
	if( !space ) {
		space = "-";
	}
	var dateFormat = /^\d{2}\-\d{2}\-\d{4}/;
	
	return dateFormat.test(dateStr);
}

function validPhone( phoneStr, empty ) {
	if( typeof(empty) != 'undefined' && empty && phoneStr.length == 0 ) {
		return true;
	}
	
	var format = /^[0-9\-\(\)\. ]+$/;
	if( !format.test(phoneStr) || phoneStr.length < 7 )
		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);
}

function isEmpty( str ) {
	if( trim(str) == 0 || str == '' || str == '0' || !str ) {
		return true;
	}
	
	return false;
}

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;
			}
		}
	}
}

// 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 );
	}
}

// check input value is float or interger
function blockNonNumbers( obj, e, allowDecimal, allowFormat ) {
	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;
	var isFormat = allowFormat ? ( (keychar == '.' || keychar == ',') && (obj.value.length > 0) ) : false;
	if( (keychar == '0') && (obj.value.length == 0) ) {
		return false;
	}
														 
	reg = /\d/;
	return ( isFirstD || isFormat || reg.test(keychar) );
}

// convert data on From to Query String
function convertForm( formId, remove ) {
	var oForm;
	if( typeof(formId) == 'object' ) {
		oForm = formId;
	}
	else if( typeof(formId) == 'string' ) {
		oForm = eval('document.'+ formId);
		if( !oForm ) {
			oForm = (getObjectById(formId) || document.forms[formId]);
		}
	}
	if( !oForm ) return false;
	
	if( typeof(remove) == 'undefined' ) remove = [];
	
	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)
		{
			// continue with remove
			if( typeof(remove) == 'string' ) {
				if( remove == oName ) {
					continue;
				}
			}
			else if( typeof(remove) == 'object' ) {
				if( in_array(oName, remove) ) {
					continue;
				}
			}
			// --------------- //
			
			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;
}
// convert data on From to Array[key]=[value]
function convertFormToArray( formId, remove ) {
	var oForm;
	if( typeof(formId) == 'object' ) {
		oForm = formId;
	}
	else if( typeof(formId) == 'string' ) {
		oForm = eval('document.'+ formId);
		if( !oForm ) {
			oForm = (getObjectById(formId) || document.forms[formId]);
		}
	}
	if( !oForm ) return false;
	
	if( typeof(remove) == 'undefined' ) remove = [];
	
	var oElement, oName, oValue, oDisabled;
	var hasSubmit = false;
	var _aFormData = {};
	
	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)
		{
			// continue with remove
			if( typeof(remove) == 'string' ) {
				if( remove == oName ) {
					continue;
				}
			}
			else if( typeof(remove) == 'object' ) {
				if( in_array(oName, remove) ) {
					continue;
				}
			}
			// --------------- //
			
			switch (oElement.type) {
				case 'select-one':
				case 'select-multiple':
					var tmp = [];
					for(var j=0; j<oElement.options.length; j++){
						if(oElement.options[j].selected){
							if(window.ActiveXObject) {
								tmp.push( oElement.options[j].attributes['value'].specified?oElement.options[j].value:oElement.options[j].text );
							}
							else {
								tmp.push( oElement.options[j].hasAttribute('value')?oElement.options[j].value:oElement.options[j].text );
							}
						}
					}
					if( oName.indexOf('[]') < 0 ) {
						_aFormData[oName] = tmp.toString();
					}
					else {
						_aFormData[oName] = tmp;
					}
					break;
				case 'radio':
				case 'checkbox':
					if(oElement.checked) {
						_aFormData[oName] = 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) {
						_aFormData[oName] = oValue;
						hasSubmit = true;
					}
					break;
				default:
					_aFormData[oName] = oValue;
					break;
			}
		}
	}

	_isFormSubmit = true;
	
	return _aFormData;
}

function get_form_element_multiple( formId, elName, isArray )
{
	var oForm;
	if( typeof(formId) == 'object' ) {
		oForm = formId;
	}
	else if( typeof(formId) == 'string' ) {
		oForm = eval('document.'+ formId);
		if( !oForm ) {
			oForm = (getObjectById(formId) || document.forms[formId]);
		}
	}
	if( !oForm ) return false;
	
	if( typeof(isArray) == 'undefined' ) isArray = true;
	if( isArray ) elName = elName +'[]';
	
	var element = false;
	for( var i=0; i < oForm.elements.length; i++ ){
		if( oForm.elements[i].name == elName && (oForm.elements[i].type == 'select-one' || oForm.elements[i].type == 'select-multiple' || oForm.elements[i].type == 'checkbox') ) {
			element = oForm.elements[i];
			break;
		}
	}
	return element;
}

var openImageDivID = 'luloOpenImage';
function openImageWin( src ) {
	disableBody( true, 'closeOpenedWin' );
	
	var html = '<img border="0" src="'+ src +'" alt="loading" align="absmiddle" />';
	
	var imgPreloader = new Image();
	imgPreloader.src = src;
	imgPreloader.onload = function() {
		viewOpenImage(html, this.width, this.height);
		imgPreloader.onload = function() {};	//	clear onLoad, IE behaves irratically with animated gifs otherwise
	};
	
	// for IE
	if( imgPreloader.complete ) {
		viewOpenImage(html, imgPreloader.width, imgPreloader.height);
	}
	
	return false;
}
function viewOpenImage(html, width, height, callback) {
	var container = $('#'+openImageDivID);
	if( !container.hasClass('absolute') ) {
		container = $('<div/>').addClass('absolute').attr('id', openImageDivID);
		$(document.body).append(container);
	}
	
	var pWidth = $(document.body).innerWidth();
	var pHeight = $(document.body).innerHeight();
	
	var left 	= (pWidth - width) / 2;
	var top 	= (pHeight - height) / 2 - 10;
	
	left 	= (left < 0)? 1 : left;
	top 	= (top < 0)? 3 : top;
	
	var html = '<a style="position:absolute; top:0px; left:'+ (width-19) +'px; z-index:1000; background-color:#FFFFFF; padding:3px; filter:alpha(opacity=80); -moz-opacity:0.8; opacity: 0.8; border-left: 1px solid #666; border-bottom: 1px solid #666;"'
	+ ' href="javascript:closeOpenedWin()" title="close">'
	+ '<img border="0" src="/images/icon_close.gif" />'
	+ '</a>'
	+ html
	;
	container.html(html);
	container.css({ top: top +'px', left: left +'px', width: width +'px', height: height +'px' });
	container.show('slow', callback? callback : null);
}
function closeOpenedWin() {
	var container = $('#'+openImageDivID);
	if( container.hasClass('absolute') ) {
		container.hide('slow');
	}
	disableBody( false );
}

var global_page_size = null;
function getPageSize()
{
	if( global_page_size != null ) {
		return global_page_size;
	}
	
	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)
	
	// set page size
	global_page_size = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
	return global_page_size;
}

function disableBody( status, funcName ) {
	if( typeof(status) == 'undefined' ) {
		status = true;
	}
	
	var container = $('#lulo_overlay');
	if( !container.hasClass('overlay') )
	{
		var body = document.body, div = document.createElement("div");
		
		div.id = 'lulo_overlay';
		div.className = 'overlay';
		body.insertBefore( div, body.firstChild );
		
		var div = document.createElement("div");

		document.body.appendChild( div );
		container = $('#lulo_overlay');
	}
	
	if( status == true )
	{
		var pWidth = $(document.body).innerWidth();
		var pHeight = $(document.body).innerHeight();
		
		container.css({ top: 0, left: 0, width: pWidth +'px', height: pHeight +'px' });
		
		// function hide
		if( typeof(funcName) != 'undefined' ) {
			container.click(function() { eval( funcName +'()'); });
		}
		container.show('slow');
	}
	else
	{
//		container.css({ top: 0, left: 0, width: '1px', height: '1px' });
		
		container.click(function() {return true;});
		container.hide('slow');
	}
}

// swap image
function swapImage( id, hov, ext, allow )
{
	var el = getObjectById( id );
	if( el && el.src ) {
		if( !hov ) hov = 'hover';
		if( !ext ) ext = '.gif';
		if( !allow ) allow = true;
		
		var reg = new RegExp(hov, "i");
		var src = el.src;
		
		if( reg.test(el.src) ) {
			if( allow ) {
				src = el.src.replace( '_'+hov, '' );
			}
		}
		else {
			if( allow ) {
				src = el.src.replace( ext, '_'+hov+ext );
			}
		}
		preloadImages( src );
		el.src = src;
	}
}
// reset swap image
function resetSwapImg( id, hov, ext )
{
	swapImage( id, hov, ext, false );
}

// swap image
function swapImage2( id, src )
{
	var el = getObjectById( id );
	if( el && el.src ) {
		preloadImages( src );
		el.src = src;
	}
}
