/**
 * @author huy.pham
 */

/*
 * Utilities helper functions
 */
function getHost() {
	var url = document.location.toString();
	var end;
	for (end = 'http://'.length; url.charAt(end) != '/'; end++) {
		if (end == url.length - 1) {
			break;
		}
	}
	return url.substring(0, end, '/');
}

/*
 * Helper functions for Ajax loading request
 */
function renderAjaxLoadingRequest(delayTime) {
	var delay = delayTime?delayTime:500;
	document.body['ajaxLoadingRenderRequestHanle'] = setTimeout('renderAjaxLoading();', delay);
}

function renderAjaxLoadingStop() {
	if (document.body['ajaxLoadingRenderRequestHanle']) {
		clearTimeout(document.body['ajaxLoadingRenderRequestHanle']);	
	}
	document.getElementById('spinner').style.display='none';
	document.body.className = document.body['preClassName'];
}

function renderAjaxLoading() {
	var backgroundElement = document.getElementById("spinner");  
    var clientWidth;
    var clientHeight;
    if (navigator.userAgent.indexOf("MSIE") > -1) 
	{
//case InternetExplorer:
			clientWidth = document.documentElement.clientWidth;
			clientHeight = document.documentElement.clientHeight;
	}
	else if (navigator.userAgent.indexOf("Safari") > -1)
	{
//case Safari:
			clientWidth = window.innerWidth;
			clientHeight = window.innerHeight;
	}
	else if (navigator.userAgent.indexOf("Opera") > -1)
	{
//case Opera:
			clientWidth = Math.min(window.innerWidth, document.body.clientWidth);
			clientHeight = Math.min(window.innerHeight, document.body.clientHeight);
	}
	else
	{
//default: Firefox, etc.
			clientWidth = Math.min(window.innerWidth, document.documentElement.clientWidth);
			clientHeight = Math.min(window.innerHeight, document.documentElement.clientHeight);
	}
	backgroundElement.style.width = ( Math.max(
																		Math.max(document.documentElement.scrollWidth, document.body.scrollWidth), 
																		clientWidth) - 25 ) + 'px';
	backgroundElement.style.height = ( Math.max(
																		Math.max(document.documentElement.scrollHeight, document.body.scrollHeight), 
																		clientHeight) - 25 ) + 'px';
	backgroundElement.style.zIndex = 10000;

	//Show Blending
	document.getElementById('spinner').style.display='block';
	document.body['preClassName'] = document.body.className;
	document.body.className = document.body["preClassName"] + ' blending';
}

/*
 * Helper functions for sorted table rendering
 * see SortPanel & SortPanelList Ruby class
 */
function gridResort(table, column, _this){
	var form = (document.all?event.srcElement:_this).form;
	var sorted_column = table + '[sorted_column]';
	var pre_sorted_column = form[sorted_column].value.toString().replace(/^\s+|\s+$/g, '').toLowerCase();
	column = column.toLowerCase();
	form[sorted_column].value = column;
	//Compute and set the sorted type
	var sorted_type = table + '[sorted_type]';
	var next_sorted_type = 'inc';
	if (column == pre_sorted_column && 'inc' == form[sorted_type].value.toString().replace(/^\s+|\s+$/g, '').toLowerCase()) {
		next_sorted_type = 'desc';
	}
	form[sorted_type].value = next_sorted_type;
	return true;
}

/*
  Helper functions for validating length of text inputed for textarea
*/
function textCounter(caller, e, maxlimit, onCount) {
	var field = document.all?e.srcElement:caller;
	var testSize = field.value.length;

	if (window.clipboardData) { //IE could access clipboard
		if (e.type=='paste') {
			var clipTxt = window.clipboardData.getData("Text");
			if (clipTxt != null) {
				testSize += clipTxt.length;
			}
		}
	} else { //FF could not access clipboard so we will work arround
		if(testSize <= (maxlimit-1))
			field['_preValue'] = field.value;
		if(testSize > maxlimit)
			field.value = field['_preValue'];		
	}

	if(onCount!=null) {
		var counter = maxlimit - field.value.length;
		var launchStr = onCount+ '(' +counter+ ');';
		eval(launchStr);
	}
	if (testSize > (maxlimit-1)) {
		return stopKeyPress(e);
	}
	return true;
}

