/* GENERAL USE SCRIPTS */

// Dreamweaver Default Scripts
// Image Preloader
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

// Swap Image Restory
function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

// Find Obj (Dreamweaver)
function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

// Swap Image
function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

// Swap Image (non macromedia auto fill)
function swapImage() { //v3.0
  var i,j=0,x,a=swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

// Open Browser Window
function MM_openBrWindow(theURL,winName,features) { //v2.0
  newwindow = window.open(theURL,winName,features);
  if (window.focus) {newwindow.focus()}
}

// Counts how many characters are left from the Limit Text Function
function TrackCount(fieldObj,countFieldName,maxChars)
{
  var countField = eval("fieldObj.form."+countFieldName);
  var diff = maxChars - fieldObj.value.length;

  // Need to check & enforce limit here also in case user pastes data
  if (diff < 0)
  {
    fieldObj.value = fieldObj.value.substring(0,maxChars);
    diff = maxChars - fieldObj.value.length;
  }
  countField.value = diff;
}

// Limits the text in a textarea field
function LimitText(fieldObj,maxChars)
{
  var result = true;
  if (fieldObj.value.length >= maxChars)
    result = false;
  
  if (window.event)
    window.event.returnValue = result;
  return result;
}

// Function to check/uncheck all checkboxes
function SetAllCheckBoxes(FormName, FieldName, CheckValue)
{
	if(!document.forms[FormName])
		return;
	var objCheckBoxes = document.forms[FormName].elements[FieldName];
	if(!objCheckBoxes)
		return;
	var countCheckBoxes = objCheckBoxes.length;
	if(!countCheckBoxes)
		objCheckBoxes.checked = CheckValue;
	else
		// set the check value for all check boxes
		for(var i = 0; i < countCheckBoxes; i++)
			objCheckBoxes[i].checked = CheckValue;
}

// ShowHide id_#id#
function showHide(targetId) {
	//alert(document.getElementById('icon_' + targetId).src);
	if (document.getElementById('id_' + targetId)) {
	
		if (document.getElementById('id_' + targetId).style.display == "none") {
			document.getElementById('id_' + targetId).style.display = "";
			//document.getElementById('icon_' + targetId).src = "images/e.jpg";
		} else {
		document.getElementById('id_' + targetId).style.display = "none";
		//document.getElementById('icon_' + targetId).src = "images/c.jpg";
		}
		
	}
}

// ShowHide2 id_#id#
function showHide2(targetId,theAction) {
	
	// if the id exists
	if (document.getElementById(targetId)) {
		
		//if the action is hide
		if (theAction == 'hide') {
			document.getElementById(targetId).style.display = 'none';
		} else {	
			document.getElementById(targetId).style.display = '';
		}
		
	}

}

// ShowHide id
function showHide3(targetId) {
	//alert(document.getElementById('icon_' + targetId).src);
	if (document.getElementById(targetId)) {
	
		if (document.getElementById(targetId).style.display == "none") {
			document.getElementById(targetId).style.display = "";
		} else {
			document.getElementById(targetId).style.display = "none";
		}
		
	}
}

/* EVENT CALENDAR SCRIPTS */

// What happens when you roll over a day
function rolloverDay(theID,theClass) {
	
	var myElement = document.getElementById(theID);
	
	if (!(myElement.className == theClass)) {
		myElement.className = theClass;
	}
	
}

// What happens when you un-roll over a day
function unRolloverDay(theID,theClass) {
	
	var myElement = document.getElementById(theID);
	
	if (!(myElement.className == theClass)) {
		myElement.className = theClass;
	}
	
}

/* this function shows the pop-up when
 user moves the mouse over the link */
function Show(theDiv,e)
{
	var TheEventObject;
	if(e)
	{
	TheEventObject = e;
	}
	else if(window.event)
	{
	TheEventObject = window.event;
	}
	else
	{
	TheEventObject = null;
	}
	
	var divRef = document.getElementById(theDiv);
	var ifrRef = document.getElementById(theDiv + '_frame');
	
	/* get the mouse left position */
	x = TheEventObject.clientX + document.documentElement.scrollLeft + 50;
	/* get the mouse top position  */
	y = TheEventObject.clientY + document.documentElement.scrollTop - 30;
	/* display the pop-up */
	divRef.style.display="block";
	/* display the frame */
	ifrRef.style.width = divRef.offsetWidth - 2 + "px";
	ifrRef.style.height = divRef.offsetHeight - 2 + "px";
	ifrRef.style.display="block";
	
	divRef.style.position = "absolute";
	/* set the pop-up's left */
	//divRef.style.left = 0;//x + "px";
	/* set the pop-up's top */
	//divRef.style.top = 0;//y + "px";
	
	//alert(divRef.style.left)
	
	//alert(findPosX(divRef))
	
	$(divRef).offset({left:x,top:y});
	
}

function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }

  function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }


