/**
 * Resize a popup window to 90% of the screen width and to two thirds of the screen height.
 * The function also moves the window to the screen top an 5% from the left of the screen.
 */
function setWindowWidthToScreenWidth() 
{
    if (parent.parent == null)
     parent.resizeTo(screen.width * 0.9, screen.height - screen.height/3);
}

/**
 * Set/unset focus on an image.
 * The method change the src of the image with ID given by parameter "sImgID"
 * to an javascript Image with the same name. or with the same name and a digit2.
 */
function focusImage(sImgID, bFocus) {

	theImg = getObj(sImgID);

	if(bFocus)
		theImg.src = eval(sImgID).src;
	else
		theImg.src = eval(sImgID + "2").src;
}

function addStyleSheetRule(stylesheet, elementType, rules, index) {
	if(document.all)
		stylesheet.addRule(elementType, rules, index);
	else
		stylesheet.insertRule(elementType.toLowerCase() + " { " + rules + " } ", index);
}

function cssRulesToLowercase(ss) {
	if(!document.all) {
		var selectors = new Array();
		var cssTexts = new Array();
		var nrOfRules = ss.cssRules.length;
		for(var i=0; i < nrOfRules; i++) {
			selectors.push(ss.cssRules[i].selectorText);
			cssText = ss.cssRules[i].cssText;
			cssText = cssText.substring(cssText.indexOf("{")+1, cssText.indexOf("}"));
			cssTexts.push(cssText);
		}
		for(var i=0; i < nrOfRules; i++)
			ss.deleteRule(0);
		for(var i=0; i < nrOfRules; i++)
			addStyleSheetRule(ss, selectors[i].toLowerCase(), cssTexts[i], 0);
	}
}

function enableButton(imgId, bEnable) {
	var obj = getObj(imgId);
	if(obj) {
		if(bEnable && obj.name != "enabled" && obj.name != "selected" && !obj.disabled) {
			obj.name = "enabled";
			focusButton(imgId, false);
		} else if(!bEnable && (obj.name == "enabled" || obj.name == "selected") && !obj.disabled) {
			obj.name = "disabled";
			focusButton(imgId, false);
		}
	}
}