function textAreaLimit(element, limit, callBack) {
	var inputEvents = ['keypress', 'keyup', 'keydown', 'paste', 'input'];
	for(var i=0; i<inputEvents.length; i++) {
		bindEvent(element, inputEvents[i], function(e) {return textCounter(this, e, limit, callBack);});
	}
}

function bindEvent(element, event, callback) {
	if (document.all) { //IE
		element.attachEvent('on' + event, callback);
	} else { //FF
		element.addEventListener(event, callback, true);
	}
}

function stopKeyPress(e){
	var keyCode = e.keyCode ? e.keyCode : e.which;
	var block = !(keyCode>=33 && keyCode<=40) && !e.ctrlKey && keyCode!=8 && keyCode!=46;
	//If not operation keys (paste, copy...) skip this event
	block |= !keyCode && e.type=='paste';
	if (block) {
		if (e.stopPropagation) {
			e.returnValue = false;
			e.cancel = true;
			e.stopPropagation();
			e.preventDefault();
		}
		return false;
	}
	return true;
}

/* use for icon loading ajax*/
function initializeSpinner() {
	var backgroundElement = document.getElementById("spinner");  
    var clientWidth;
    var clientHeight;
	if (navigator.userAgent.indexOf("MSIE") > -1){
	        //case InternetExplorer:
			clientWidth = document.documentElement.clientWidth;
			clientHeight = document.documentElement.clientHeight;
	}else if (navigator.userAgent.indexOf("Safari") > -1){
	        //case Safari:
			clientWidth = window.innerWidth;
			clientHeight = window.innerHeight;
	}else if (navigator.userAgent.indexOf("Opera") > -1){
	        //case Opera:
			clientWidth = Math.min(window.innerWidth, document.body.clientWidth);
			clientHeight = Math.min(window.innerHeight, document.body.clientHeight);
	}else{
	        //default: Firefox, etc.
			clientWidth = Math.min(window.innerWidth, document.documentElement.clientWidth);
			clientHeight = Math.min(window.innerHeight, document.documentElement.clientHeight);
	}
	backgroundElement.style.width = ( Math.max(
												Math.max(document.documentElement.scrollWidth, document.body.scrollWidth), 
												clientWidth) ) + 'px';
	backgroundElement.style.height = ( Math.max(
												Math.max(document.documentElement.scrollHeight, document.body.scrollHeight), 
												clientHeight) ) + 'px';
	backgroundElement.style.zIndex = 10000;
	backgroundElement.className = "modalBackground";
}
var _spinner;
function showSpinner(second) {
	_spinner = setTimeout("Element.show('spinner');", second);
}
function hideSpinner() {
	clearTimeout(_spinner);
	Element.hide('spinner');
}

function isNumberKey(evt) {

   var charCode = (window.event) ? window.event.keyCode : (evt) ? evt.which : -1;
   if (charCode == -1) return true; 	   
   if (charCode == 46)
      return true;
   if (charCode > 31 && (charCode < 48 || charCode > 57))
      return false;

   return true;
}

function goPage(url) {
	window.location=url;
}

function popupPhoto(url){
	var w = window.open('/photo.htm?' + url, 'IMAGE', 'menubar=no,width=200,height=200,toolbar=no,resizable=1,scrollbars=0'); 
	w.focus();
}

function formatCurrency(num, unit, delimiter) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num)) num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10) 
		cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+(delimiter?delimiter:'')+
	
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + (unit?unit:'') + num + '.' + cents);
}

function validate_creditcard(e) {
	var keynum;
	var keychar;
	var numcheck;

	if(window.event) // IE
	  {
	  keynum = e.keyCode;
	  }
	else if(e.which) // Netscape/Firefox/Opera
	  {
	  keynum = e.which;
	  }
	keychar = String.fromCharCode(keynum);
	numcheck = /\d/;
	return numcheck.test(keychar);
}

function fckeditor_count(element_id, method, max_length) {
	var num_chars_left;
	var fckeditor_html;

	oEditor = FCKeditorAPI.GetInstance(element_id);
	fckeditor_html = oEditor.GetXHTML();
	num_chars_left = max_length - fckeditor_html.length;
	$(method).innerHTML = num_chars_left + '';
}