/* this function hides the pop-up when
 user moves the mouse out of the link */
function Hide(theDiv)
{
	/* hide the pop-up */
	document.getElementById(theDiv).style.display="none";
}

//Highlights a DIV
function highlightDiv(theDiv) {
	
	var myElement = document.getElementById(theDiv);
	
	if (!(myElement.className == "event_rollover")) {
		/*alert('highlight_div');*/
		myElement.className = "event_rollover";
	}
	
}

// unhighlights a div
function UnHighlightDiv(theDiv) {
	
	var myElement = document.getElementById(theDiv);
	
	if (!(myElement.className == "event_rollover_no")) {
		/*alert('UNhighlight_div');*/
		myElement.className = "event_rollover_no";
	}
	
}

// Shows the extra events
function showExtraEvents(theDay) {
	document.getElementById('day_Plus_' + theDay).style.display = "none";
	document.getElementById('day_Minus_' + theDay).style.display = "inline";
	document.getElementById('extraEvents_' + theDay).style.display = "block";
}

// Hides the extra events
function hideExtraEvents(theDay) {
	document.getElementById('day_Plus_' + theDay).style.display = "inline";
	document.getElementById('day_Minus_' + theDay).style.display = "none";
	document.getElementById('extraEvents_' + theDay).style.display = "none";
}

// goes through a table and makes sure every row has the correct className
function colorTable ( theTable ) {
	var tbl = document.getElementById(theTable);
	var rowCount = 0;
	
	//if (tbl) {
	
		for (var r = 1; r < tbl.rows.length; r++){
			if (tbl.rows[r].style.display == 'none') {
		} else {
			rowCount++;
		}
		if(rowCount % 2 == 0){ 
			displayClass = 'dataEvenRow'; 
		} else { 
			displayClass = 'dataOddRow';
		}
			tbl.rows[r].className = displayClass;
	}
	
	//}
}

// This script will show/hide table rows of parent/child relationships
function showHideRows(theTable,myId) {

	var plusImage = new Image();
    plusImage.src = '../admin/customIcons/plus.gif';
	
	var minusImage = new Image();
    minusImage.src = '../admin/customIcons/minus.gif';
	
	//alert('hiding children of: ' + myId + 'on the table: ' + theTable);
	
	// the currentAction defines whether we are hiding or showing. its set below 
	var currentAction = ''
	
	// stat by getting a list of ALL of the rows on the page
	allRows = document.getElementById(theTable).getElementsByTagName('TR')
	
	//alert(allRows.length + ' rows found');
	
	// loop through the rows array
	for( x=0; x < allRows.length; x++ ) {
		//get the Id for the current row
		var currentId = allRows[x].getAttribute("id");
		//alert('currentID: ' + currentId);
		//alert('comparing: ' + currentId.substring(0,divLength) + 'And: ' + parentDiv);
		// Assign the value of the first list element to a variable
		if ( currentId ) {
		
			var currentList = listgetat(currentId,2,'_')
			var currentValue = listgetat(currentId,3,'_')
			//alert('current list: ' + currentList);
			
			// see if the id of the parent is present in this list
			listfind(currentList,myId)
			//alert('Comparing: ' + myId + ' to: ' + currentList +' Found Status: ' + FoundIdx);
			
			//if the id is found in this list. then we are speaking to the right row(s). Proceed.
			if( FoundIdx != 0 ){
				
				//alert('match found!');
				//assign the action we are taking basedon the state of the first row we find
				if (allRows[x].style.display == 'none' && currentAction == '') {
					currentAction = 'show';
				} else if (currentAction == '') { 
					currentAction = 'hide';	
				}
				
				// now sometimes, there will be elements nested below other elements (3 tree levels or more). 
				// We want to retain the state of the other elements, so we need to know what the next lefel element is.
				// get the first item in the list
				lastElement = listgetat(currentList,listlen(currentList))
				//alert('lastElement: ' + lastElement);
				
				// if we are at the first tree branch, set the hidden form field.
				if ( lastElement == myId ) {
					if ( currentAction == 'hide' ) {
						document.getElementById('visible_' + theTable + '_' + currentValue).value = 'no'
					} else {
						document.getElementById('visible_' + theTable + '_' + currentValue).value = 'yes'
					}	
				}
				
				//alert('currentValue: ' + document.getElementById('visible_' + theTable + '_' + currentValue).value);
				
				if ( currentAction == 'hide' ) {
					allRows[x].style.display='none';
				} 
				//only reveal this if it is the first tree branch, or if the last state is yes
				else if ( lastElement == myId || document.getElementById('visible_' + theTable + '_' + currentValue).value == 'yes' ) {
					allRows[x].style.display='';
				}
				
			}
			
		}
	}
	
	if (currentAction == 'hide') {
		//alert('more_' + myId + ' making plus');
		document.getElementById('more_' + myId).src = plusImage.src;
	} else {
		document.getElementById('more_' + myId).src = minusImage.src;
		//alert('more_' + myId + ' making minus');
	}
	
	colorTable( theTable );
}

