/*
Author: Philip Wu
*/
	 function cloneSection(cloneFrom, insertBeforeRow, index) {
			var blueprint = document.getElementById(cloneFrom);
			var insertBeforeRowEl = document.getElementById(insertBeforeRow);

			
			cloneSectionByCallback(blueprint, insertBeforeRowEl, index, enableFormElement);			
	 }	 
	 
	 /**
	  * Clones from a blueprint and enables each form element and inserts into a table
	  * 
	  * @param blueprint
	  * @param insertBeforeRowEl
	  * @param index
	  * @return
	  */
	 function cloneSectionEl(blueprint, insertBeforeRowEl, index) {
		 cloneSectionByCallback(blueprint, insertBeforeRowEl, index, enableFormElement);	
	 }
	 
	 function cloneSectionByCallback(blueprint, insertBeforeRow, index, fnCallback) {
		 
			var clonedBlueprint = blueprint.cloneNode(true);
			var newInnerHtml = clonedBlueprint.innerHTML;
			var newInnerHtml = newInnerHtml.replace(/___INDEX___/g, index);

			clonedBlueprint.innerHTML = newInnerHtml;
		 
			var rowEls = clonedBlueprint.getElementsByTagName("tr");
			if (rowEls.length > 0) {
				var rowEl = rowEls[0];

				 while (rowEl != null) {

					if (rowEl.nodeType == 1 && rowEl.tagName.toLowerCase()=='tr') { 
						
						var childClone = rowEl.cloneNode(true);						
						
						enableAllFormElementsByCallback(childClone, index, fnCallback);
						
						insertBeforeRow.parentNode.insertBefore(childClone,insertBeforeRow);
					}
					rowEl = rowEl.nextSibling;
				 } 
			}
		 
	 }
	 
	 
	 function updateIds(el, index) {		 
		 if (el == null)
			 return;
		 else if(el.nodeType == 1 /* Node.ELEMENT_NODE*/) {
			 
			 var id = el.getAttribute("id");
			 if (id != null) {
				 var newId = id.replace("___INDEX___", index);
				 el.setAttribute("id", newId);
				 el.id=newId;
			 }
			 
			 // Recurse
			 for (var m=el.firstChild; m!= null; m = m.nextSibling) {
				updateIds(m, index); 
			 }			 
		 }
		 
	 }
	 
	 var enableFormElement = function(el, index) {
			var curName = el.name;
			if (curName != null) {
				var newName = curName.replace('___INDEX___',index);
				el.name = newName;
			}
			
			el.disabled=false;	 
	 };	 
	 
	 function enableAllFormElements(parent, index) {
		 
		 enableAllFormElementsByCallback(parent, index, enableFormElement);
		 
	 }
	 
	 function enableAllFormElementsByCallback(parent, index, fnCallback) {
		 
		 updateIds(parent, index);
		 
		 if (typeof(fnCallback) == 'function') {
			//update the name of the input element
			var inputEls = parent.getElementsByTagName('input');
			if (inputEls != null && inputEls.length > 0) {
				for (j=0; j<inputEls.length; j++) {
					var inputEl = inputEls[j];
					fnCallback(inputEl, index);
				}
			}

			var selectEls = parent.getElementsByTagName('select');
			if (selectEls != null && selectEls.length > 0) {
				for (j=0; j<selectEls.length; j++) {
					var selectEl = selectEls[j];
					fnCallback(selectEl, index);
				}
			}

			var textareaEls = parent.getElementsByTagName('textarea');
			if (textareaEls != null && textareaEls.length > 0) {
				for (j=0; j<textareaEls.length; j++) {
					var textareaEl = textareaEls[j];
					fnCallback(textareaEl, index);
				}
			}
			
			var anchorEls = parent.getElementsByTagName('a');
			if (anchorEls != null && anchorEls.length > 0) {
				for (j=0; j<anchorEls.length; j++) {
					var anchorEl = anchorEls[j];
					fnCallback(anchorEl, index);
				}
			}
			
		 }
		 
	 }
	 
	 function f_clientWidth() {
			return f_filterResults (
				window.innerWidth ? window.innerWidth : 0,
				document.documentElement ? document.documentElement.clientWidth : 0,
				document.body ? document.body.clientWidth : 0
			);
		}
		function f_clientHeight() {
			return f_filterResults (
				window.innerHeight ? window.innerHeight : 0,
				document.documentElement ? document.documentElement.clientHeight : 0,
				document.body ? document.body.clientHeight : 0
			);
		}
		function f_scrollLeft() {
			return f_filterResults (
				window.pageXOffset ? window.pageXOffset : 0,
				document.documentElement ? document.documentElement.scrollLeft : 0,
				document.body ? document.body.scrollLeft : 0
			);
		}
		function f_scrollTop() {
			return f_filterResults (
				window.pageYOffset ? window.pageYOffset : 0,
				document.documentElement ? document.documentElement.scrollTop : 0,
				document.body ? document.body.scrollTop : 0
			);
		}
		function f_filterResults(n_win, n_docel, n_body) {
			var n_result = n_win ? n_win : 0;
			if (n_docel && (!n_result || (n_result > n_docel)))
				n_result = n_docel;
			return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
		}
		
		  function show_hide_column(col_no, do_show, tableId) {

			    var stl;
			    if (do_show) stl = ''
			    else         stl = 'none';

			    var tbl  = document.getElementById(tableId);
			    var rows = tbl.getElementsByTagName('tr');

			    for (var row=0; row<rows.length;row++) {
			      var cels = rows[row].getElementsByTagName('td');
			      if (col_no < cels.length - 1)
			    	  cels[col_no].style.display=stl;
			      
			      var thCells = rows[row].getElementsByTagName('th');
			      if (col_no < thCells.length - 1)
			    	  thCells[col_no].style.display=stl;
			    }
			  }

		//Keep traversing through the parent nodes until we find an element that is a row
		  function findParentRowEl(el) {

		  	return findParentEl(el, 'tr');
		  	
		  }

		  function findParentEl(el, parentElName) {

		  	 if (el == null)
		  		 return;
		  	 else if(el.nodeType == 1 /* Node.ELEMENT_NODE*/ && el.tagName.toLowerCase() == parentElName) {
		  			 return el;
		  	 } else {
		  		 return findParentEl(el.parentNode, parentElName);
		  	 }
		  	
		  }
		  
		  function nextSiblingElement(element) {
				var el = element;
				do el = el.nextSibling;
				while (el != null && el.nodeType != 1);
				return el;
			}		  
	 
		  
	  document.getElementsByClassName = function(cl) {
		  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 (myclass.test(classes)) retnode.push(elem[i]);
		  }
		  return retnode;
	  }; 
	  
	  function showElement(id) {
		  var el = document.getElementById(id);  
		  el.style.display='';
	  }
	  
	  function showElementBlock(id) {
		  var el = document.getElementById(id);  
		  el.style.display='block';
	  }
	  
	  function hideElement(id) {
		  var el = document.getElementById(id);  
		  el.style.display='none';
	  }
	  
	  function showInvestigator(index) {

			var plusEl = document.getElementById('investigatorPlus'+index);
			plusEl.style.display='none';
			var minusEl = document.getElementById('investigatorMinus'+index);
			minusEl.style.display='block';

			$("#investigator"+index).slideDown("slow");
			
			
		}


		function hideInvestigator(index) {

			var plusEl = document.getElementById('investigatorPlus'+index);
			plusEl.style.display='block';
			var minusEl = document.getElementById('investigatorMinus'+index);
			minusEl.style.display='none';

			$("#investigator"+index).slideUp("slow");
		}	
				
		function toggleSidebar(type) {
			
			var groupId = 'sidebar'+type;
			var groupEl = document.getElementById(groupId);
			var expand = document.getElementById(type+'Expand');
			var collapse = document.getElementById(type+'Collapse');
			
			if (groupEl.expanded == null) {
				var expanded = groupEl.getAttribute("expanded");
				if (expanded == 'true') {
					groupEl.expanded = true;
				} else
					groupEl.expanded = false;
			}
			
			if ( groupEl.expanded ) {
				
				groupEl.style.display = 'none';
				
				updateMenuState(type, 'none');
				
				expand.style.display = 'none';
				collapse.style.display = 'inline';
				UserPreferences.updateSessionMenuPreferences('menu'+type, false, null);
				groupEl.expanded = false;
				
			} else {
				
				groupEl.style.display= '';
				
				updateMenuState(type, '');
				
				expand.style.display = 'inline';
				collapse.style.display = 'none';				
				UserPreferences.updateSessionMenuPreferences('menu'+type, true, null);
				groupEl.expanded = true;
			}
			
		}
		  
		/**
		 * For hiding/showing group of list(li) elements
		 * @param type
		 * @param displayValue
		 * @return
		 */
		function updateMenuState(type, displayValue) {
			
            $("li[group='"+type+"']").each(function() 
	                { 
	                    this.style.display = displayValue; 
	                }); 			
		}
		
		this.screenshotPreview = function(){	
			/* CONFIG */
				
				xOffset = 10;
				yOffset = 30;
				
				// these 2 variable determine popup's distance from the cursor
				// you might want to adjust to get the right result
				
			/* END CONFIG */
			$("a.screenshot").hover(function(e){
				this.t = this.title;
				this.title = "";	
				var c = (this.t != "") ? "<br/>" + this.t : "";
				$("body").append("<p id='screenshot'><img src='"+ this.rel +"' alt='url preview' />"+ c +"</p>");								 
				$("#screenshot")
					.css("top",(e.pageY - xOffset) + "px")
					.css("left",(e.pageX + yOffset) + "px")
					.fadeIn("slow");						
		    },
			function(){
				this.title = this.t;	
				$("#screenshot").remove();
		    });	
			$("a.screenshot").mousemove(function(e){
				$("#screenshot")
					.css("top",(e.pageY - xOffset) + "px")
					.css("left",(e.pageX + yOffset) + "px");
			});			
		};
		
		function confirmDelete(delUrl) {
			  if (confirm("Are you sure you want to delete")) {
			    document.location = delUrl;
			  }
			}
		
		function confirmDeleteMessage(msg, delUrl) {
			  if (confirm(msg)) {
			    document.location = delUrl;
			  }
			}		
		
		/*
		  Finds the previous element relative to the current element with the given element name
		  @param selectEl
		  @return
		 */
		function findPreviousElement(currentEl, elName) {
			
			var prevAnchor = null;
			var curNode = currentEl;
			elName = elName.toUpperCase();
			while (curNode.previousSibling != null) {
				
				if (curNode.previousSibling.nodeType == 1 && curNode.previousSibling.tagName.toUpperCase() == elName ) {
					prevAnchor = curNode.previousSibling;			
					break;
				}		
				curNode = curNode.previousSibling;
			}
			return prevAnchor;
		}		
		
		/*
		  Finds the next element relative to the current element with the given element name
		  @param selectEl
		  @return
		 */
		function findNextElement(currentEl, elName) {
			
			var targetEl = null;
			var curNode = currentEl;
			elName = elName.toUpperCase();
			while (curNode.nextSibling != null) {
				
				if (curNode.nextSibling.nodeType == 1 && curNode.nextSibling.tagName.toUpperCase() == elName ) {
					targetEl = curNode.nextSibling;			
					break;
				}		
				curNode = curNode.nextSibling;
			}
			return targetEl;
		}		
		
		/**
		 * Clears the file input
		 * @param el
		 * @return
		 */
		var clearFileInputField = function (el) { 
			
			var fileInputEl = findPreviousElement(el, 'INPUT');
			
			fileInputEl.type = 'input';
			fileInputEl.type = 'file';
		} 		
		
		
		/**
		 * Resizes the frame adding an additional buffered height
		 * @param el
		 * @param bufferHeight
		 * @return
		 */
		function resizeFrame(el, bufferHeight){
		    el.height=100;
		    el.height=window.frames[el.name].document.body.scrollHeight + bufferHeight;
		}			
		
		
		/**
		 * For editing storage locatin positions. When pressing 'tab' move
		 * down to the next row in the same column
		 */   
		function handleKeyPressTabDown(e, el) {

			var keynum;
			if(window.event) { // IE 
				keynum = window.event.keyCode;
			} else if(e.which) { // Netscape/Firefox/Opera	
				keynum = e.which;
			}

			if (keynum == 13) {
				return false;
			} else if (keynum == 9) { // tab

				var tdEl = findParentEl(el,'td');
				var trEl = findParentEl(el,'tr');

				// find the column index to which the tdEl belongs in the table
				var tds = trEl.getElementsByTagName('td');
				var columnIndex = 0;
				for (var i=0; i < tds.length; i++ ) {

					var td = tds[i];
					if (td == tdEl) {
						columnIndex = i;
						break;	
					}
				}
				//alert('column index='+columnIndex);

				var rowEl = trEl.nextSibling;
				while (rowEl != null) {
					if (rowEl.nodeType == 1 && rowEl.tagName.toLowerCase()=='tr') { 
						var rowTds = rowEl.getElementsByTagName('td');
						var targetTd = rowTds[columnIndex];
						if (targetTd != null) {
							//targetTd.setAttribute("style", "background-color: green");
							var inputEls = targetTd.getElementsByTagName('input');
							if (inputEls != null && inputEls.length > 0) {							
								inputEls[0].focus();
								return false;						
							}
						}
						break;
					}
					rowEl = rowEl.nextSibling;
				 } 			
				
			}
		
		 	return true;

		}		
		
		/**
		 * Handle keypresses of scores restricting it to values 0-5 only
		 * @param e
		 * @param el
		 * @return
		 */
		function handleKeyPressScore(e, el) {
			
			var keynum;
			if(window.event) { // IE 
				keynum = window.event.keyCode;
			} else if(e.which) { // Netscape/Firefox/Opera	
				keynum = e.which;
			}
			
			// If 0-5 or tab key, backspace, or del
			if ((keynum >= 48 && keynum <=53) || (keynum >=96 && keynum <= 101) || keynum == 9 || keynum == 8 || keynum == 127)
				return handleKeyPressTabDown(e, el);
			else
				return false;						
		}
		

		