/**
 * @function: dynamicTextbox
 * @description: changes the width of the text input field as you type
 * @param
 *	(string) idName = id of the input field, REQUIRED
 *	(number) offsetNum = number of pixels to add to the text input field as a buffer, default to 24 pixel
 *	(number) limitNum = maximum size of the input field if wish to limit the width
 * @dependency: call this function after all the page is loaded, alternatively call it in window.onload event
 */
function dynamicTextbox(idName, offsetNum, limitNum){
	
	var targetObject = document.getElementById(idName);
	var spanId = "_dw" + idName;
	var offset = 24;
	var limit = -1;
	
	if(typeof offsetNum != 'undefined' && !isNaN(offsetNum) && offsetNum > 0){
		offset = offsetNum;
	}
	
	if(typeof limitNum != 'undefined' && !isNaN(limitNum) && limitNum > 0){
		limit = limitNum;
	}
	
	// create span and add to body
	var spanTag = document.createElement('span');
	spanTag.setAttribute('id',this.spanId);
	spanTag.setAttribute('style','position: absolute; bottom: 0px; left: 0px; visibility: hidden;');
	document.getElementsByTagName('body')[0].appendChild(spanTag);
	spanTag.className = 'noShow';
	
	// function to call when input area was changed or typed on
	var increaseSize = function(event){
		// fix event
		if (!event) event = window.event
		
		spanTag.innerHTML = targetObject.value;
		if(limit > 0 && (spanTag.offsetWidth+offset) > limit){
			targetObject.style.width = limit + "px";
		}
		else{
			targetObject.style.width = (spanTag.offsetWidth + offset) + "px";
		}
	}
	
	// add event
	var oldOnClick = targetObject.onclick;	// check if it has previous onchange event
	if(typeof oldOnClick == 'function'){
		targetObject.onclick = function(event){
			if (!event) event = window.event
			
			oldOnClick(event);
			increaseSize();
		}
	}
	else{
		targetObject.onclick = increaseSize;
	}
	
	var oldOnChange = targetObject.onchange;	// check if it has previous onchange event
	if(typeof oldOnChange == 'function'){
		targetObject.onchange = function(event){
			if (!event) event = window.event
			
			oldOnChange(event);
			increaseSize();
		}
	}
	else{
		targetObject.onchange = increaseSize;
	}
	
	var oldOnKeyDown = targetObject.onkeydown;	// check if it has previous onkeydown event
	if(typeof oldOnKeyDown == 'function'){
		targetObject.onkeydown = function(event){
			if (!event) event = window.event
			
			oldOnKeyDown(event);
			increaseSize();
		}
	}
	else{
		targetObject.onkeydown = increaseSize;
	}
}
// END of function

/**
 * miscellaneous functions
 */
 
//checks to see if the string contains the white space
//returns false if string contains the white space
function isEmpty(txt){
        if(txt == null || txt.length == 0 || typeof txt == 'undefined') //returns false if empty
                {
                        return true;
                }
        else
        {
                for(i = 0;i < txt.length; i++){
                        var c = txt.charAt(i);
                        if(c != " "){
                                return false;
                        }
                }
                return true;
        }
}


// checks to see if argument is a boolean type
// returns true if boolean else false
function isBoolean(arg){
	if(typeof arg == 'boolean'){
		return true;
	}
	else{
		return false;
	}
}


// trims whitespace 
function Trim(TRIM_VALUE){
	if(TRIM_VALUE.length < 1){
		return"";
	}
	TRIM_VALUE = RTrim(TRIM_VALUE);
	TRIM_VALUE = LTrim(TRIM_VALUE);
	if(TRIM_VALUE==""){
		return "";
	}
	else{
		return TRIM_VALUE;
	}
} //End Function


// trims the end
function RTrim(VALUE){
	var w_space = String.fromCharCode(32);
	var v_length = VALUE.length;
	var strTemp = "";
	if(v_length < 0){
		return"";
	}
	
	var iTemp = v_length -1;
		
	while(iTemp > -1){
		if(VALUE.charAt(iTemp) == w_space){
		}
		else{
			strTemp = VALUE.substring(0,iTemp +1);
			break;
		}
		iTemp = iTemp-1;
	} //End While
	return strTemp;

} //End Function


// trim beginning
function LTrim(VALUE){
	var w_space = String.fromCharCode(32);
	if(v_length < 1){
		return"";
	}
	var v_length = VALUE.length;
	var strTemp = "";
	
	var iTemp = 0;
	
	while(iTemp < v_length){
		if(VALUE.charAt(iTemp) == w_space){
		}
		else{
			strTemp = VALUE.substring(iTemp,v_length);
			break;
		}
		iTemp = iTemp + 1;
	} //End While
	return strTemp;
} //End Function