// This script will show/hide table rows of parent/child relationships
function showHideRows2(theTable,theID,action) {

	//console.log(action + 'rows');
	
	var showImage = document.getElementById(theTable + '_' + theID + '_show');
	var hideImage = document.getElementById(theTable + '_' + theID + '_hide');

	// stat by getting a list of ALL of the rows in the table
	allRows = document.getElementById(theTable).getElementsByTagName('TR');
	
	//console.log(allRows.length + ' rows found');
	
	// loop through the rows array. we are looking for the branch that belongs to the one we just clicked.
	for( x=0; x < allRows.length; x++ ) {
		
		//get the Id for the current row
		var currentId = allRows[x].getAttribute("id");
		//console.log('currentID: ' + currentId);
		
		// Assign the value of the first list element to a variable
		if ( currentId ) {
		
			var currentValue = listgetat(currentId,2,'_')
			
			// get this row's parent tree
			var currentTreeObject = document.getElementById(theTable + '_' + currentValue + '_parentTree')
						
			if (currentTreeObject) {
				currentTree = currentTreeObject.value;
			} else {
				currentTree = '0';
			}
			
			// if the ID of the record we clicked is in the currentTree, then we are looking at a subrecord of the 
			// clicked branch.  We will want to perform some action with this.
			listfind(currentTree,theID)
			//console.log('Comparing: ' + theID + ' to: ' + currentTree +' Found Status: ' + FoundIdx);
			
			//if the id is found in this list. then we are speaking to the right row(s). Proceed.
			if( FoundIdx != 0 ){
				
				var currentVisibleField = document.getElementById(theTable + '_' + currentValue + '_visible')
				
				//console.log('match found!');
				
				// now sometimes, there will be elements nested below other elements (3 tree levels or more). 
				// We want to retain the state of the other elements, so we need to know what the next lefel element is.
				// get the last item in the list
				currentParent = listgetat(currentTree,listlen(currentTree))
				//console.log('currentParent: ' + currentParent);
				//console.log('i am ' + allRows[x].style.display + ' and we are going to ' + action);
				
				// if we are one level down from the clicked element, set the hidden form field appropriately.
				if ( currentParent == theID ) {
					
					if ( action == 'hide' ) {
						currentVisibleField.value = 'no'
					} else {
						currentVisibleField.value = 'yes'
					}	
					
				}
				
				//console.log(currentVisibleField.value);
				//THIS IS WHERE WE RUN INTO TROUBLE
				// since the clicked row exists in this row's parentTree, hide it
				if ( action == 'hide' ) {
					allRows[x].style.display = 'none';
				} 
				//only reveal this if it is the first tree branch, or if the last state is yes
				else if ( currentParent == theID || currentVisibleField.value == 'yes' ) {
					allRows[x].style.display='';
				}
				
			}
			
		}
	}
	
	//console.log('process the icon');
	if (action == 'hide') {
		showImage.style.display = '';
		hideImage.style.display = 'none';
	} else {
		showImage.style.display = 'none';
		hideImage.style.display = '';
	}
	
	colorTable( theTable );
}

function highlightRow( myId ) {
	/*var oldClass = document.getElementById(myId).className
	document.getElementById(myId).className = 'dataHover';
	document.getElementById(myId).onmouseout = function() { 
		document.getElementById(myId).className = oldClass;
	}*/
	document.getElementById(myId).style.backgroundColor = '#f5d89f';
}