function escapeChars(text) {
	//convert <,>,",',\ and & to the corresponding entities
	return String(text)
			.replace(/\n{2,}/g, "\n")
			.replace(/\&/g, "&amp;")
			.replace(/</g, "&lt;")
			.replace(/>/g, "&gt;")
			.replace(/\"/g, "&quot;")
			.replace(/\'/g, "&#39;")
			.replace(/\?/g, "&#63;")
			.replace(/\\/g, "&#92;")
			.replace(/\u00A0/g, "&nbsp;");
}

/**
 * Set/unset clicked on an image.
 * The method change the src of the image with ID given by parameter "sImgID"
 * to an javascript Image with the same name. or with the same name and a digit3.
 */
function pushImage(sImgID, bPushed) {
	theImg = getObj(sImgID);
	if(bPushed)
		theImg.src = eval(sImgID + "3").src;
	else
		theImg.src = eval(sImgID + "2").src;
}

function trimEndingSpace(text) {
	if(text.charAt(text.length - 1) == " ")
			text = text.substring(0, text.length - 1);
	return text;
}

/**
 * Resize a popup window to the width and height of an object that can be I.e. a table
 * or a div element.
 */ 
function setWindowSize(objectId) 
{
	/*
    // Get the input object
    object = document.getElementById(objectId);

    // Get object meassures
    var height = object.offsetHeight;
    var width = object.offsetWidth;

    // Maximum height
    if(height > screen.height * 0.8)
        height = screen.height * 0.8;

    // Maximum width
    if(width > screen.width * 0.8)
        width = screen.width * 0.8;

    // Outside right screen border?
    if(parent.screenLeft + width > screen.width)
        parent.moveBy((parent.screenLeft + width - screen.width) * -2);

    // Outside bottom screen border?
    if(parent.screenTop + height > screen.height)
        parent.moveBy(0, (parent.screenTop-20) * -1);

    // Resize window
    parent.resizeTo(width + 30, height + 50);
	*/
}

/**
 * Resize a popup window to the width and height of an object that can be I.e. a table
 * or a div element.
 */ 
function setObjectWindowSize(objectId) 
{

    // Get the input object
    object = document.getElementById(objectId);

    // Get object meassures
    var height = object.offsetHeight;
    var width = object.offsetWidth;

	// IE - Adjust size
	if(document.all) {
		width += 100;
		height += 20;
	} else {
		width += 150;
		height += 150;
	}

    // Maximum height
    if(height > screen.height * 0.8)
        height = screen.height * 0.8;

    // Maximum width
    if(width > screen.width * 0.8)
        width = screen.width * 0.8;

    // Outside right screen border?
    if(parent.screenLeft + width > screen.width)
        parent.moveBy((parent.screenLeft + width - screen.width) * -2);

    // Outside bottom screen border?
    if(parent.screenTop + height > screen.height)
        parent.moveBy(0, (parent.screenTop-20) * -1);

    // Resize window
    if(document.all) {
	    // IE
	    parent.dialogWidth = width + "px";
	    parent.dialogHeight = height + "px";
    } else {
    	// Mozilla
   		parent.resizeTo(width, height);
    }
}

function getObj(objectId) {
	if (document.getElementById(objectId) != null) {
	    return document.getElementById(objectId);
	} else {
		return document.getElementsByName(objectId)[0];
	}
}

function getOpener() {
	if (window.dialogArguments) {
	    return window.dialogArguments;
	} else {
		if (top.opener != null) {		
			return top.opener;
		} else if (window.opener != null) {		
			return window.opener;
		} else if(parent.opener != null) {
			return parent.opener;
		} else {
			return parent.window.opener;
		}
	}
}

function getParentElement(src) {
	//alert("src.tagName: " + src.tagName + "\nsrc.name: " + src.name); 
	if (src.parentElement) {
		return src.parentElement;
	} else if (src.parentNode) {
		return src.parentNode;
	} else {
		return null;
	}
}

function getEventSrcElement(evt) {
	var srcElement;
	if (evt && evt.target) {
		srcElement = evt.target;
		if (srcElement.nodeType == 3) {
			srcElement = srcElement.parentNode;
			}
	} else if (window.event) {
		srcElement = window.event.srcElement;
	}
	return srcElement;
}

function getChildElement(src, index) {
	if (src.childNodes)	{
		return src.childNodes[index];
	} else {
		return src.children[index];
	}
}

function popup(URI, width, height) { popup(URI, width, height, '', 150, 150); }
function popup(URI, width, height, name) { popup(URI, width, height, name, 150, 150); }
function popup(URI, width, height, name, posX, posY)
{
 try {
	/*if (window.showModalDialog) {
		posX = posX != undefined ? posX : 150;
		posY = posY != undefined ? posY : 150;
		window.showModalDialog(URI, window, "resizable:yes;dialogWidth:" + width + "px;dialogHeight:" + height + "px;dialogLeft:" + posX + "px;dialogTop:" + posY + "px");
	} else  {
		var win = window.open(URI,URI,"scrollbars=yes,modal=1,width=" + width + "px,height=" + height + "px" + ",resizable=yes");
		if (win != null) {
			win.focus();
			posX = posX != undefined ? posX : 150;
			posY = posY != undefined ? posY : 150;
			win.moveTo(posX, posY);
		}
		return win;
	}*/
	resizable_popup(URI, width, height, name, posX, posY);
	
 } catch(e) {
 }
}
function resizable_popup(URI, width, height) { resizable_popup(URI, width, height, ''); }
function resizable_popup(URI, width, height, name) 
{
	resizable_popup(URI, width, height, name, 150, 150);
}

function resizable_popup(URI, width, height, name, posX, posY)
{
	var win=window.open(URI, name,"width="+width+",height="+height+",status=no,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes");
	win.focus();
	win.moveTo(posX, posY);
}

/** 
 * Check if a text contains only alphabetic and/or numeric characters.
 *
 * param: sText       - Text to validate.
 * param: bAlphabetic - All characters "A-�, a-�" are seen as valid when this parameter is true.
 * param: bNumeric    - All characters "0-9" are seen as valid when this parameter is true.
 * param: bBlanks     - Blank characters are seen as valid when this parameter is true.
 *
 * return: true if all characters in sText parameter is valid.
 */
 function isValid(sText, bAlphabetic, bNumeric, bBlanks) {
    var bValid = true;
    for (var i=0; bValid && i < sText.length; i++) {		
        var c = sText.charCodeAt(i);
        bValid = false;

        // Number?
        if(bNumeric && c >= 48 && c <=57)
            bValid = true

        // Big capital alphabetic?
        if(!bValid && bAlphabetic && ((c >= 65 && c <= 90) || c == 197 || c == 196 || c == 214 || c == 45))
            bValid = true;

        // Small letter alphabetic?
        if(!bValid && bAlphabetic && ((c >= 97 && c <= 122) || c == 229 || c == 228 || c == 246))
            bValid = true;

		// Blank space
        if(!bValid && bBlanks && c == 32)
            bValid = true;
    }
    return bValid;
 }

 cellIndex = 0;
 rowIndex = 0;

function setEditMode(cell, rowIndex, cellIndex, baseURL, size, params) {
	 this.rowIndex = rowIndex;
	 this.cellIndex = cellIndex;

	 if(cell.name != "edit") {
		var value = cell.innerText ? cell.innerText : cell.textContent;

		var oldValue = encodeURIComponent(cell.innerHTML);
		cell.name = "edit";
		var sKeyDown =  "if(event.keyCode == 9) {";
			sKeyDown += "setViewMode(parentNode, '"+ baseURL + "', true , '" + oldValue + "', '" + params + "');";
			sKeyDown += "} else if(event.keyCode == 13) {";
			sKeyDown += "setViewMode(parentNode, '"+ baseURL + "', false , '" + oldValue + "', '" + params + "');";
			sKeyDown += "}";
		var maxlength = "";
		if(size == undefined || size == -1) {
			size = (cell.innerHTML.length+2);
		} else {
			maxlength = "maxlength = \"" + size + "\"";
		}

		cell.innerHTML = "<input id=\"editableTableCell\" onblur=\"" + "setViewMode(parentNode, '" + baseURL + "', false, '" + oldValue + "', '" + params + "');" + "\" onchange=\"" + "setViewMode(parentNode, '"+ baseURL + "', false, '" + oldValue + "', '" + params + "');" + "\" type=\"text\" size=\"" + size + "\" " + maxlength + "onkeydown=\"" + sKeyDown + "\">";
		
		if(value)
			getObj("editableTableCell").value = value;
 		getObj("editableTableCell").select();
	 }
 }

 function setViewMode(cell, baseURL, focusNext, oldValue, params) {
	 if(cell.name == "edit") {
		 cell.name = "view";
		 var value = cell.firstChild.value;
		 if(document.all)
			cell.innerText = value;
		 else
			cell.textContent = value;
		 value = encodeURIComponent(value);
		 if(baseURL != null && oldValue != value) {
		 	var url = baseURL + "/modifyTableCell.do";
		 	url += "?rowIndex=" + rowIndex;
		 	url += "&cellIndex=" + cellIndex;
		 	url += "&value=" + value;
		 	if(params)
		 		url += "&" + params;
			setHiddenURL(url);
		 }
	 }
	 /*
	 if(focusNext) {
		 var cellIndexNew = (Number(cellIndex) + 1);
		 if (document.getElementById(rowIndex + "_" + cellIndexNew) != null)
			 setEditMode(document.getElementById(rowIndex + "_" + cellIndexNew), rowIndex, cellIndexNew, baseURL, -1, table);
	 }
	 */
 }

function setHiddenURL(sURL) {
	if(frames["hidden"] != null && frames["hidden"] != undefined)
		frames["hidden"].location.href = sURL;
	else {
		parent.parent.parent.frames["hidden"].location.href = sURL;
	}
}

function getHiddenFrame() {
	return parent.parent.parent.frames["hidden"];
}

function getContentFrame() {
	 var frmContent;
	 if (parent.frames["popupTable"] != null) {
		frmContent = parent.frames["popupTable"]
	 } else if(parent.frames["content"] && !parent.frames["content"].frames) {
		frmContent = parent.frames["content"];
	 } else if((!document.all && parent.frames["content"].frames["frmContent"]) || (document.all && parent.frames["content"])){
		frmContent = parent.frames["content"].frames["frmContent"];
	 } else {
		frmContent = parent;
	 }
	/* } else if(parent.parent.frames["content"].frames["content"] != undefined && parent.parent.frames["content"].frames["content"].frames == undefined) {
		frmContent = parent.frames["content"];
	 } else if(parent.parent.frames["content"].frames["content"] == undefined) {
		frmContent = parent.parent.frames["content"].frames["frmContent"];
	 } else if(parent.frames["content"].frames["content"] != undefined) {
		frmContent = parent.frames["content"].frames["content"].frames["frmContent"];
	 } else if (parent.parent.frames["content"].frames["content"] != undefined) {
		frmContent = parent.parent.frames["content"].frames["content"].frames["frmContent"];
	 } else {
		frmContent = parent.frames["content"].frames["frmContent"];
	 }*/

	 return frmContent;
 }

 function getMainPage() {
	 return parent.parent.frames["content"];
 }

// Preloading images
imgCheckbox = new Image();
imgCheckbox.src = "images/checkbox.gif";
imgCheckbox2 = new Image();
imgCheckbox2.src = "images/checkbox_checked.gif";

function checkAll(theImg) {
	var elmts = document.forms[0].elements;
	if(theImg.src == imgCheckbox.src) {
		var bCheck = true;
		theImg.src = imgCheckbox2.src;
	} else {
		var bCheck = false;
		theImg.src = imgCheckbox.src;
	}
	for(i=0; i < elmts.length; i++) {
		if(elmts[i].type == "checkbox") {
			if(bCheck) {
				elmts[i].checked = true;
			} else {
				elmts[i].checked = false;
			}
		}
	}
}

/**
 * This function can be used in textfields that allows only numeric values.
 * add following code in the input tag: onkeydown="return isNumeric(event)"
 */
function isNumeric(event) { 
	event = (event) ? event : ((window.event) ? window.event : "");
	var isValid = false;
	if(event.keyCode == 27
		|| event.keyCode == 13
		|| event.keyCode == 9
		|| (event.keyCode >= 48 && event.keyCode <= 57)
		|| (event.keyCode >= 96 && event.keyCode <= 105)
		|| event.keyCode == 8
		|| event.keyCode == 46
		|| event.keyCode == 39
		|| event.keyCode == 37
		|| event.keyCode == 36
		|| event.keyCode == 35
		|| (event.ctrlKey) && (event.keyCode == 67 || event.keyCode == 86 || event.keyCode == 88)) // ctrl + c,v,x
			isValid = true;
	if(!isValid)
		return false;
}

/**
 * This function can be used in textfields that allows only numeric values.
 * 
 * Add following code in the input tag:
 *
 * onfocus="this.oldValue = this.value" onblur="preventNaN(this);"
 */
function preventNaN(inputObj) {
	if(isNaN(inputObj.value))
		inputObj.value = inputObj.oldValue ? inputObj.oldValue : 0;
}

/*
function modelessDialogShow(url,width,height)
	{
	window.showModelessDialog(url,window,"dialogWidth:"+width+"px;dialogHeight:"+height+"px;edge:Sunken;center:Yes;help:No;resizable:No;status:No");
	}
function modalDialogShow(url,width,height)
	{
	window.showModalDialog(url,window,"dialogWidth:"+width+"px;dialogHeight:"+height+"px;edge:Sunken;center:Yes;help:No;resizable:No;status:No");
	}
function modelessDialogShowResizable(url,width,height)
	{
	window.showModelessDialog(url,window,"dialogWidth:"+width+"px;dialogHeight:"+height+"px;edge:Sunken;center:Yes;help:No;resizable:Yes;status:No");
	}
function modalDialogShowResizable(url,width,height)
	{
	window.showModalDialog(url,window,"dialogWidth:"+width+"px;dialogHeight:"+height+"px;edge:Sunken;center:Yes;help:No;resizable:Yes;status:No");
	}

function replaceModalDialog(modalWindow, url, width, height) {
	var left = modalWindow.screenLeft - 4;
	var top = modalWindow.screenTop - 23;
	modalparent.close();
	window.showModalDialog(url,window,"dialogLeft:"+left+"px;dialogTop:"+top+"px;dialogWidth:"+width+"px;dialogHeight:"+height+"px;edge:Sunken;center:No;help:No;resizable:No;status:No");
}

function replaceModalDialogResizable(modalWindow, url, width, height) {
	var left = modalWindow.screenLeft - 4;
	var top = modalWindow.screenTop - 23;
	modalparent.close();
	modalDialogShowResizable(url,width,height);

	//window.showModalDialog(url,window,"dialogLeft:"+left+"px;dialogTop:"+top+"px;dialogWidth:"+width+"px;dialogHeight:"+height+"px;edge:Sunken;center:No;help:No;resizable:No;status:No");
}
*/

function existsInArray(value, array) {
	var exists = false;
	for(var i=0; i < array.length; i++) {
		if(array[i] == value) {
			exists = true;
			break;
		}
	}
	return exists
}

/**
* The functionality to disable options in a select is not implemented in Internet Explorer.
* Use this function in "select"-tag to emulate the option disable functionality in IE.
*
* Usage: <select onmousedown="this.lastIndex = this.selectedIndex" onclick="checkOptionDisabled(this)">
**/
function checkOptionDisabled(objSelect) {
	if(document.all) {
		var objOption = objSelect.options[objSelect.selectedIndex];
		if(objOption.disabled)
			objSelect.selectedIndex = objSelect.lastIndex;
	}
}

/*
* Removes an element from an array and returns the array without this element.
*/
function removeElementFromArray(theArray, index) {
	index = Number(index); 
	var array = new Array();
	for(var i=0; i < index; i++)
		array.push(theArray[i]);
	for(var i=index+1; i < theArray.length; i++)
		array.push(theArray[i]);
	return array;
}

function setScrolling(condition) {
	if(!document.all) {
		if(parent.getObj("frmContent")) {
			if(condition && parent.getObj("frmContent").scrolling == "no")
				parent.getObj("frmContent").scrolling = "yes";
			else if(!condition && parent.getObj("frmContent").scrolling == "yes")
				parent.getObj("frmContent").scrolling = "no";
		}
	}
}

// capture some window's events
function capwin(w) {
	_addEvent(w, "click", _parentEvent);
	_addEvent(w, "dblclick", _parentEvent);
	_addEvent(w, "mousedown", _parentEvent);
	_addEvent(w, "mouseup", _parentEvent);
	_addEvent(w, "mouseover", _parentEvent);
	_addEvent(w, "focus", _parentEvent);
};

// release the captured events 
function relwin(w) {
	_removeEvent(w, "click", _parentEvent);
	_removeEvent(w, "dblclick", _parentEvent);
	_removeEvent(w, "mousedown", _parentEvent);
	_removeEvent(w, "mouseup", _parentEvent);
	_removeEvent(w, "mouseover", _parentEvent);
	_removeEvent(w, "focus", _parentEvent);
};

var srcWindow;
function setSourceWindow(src) {
	srcWindow = src;
}

function _addEvent(el, evname, func) {
	if (document.all) {
		el.attachEvent("on" + evname, func);
	} else {
		el.addEventListener(evname, func, true);
	}
};

function _removeEvent(el, evname, func) {
	if (document.all) {
		el.detachEvent("on" + evname, func);
	} else {
		el.removeEventListener(evname, func, true);
	}
};

function _parentEvent(ev) {
	_stopEvent(ev);
};

function _stopEvent(ev) {
	if (document.all) {
		ev.cancelBubble = true;
		ev.returnValue = false;
	} else {
		ev.preventDefault();
		ev.stopPropagation();
		if(srcWindow) {
			try {
				srcWindow.focus();	
			} catch (err) {
				// Do nothing
			}			
		}
	}
};

function goToURL(url, baseURL) {
	window.location.href = baseURL  + url;
}

function initKeyListener() {
	// Check for the Enter key
	if(document.all)
		document.attachEvent("onkeydown", function evt_ie_keydown(event) {checkEnterKey(event);});
	else
		document.addEventListener('keydown', checkEnterKey, false);
	
	try {
		preselect();
	}catch (err){
		// Do nothing
	}
}

// Check if the [Enter]-key has been pressed.
//
// Calls a method called "submitForm()" if the [Enter]-key has been pressed.
//
// If a textarea or a time field is in focus, the function call will not be executed.
//
// You must add following code to all textareas on your page:
// onfocus="this.status=true" onblur="this.status=false"
function checkEnterKey(event) {
	if(event.keyCode == 13) {
		var doSubmit = true;

		// Textarea
		var txtAreas = document.getElementsByTagName("TEXTAREA");
		for(var i=0; i < txtAreas.length; i++) {
			if(txtAreas[i].status) {
				doSubmit = false;
				break;
			}
		}

		// Input, Time fields
		if(doSubmit) {
			var inputs = document.getElementsByTagName("INPUT");
			for(var i=0; i < inputs.length; i++) {
				if(inputs[i].name.indexOf("_Hours") == (inputs[i].name.length - 6)
					|| inputs[i].name.indexOf("_Minutes") == (inputs[i].name.length - 8))
				{
					doSubmit = false;
					break;
				}
			}
		}

		if(doSubmit)
			submitForm();
	}
}

function getBaseURL() {
	return window.location.protocol + "//" + window.location.host + "/admin/";
}

function clearTableCache(tableName) {
	
	var path = getBaseURL() + "clearTableCache.do?";

	// Array
	if(tableName instanceof Array) {
		for(var i=0; i < tableName.length; i++)
			path += "&t=" + tableName[i];
	// String	
	} else {
		path += "&t=" + tableName;		
	}
	
	if(top.getOpener && top.getOpener().setHiddenURL)
		top.getOpener().setHiddenURL(path);
	else if(parent.getOpener && parent.getOpener().setHiddenURL)
		parent.getOpener().setHiddenURL(path);
}

// Remove space, set to lowercase, except for second words capital letters
function generateKeyName(inString) {
	var pattern = /(\w)(\w*)/; // a letter, and then one, none or more letters
    var stringArray = inString.split(/\s+/g); // split the sentence into an array of words

    for (i = 0 ; i < stringArray.length ; i ++ ) {
        var parts = stringArray[i].match(pattern);
		var firstLetter = "";
		var restOfWord = "";

		try {
			if(i == 0) {
	        	firstLetter = parts[1].toLowerCase(); // First time make lover case
	        } else {
	        	firstLetter = parts[1].toUpperCase();
	        }
	  		restOfWord = parts[2].toLowerCase();
		} catch(err)
		{ 
			// do nothing 
		}
        stringArray[i] = firstLetter + restOfWord; // re-assign it back to the array and move on
    }
    
    return stringArray.join(''); // join it back together
} 

function trim(data) {
	return data.replace(/^\s+|\s+$/g,"");
}