// check if given variable is an array
function isArray(a) {
    return isObject(a) && a.constructor == Array;
}


// check if given variable is an object
function isObject(a) {
    return (a && typeof a == 'object') || isFunction(a);
}

// check if given variable is a function
function isFunction(a) {
    return typeof a == 'function';
}


// function to make a name camel case by striping white space
function camelCase(text){
	if(!isEmpty(text)){
		var textFragments = Trim(text).split(/\s/);
		if(textFragments.length == 1){
			return textFragments[0];
		}
		var newText = '';
		var firstCharacter = true;
		for(var i=0; i<textFragments.length; i++){
			// beware of empty ones in front
			if(isEmpty(textFragments[i]) && firstCharacter){
				continue;
			}
			
			if(firstCharacter){
				newText += textFragments[i].toLowerCase();
				firstCharacter = false;
			}
			else{
				newText += capitalizeFirstletter(textFragments[i]);				
			}
		}
		return newText;
	}
	else{
		return '';
	}
}


// function to capitalize the first letter
function capitalizeFirstletter(text){
	if(!isEmpty(text)){
		var newText = '';
		if(text.length > 1){
			newText = text.toLowerCase();
			newText = newText.charAt(0).toUpperCase() + newText.substring(1);
		}
		else{
			newText = text.toUpperCase();
		}
		return newText;
	}
	else{
		return '';
	}
}


// function to hide element with given id
function hidethis(idname){
	try{
		document.getElementById(idname).style.display = "none";
	}
	catch(e){
		
	}
}

// function to show element with given id
function showthis(idname){
	try{
		document.getElementById(idname).style.display = "block";
	}
	catch(e){
		
	}
}

var donttype = false;
// set if can type or not
function canType(e){
	donttype = false;
	var targetobj;
	
	if(!e){
		e = window.event;
	}
		
	if (e.target){
		targetobj = e.target;
	}
	else if(e.srcElement){
		targetobj = e.srcElement;
	}
	
	if (targetobj.nodeType == 3){ // defeat Safari bug
		targetobj = targetobj.parentNode;
		issafari = true;
	}
	
	// unhighlight current object
	try{
		if(targetobj.nodeName.toLowerCase() == "input" || targetobj.nodeName.toLowerCase() == "textarea" || targetobj.nodeName.toLowerCase() == "select"){
			donttype = true;
		}
		else{
			donttype = false;
		}
	}
	catch(e){
		donttype = false;
	}
}


/*
 * Suppresses backspaces and spaces to prevent unwanted redirection of browser
 */
function suppressBackspace(e){
	
	if(!e){
		e = window.event;
	}
	
	if(document.all){
		var keycode = window.event.keyCode;
	}
	else if(document.getElementById){
		var keycode = e.which;
	}	// end of if and else statement for browsers
	
	if(keycode == 8){	// 8 is backspace
		if(donttype){
			return true;
		}
		else{
			// now suppress bubbling
			if(document.all){
				window.event.cancelBubble = true;
				window.event.returnValue = false;
			}
			return false;
		}
	}
	else if(keycode == 32){
		if(donttype){
			return true;
		}
		else{
			// now suppress bubbling
			if(document.all){
				window.event.cancelBubble = true;
				window.event.returnValue = false;
			}
			return false;
		}
	}
}

function setActiveStyleSheet(title) {
   var i, a, main;
   for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
     if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
	     if(a.getAttribute("title") == title){
		     a.disabled = false;
	     }
	     else{
		     a.disabled = true;     
	     }
     }
   }
}


function writeToNewWindow(content,windowName,width,height)
{
	newwindow2=window.open('',windowName,'height=' + height + ',width=' + width + ',resizable=1,scrollbars=1,status=1,toolbar=1,menubar=1');
	var tmp = newwindow2.document;
	tmp.write(content);
	tmp.close();
	newwindow2.focus();
}

/*
 * Name: htmlentities()
 *
 * Description:
 * converts few the symbols (&,<,>,”,“) to htmlentities and returns the string
 */
function htmlEntities(htmlText) {
	var htmlText = new String(htmlText);
	return htmlText.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/”/g,"&rdquo;").replace(/“/g,"&ldquo;").replace(/"/g,"&quot;");
}


/**
 * @ function: setOpacity
 * @ param: opacity (0~1), Dom object
 * @ return: none;
 * @ description: set the opacity of the given object
 */
function setOpacity(thisObject, opacity){
	if(document.all){
		thisObject.style.filter='alpha(opacity='+(opacity*100)+')'; 
	}
	else{
		thisObject.style.opacity = opacity;
	}
}