function unHighlightRow( myId ) {
	/*var oldClass = document.getElementById(myId).className
	document.getElementById(myId).className = 'dataHover';
	document.getElementById(myId).onmouseout = function() { 
		document.getElementById(myId).className = oldClass;
	}*/
	document.getElementById(myId).style.backgroundColor = '';
}

// This function will allow filtering of a table
function filter3 (phrase, _id){
	// Define default vars
	var words = phrase.value.toLowerCase().split(" ");
	var table = document.getElementById(_id);
	var ele;
	var rowCount = 1;
	alert(table);
	// loop through the rows of the table
	for (var r = 1; r < table.rows.length; r++){
		ele = table.rows[r].innerHTML.replace(/<[^>]+>/g,""); // Eliminate bad characters and HTML
		var displayStyle = 'none';
		var displayClass = '';
		// assign the id of the row to a variable
		var thisId = table.rows[r].id;
		// start a new array
		var currentId = new Array()
		// split the string into an array via '_'
		currentId = thisId.split('_');
		//var oppositeId = document.getElementById(currentId[0] + '_right_' + currentId[2]);
		// if the opposite table has a showing value, don't include it in the search
		//if ( document.getElementById(currentId[0] + '_right_' + currentId[2]) && document.getElementById(currentId[0] + '_right_' + currentId[2]).style.display != '' ) {
			for (var i = 0; i < words.length; i++) {
				// If we have a match...
				if (ele.toLowerCase().indexOf(words[i])>=0) {
					rowCount++;
					displayStyle = '';
					displayClass = '';
					/*if(rowCount % 2 == 0){ 
						displayClass = 'dataEvenRow'; 
					} else { 
						displayClass = 'dataOddRow';
					}*/
				} else {
					displayStyle = 'none';
					displayClass = '';
					break;
				}
			}
			table.rows[r].style.display = displayStyle;
			table.rows[r].className = displayClass;
		//}
	}
	//slower
	colorTable (_id);
}

// Toggle Visibility
// Send the id you want to toggle visible or invisibie. optionally, you can also send the id of the image you want to swap
function toggleVisibility(theId,theImage) {
	
	if(!delimiters){var delimiters=','}

	_TempListSplitArray = theId.split(delimiters)
	
	for(i=0;i<_TempListSplitArray.length;i++){

		if ( document.getElementById(_TempListSplitArray[i]) ) {
			
			var theElement = document.getElementById(_TempListSplitArray[i])
		
			if ( theElement.style.display == "none") {
				
				theAction = 'show';
				theElement.style.display = "";
				
				// and the image
				if ( theImage ) {
					document.getElementById(theImage).src = "images/e.gif";
				}
				
			} else {
				
				theAction = 'hide';
				theElement.style.display = "none";
				
				// and the image
				if ( theImage ) {
					document.getElementById(theImage).src = "images/c.gif";
				}
			
			}
			
		}
		
	}
}

function advancedSearchCheck ( theDiv ) {
	if ( document.getElementById('advancedSearch').checked == true ) {
		document.getElementById(theDiv).style.display='';
	} else {
		document.getElementById(theDiv).style.display='none';
	}
}

// Toggle Visibility from a checkbox
function toggleVisibilityCheckbox(theTarget,theCheckbox,ifChecked) {
	if (!ifChecked) ifChecked = 'show'
	if (theCheckbox.checked) {
		if (ifChecked == 'show') {
			document.getElementById(theTarget).style.display=""; 
		}else{
			document.getElementById(theTarget).style.display="none"; 
		}
	} else {
		if (ifChecked == 'show') {
			document.getElementById(theTarget).style.display="none"; 
		}else{
			document.getElementById(theTarget).style.display=""; 
		}
	}
}

// CREATE COOKIE

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

// PAGE INFO HIDE OR UNHIDE
function PageInfoProcess (theAction) {

	// if the action is 'hide'
	if ( theAction == 'hide' ) {
	
		// hide the id
		document.getElementById('infoTable').style.display = 'none';
		// show the minimized ID
		document.getElementById('infoTableMinimized').style.display = '';
		// set a cookie
		createCookie('SHOWINFOTABLE','no',365);
		
	// else show it	
	} else {
	
		// show the id
		document.getElementById('infoTable').style.display = '';
		// hide the minimized ID
		document.getElementById('infoTableMinimized').style.display = 'none';
		// set a cookie
		createCookie('SHOWINFOTABLE','yes',365);
	
	}

}