/*
  Augment an object by replacing its key:value pairs with those
  from other object(s), and adding pairs from other object(s) that don't
  exist in you.  Key:value pairs from later objects will
  overwrite those from earlier objects.
  
  If null is given as the initial object, a new one will be created.
  
  This mutates and returns the object passed as oSelf. The other objects are not changed.
*/
function augment (oSelf, oOther) {
    if (oSelf == null) {
        oSelf = {};
    }
    for (var i = 1; i < arguments.length; i++) {
        var o = arguments[i];
        if (typeof(o) != 'undefined' && o != null) {
            for (var j in o) {
                oSelf[j] = o[j];
            }
        }
    }
    return oSelf;
}


function assignOpacity(idname, value) {
	$(idname).setOpacity(value);
}

function getScreenSize() {
	var windowWidth = null;
	var windowheight = null;
	
	// get screen height and set it
	if (self.innerWidth)
	{       
			windowWidth = self.innerWidth;
			windowHeight = self.innerHeight;
	}
	else if (document.documentElement && document.documentElement.clientWidth)
	{
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
	}
	else if (document.body)
	{
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
	}
	return new Array(windowWidth, windowHeight);
}

function resizebgOverlay(idname){
	
	// get screen height and set it
	var screenDimension = getScreenSize();

	if(screenDimension[1] != null){
			$(idname).style.height = screenDimension[1] + "px";
			assignOpacity(idname,0.4);
			/* $("floater").style.marginTop = (windowHeight/2 -40) + "px"; */
	}
}                                                               

function resizeeditArea(idname){
	
	// get screen height and set it
	var screenDimension = getScreenSize();

	if(screenDimension[1] != null){
			/* $(idname).style.height = (screenDimension[1]-100) + "px"; */
			$(idname).style.width = (screenDimension[0]-100) + "px";
			$(idname).style.left = "50px";
			$(idname).style.top = "50px";
	}
}



/**
 * @function: getMouseCoordinates
 * @description: continuously gets mouse coordinates and also calculates the relative mouse coordinates.
 * 				 If dragging is turned on, also move the selected object
 * @param: event
 * @dependency: sets global variable value posX and posY
 * @return: none
 */
var posX = null;
var posY = null;
function getMouseCoordinates(e){

	if(!e) var e = window.event;
	
	// get absolute mouse position
	if (e.pageX || e.pageY)
	{
		posX = e.pageX;
		posY = e.pageY;
	}
	else if (e.clientX || e.clientY)
	{
		posX = e.clientX + document.body.scrollLeft;
		posY = e.clientY + document.body.scrollTop;
	}
	
	/*
	// calculate relative mouse position
	relativePosX = posX-document.getElementById("dragbox").offsetLeft;
	var newRelativePosY = posY-document.getElementById("dragbox").offsetTop;
	
	// determine if mouse is moving up or down
	if(newRelativePosY > relativePosY){
		movingUp = false;
	}
	else{
		movingUp = true;
	}

	relativePosY = newRelativePosY;

	// drag current element if need to
	if( startDraggingFlag ){
		
		currentElement.style.left = parseInt(parseInt(posX) - parseInt(nowX)) + "px"; //x-position
		currentElement.style.top = parseInt(parseInt(posY) - parseInt(nowY)) + "px"; //y-position
		
		// start swapping elements when moused over
		swapObject();

	}		
	else if(dragIt){ 		// drag property panel if dragging is true
		
		// only move in y coordinates
		propertyDivObject.style.top = parseInt(parseInt(posY) - parseInt(nowY)) + "px"; //y-position
		
	}
	*/
}
// end function



/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "-";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
    var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
    // February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
		if (i==2) {this[i] = 29;}
   } 
   return this
}


function isDate(dtStr){
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	/*
	var strMonth=dtStr.substring(0,pos1);
	var strDay=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
	*/
	var strYear=dtStr.substring(0,pos1);
	var strMonth=dtStr.substring(pos1+1,pos2);
	var strDay=dtStr.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (pos1==-1 || pos2==-1){
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		return false;
	}
	return true;
}

function parseDate(dtStr){
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	/*
	var strMonth=dtStr.substring(0,pos1);
	var strDay=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
	*/
	var strYear=dtStr.substring(0,pos1);
	var strMonth=dtStr.substring(pos1+1,pos2);
	var strDay=dtStr.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	
	var dateObj = new Date();
	dateObj.setYear(year);
	dateObj.setMonth(month-1);
	dateObj.setDate(day);
	
	return dateObj;
}


function convertToWysiwyg(formName){
	var oFCKeditor = new FCKeditor(formName);
	oFCKeditor.BasePath = wysiwygBasePath;
	oFCKeditor.ReplaceTextarea();
}