// Stop Enter Key Script. Taken From: http://www.webcheatsheet.com/javascript/disable_enter_key.php
function stopRKey(evt) { 
  var evt = (evt) ? evt : ((event) ? event : null); 
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null); 
  if ((evt.keyCode == 13) && (node.type=="text"))  {return false;} 
} 

// javascript imageResizer
function resizeThisImage(theImage,theSize) {
	var myImage = document.getElementById(theImage)
	var tempImage = new Image;
	tempImage.src = myImage.src
	if (tempImage.width > theSize) {
			myImage.width = theSize;
		}
}

// Confirms whether something in a select box is going to be deleted. Used in content_editor links files, etc.
function ConfirmIfDelete(theSelectBox) {
										
	var selectedValue = theSelectBox.options[theSelectBox.selectedIndex].value;
	
	if ( selectedValue == 'delete' ) {
		
		var answer = confirm("Deleting this item will permanently delete all related tracking data in the database." + '\n' + 
		"You may want to deactivating this item instead." + '\n' + 
		"Are you sure you want to proceed?");
		
		if (!answer) {
			theSelectBox.selectedIndex = 0;
		} 
		
	}
	
}

// find position X (from http://blog.firetree.net/2005/07/04/javascript-find-position/)
function findPosX(obj)
  {
    var curleft = 0;
    if(obj.offsetParent)
        while(1) 
        {
          curleft += obj.offsetLeft;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.x)
        curleft += obj.x;
    return curleft;
  }


// find position Y (from http://blog.firetree.net/2005/07/04/javascript-find-position/)
function findPosY(obj)
  {
    var curtop = 0;
    if(obj.offsetParent)
        while(1)
        {
          curtop += obj.offsetTop;
          if(!obj.offsetParent)
            break;
          obj = obj.offsetParent;
        }
    else if(obj.y)
        curtop += obj.y;
    return curtop;
  }
  
// dump function
function dump(arr,level) {
	
	var dumped_text = "";
	if(!level) level = 0;
	
	//The padding given at the beginning of the line.
	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";
	
	if(typeof(arr) == 'object') { //Array/Hashes/Objects 
		for(var item in arr) {
			var value = arr[item];
			
			if(typeof(value) == 'object') { //If it is an array,
				dumped_text += level_padding + "'" + item + "' ...\n";
				dumped_text += dump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
			}
		}
	} else { //Stings/Chars/Numbers etc.
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	return dumped_text;
}

// CANCEL JAVASCRIPT Bubbling (http://www.quirksmode.org/js/events_order.html)
function cancelEvent(e) {
e = e || window.event;
if (e.stopPropagation) e.stopPropagation();
e.cancelBubble = true;
return false;

}

// JSON2STRING
function json2string(strObject) {
 var c, i, l, s = '', v, p; 

 switch (typeof strObject) {
 case 'object':
  if (strObject) {
   if (strObject.length && typeof strObject.length == 'number') {
	for (i = 0; i < strObject.length; ++i) {
	 v = json2string(strObject[i]);
	 if (s) {
	  s += ',';
	 }
	 s += v;
	}
	return '[' + s + ']';
   } else if (typeof strObject.toString != 'undefined') {
	for (i in strObject) {
	 v = strObject[i];
	 if (typeof v != 'undefined' && typeof v != 'function') {
	  v = json2string(v);
	  if (s) {
	   s += ',';
	  }
	  s += json2string(i) + ':' + v;
	 }
	}
	return '{' + s + '}';
   }
  }
  return 'null';
 case 'number':
  return isFinite(strObject) ? String(strObject) : 'null';
 case 'string':
  l = strObject.length;
  s = '"';
  for (i = 0; i < l; i += 1) {
   c = strObject.charAt(i);
   if (c >= ' ') {
	if (c == '\\' || c == '"') {
	 s += '\\';
	}
	s += c;
   } else {
	switch (c) {
	 case '\b':
	  s += '\\b';
	  break;
	 case '\f':
	  s += '\\f';
	  break;
	 case '\n':
	  s += '\\n';
	  break;
	 case '\r':
	  s += '\\r';
	  break;
	 case '\t':
	  s += '\\t';
	  break;
	 default:
	  c = c.charCodeAt();
	  s += '\\u00' + Math.floor(c / 16).toString(16) +
	   (c % 16).toString(16);
	}
   }
  }
  return s + '"';
 case 'boolean':
  return String(strObject);
 default:
  return 'null';
 }
}


// console simulator 
if (typeof console == "undefined") var console = { log: function() {} };

// global trim function 
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}


