/*	REVIEW yss\_global\fcn_libraries\fcn_js_functions.js


		Author:	Matthew VanderMeer, mlvander@healthy.uwaterloo.ca
		
		Filename:	common_scripts.js
		
		Purpose:	These are common javascript functions that are used throughout most apps.




*/

// This is for the navigation drop down menus
var timeout    = 200;
var closetimer = 0;
var ddmenuitem = 0;
 
function topnav_open()
{  topnav_canceltimer();
   topnav_close();
   ddmenuitem = $(this).find('ul').css('visibility', 'visible');}
 
function topnav_close()
{  if(ddmenuitem) ddmenuitem.css('visibility', 'hidden');}
 
function topnav_timer()
{  closetimer = window.setTimeout(topnav_close, timeout);}
 
function topnav_canceltimer()
{  if(closetimer)
   {  window.clearTimeout(closetimer);
      closetimer = null;}}
 
$(document).ready(function()
{  $('#nav_top > li').bind('mouseover', topnav_open)
   $('#nav_top > li').bind('mouseout',  topnav_timer)});
 
document.onclick = topnav_close;


/*  THIS IS FOR THE CF AJAX */
function loadInfo(functionname,var1,var2,var3,var4,var5,var6,var7,var8)
{
	DWREngine._execute(_cfscriptLocation, null, functionname, var1, var2, var3, var4, var5, var6, var7, var8, getResult);
}

function getResult(result)
{	
	document.getElementById(thisID).innerHTML = result;
}


function handleKeyPress(e)
{	var KeyID = (window.event) ? event.keyCode : e.keyCode;
	document.processkeystroke=true;
	if (KeyID==13)
		{	document.processkeystroke=false;	}
}

function disableLinks() 
{
    var anchors = document.body.getElementsByTagName('a');
 
    for (var i=0, end=anchors.length; i<end; i++) 
		{
     		 anchors[i].onclick = function() 
			  	{	return false;	};
	    }
}

function dsp_bcard()
{
	if (document.form.bcard_formalname.value!='')
		{	document.getElementById('bcard_name').innerHTML = document.form.bcard_formalname.value	}
	else
		{	document.getElementById('bcard_name').innerHTML = document.form.firstname.value + ' ' + document.form.lastname.value	}
		
	if (document.form.bcard_designation.value!='')
		{	document.getElementById('bcard_designation').innerHTML = ', ' + document.form.bcard_designation.value;	}
	else
		{	document.getElementById('bcard_designation').innerHTML = ''	}
		
	document.getElementById('bcard_title').innerHTML = document.form.bcard_title.value;
	document.getElementById('bcard_affiliation').innerHTML = document.form.bcard_affiliation.value;
	
	if (document.form.bcard_inc_fax.value=='Yes')
		{	var tel = "<span class='telfax'>TEL. </span>"
			var fax = "<span class='telfax'>FAX. </span>"	
		}
	else 
		{	var tel = ''
			var fax = ''	
		}
	
	var myphone = tel + document.form.phone.value.substring(0,3) + '-' 
						+ document.form.phone.value.substring(3,6) + '-' 
						+ document.form.phone.value.substring(6,10);
		
	var myfax = fax + document.form.fax.value.substring(0,3) + '-' 
						+ document.form.fax.value.substring(3,6) + '-' 
						+ document.form.fax.value.substring(6,10);
	
	if(document.form.phone.value!='')
		{
			if(document.form.phone_ext.value!='')
				{	document.getElementById('bcard_phone').innerHTML = myphone + ' x' + document.form.phone_ext.value; }
			else
				{	document.getElementById('bcard_phone').innerHTML = myphone	}
		}
	else
		{	document.getElementById('bcard_phone').innerHTML = ''	}
	
	if(document.form.fax.value!='')
		{
			if (document.form.bcard_inc_fax.value=='Yes')
				{	document.getElementById('bcard_fax').innerHTML = myfax	}
			else
				{	document.getElementById('bcard_fax').innerHTML = ''	}
		}
	else
		{	document.getElementById('bcard_fax').innerHTML = ''	}
		
		
	document.getElementById('bcard_email').innerHTML = document.form.email.value;
	
}

function isdefined( variable)
{
    return (typeof(window[variable]) == "undefined")?  false: true;
}

var highlight_bknd ='#DEDBDE';
var highlight_text ='#000000';
var normal_bknd = '#FFFFFF';
var normal_text = '#000000';

function glb_select_all(field,value,colorchange)
	{	

		var theForm = document.form.elements;
		var theField = theForm[field];
	
		if (theField.length>=1)
			{
				for (i=0;i<theField.length;i++)
					{	theField[i].checked=value
					
						if(colorchange==true && value==false)
							{	document.getElementById(field+i).style.background=normal_bknd;
								document.getElementById(field+i).style.color=normal_text;
							}
						else if (colorchange==true && value==true)
							{	document.getElementById(field+i).style.background=highlight_bknd;
								document.getElementById(field+i).style.color=highlight_text;
							}
					}
			}
		else
			{	theField.checked=value

				if(colorchange==true && value==false)
					{	document.getElementById(field+'0').style.background=normal_bknd;
						document.getElementById(field+'0').style.color=normal_text;
					}
				else if (colorchange==true && value==true)
					{	document.getElementById(field+'0').style.background=highlight_bknd;
						document.getElementById(field+'0').style.color=highlight_text;
					}
			}
	}

function glb_select_user(field,number,doall)
	{
		var theForm = document.form.elements;
		var theField = theForm[field];

		if (theField.length>=1)
			{
				var thisField = theForm[field][number];
			}
		else
			{	
				var thisField = theForm[field];
			}

		if (thisField.checked==true)
			{	
				thisField.checked=false;
				document.getElementById(field + number).style.background=normal_bknd;
				document.getElementById(field + number).style.color=normal_text;
			}
		else
			{	
				thisField.checked=true;
				document.getElementById(field + number).style.background=highlight_bknd;
				document.getElementById(field + number).style.color=highlight_text;
			}
	}

function glb_onmouse_highlight(ID)
	{	document.getElementById(ID).style.background=highlight_bknd;
		document.getElementById(ID).style.color=highlight_text;
	}
function glb_mouseout_unhighlight(ID)
	{	document.getElementById(ID).style.background=normal_bknd;
		document.getElementById(ID).style.color=normal_text;
	}
function glb_confirm_save()
	{
		if(document.form.formfieldupdate.value=='true')
		   	{	
			 	return_value = false;
				alert("You have changed the details on this form and you have not saved your changes.  Please save your changes before continuing.");	
			}
	}


function glb_hide_show(section,items)
	{
		for (var x = 1; x <= items; x++)
		   {
			var section_to_toggle=document.getElementById(section+x);

			if(section_to_toggle.style.display=="none")
				{
				$('#'+section+x).show('slow');
				} 
			else 
				{
				$('#'+section+x).hide('slow');
				}
		   }
	}

function toggle(section)
	{
		var section_to_toggle=document.getElementById(section);

		if(section_to_toggle.style.display=="none")
			{
			section_to_toggle.style.display="block"
			} 
		else 
			{
			section_to_toggle.style.display="none"
			}
	}

function jquery_toggle(section,items)
	{
		for (var x = 1; x <= items; x++)
		   {
			var section_to_toggle=document.getElementById(section+x);

			if(section_to_toggle.style.display=="none")
				{
				$('#'+section+x).show('slow');
				} 
			else 
				{
				$('#'+section+x).hide('slow');
				}
		   }
	}


function glb_confirm_delete(item_to_delete)
	{
		return_value = confirm("You are about to permanently delete the selected " + item_to_delete + ".\n\nThis action cannot be undone.\n\nClick 'OK' to confirm and continue, 'Cancel' to go back.");
	}

function glb_update_details(url)
	{
	test = confirm("You have chosen to match and register this person.  \nDo you want to update the information this person information to the information that they have provided in there registration?.\n\nClick 'OK' to update details for this person\nClick 'CANCEL' to match and register without updatding details");
	
	window.location= url + '&overwrite=' + test;
	}	


function glb_confirm_update()
	{	
		return_value = confirm("You are about to overwrite the details of this user with the information provided in thier registration.\n\nIf this i correct click 'OK', if this in in error please click 'CANCEL'.")
	}
// Auto tab for pre-defined fields like phone numbers //
function autotab(original,destination)
	{
		var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		if (keyCode != 9)
			{
				if (original.getAttribute&&original.value.length==original.getAttribute("maxlength"))
					{
					destination.select();
					}
			}
	}

function MM_openBrWindow(theURL,winName,features) 
	{
		windowName = window.open(theURL,winName,features);
		windowName.focus(); // this brings new window to front--->
	}

function openWindow(theURL,winName,features) 
	{
		windowName = window.open(theURL,winName,features);
		windowName.focus(); // this brings new window to front--->
	}
/**/
function openHelpWindow(theURL)
	{	
		windowName = window.open(theURL,'help','width=300,height=400,toolbar=no,location=no,status=yes,menubar=no, scrollbars=yes,resizable=yes');
		windowName.focus(); // this brings new window to front--->
	}
	
function openMailinglabel(level,id)
	{	
		windowName = window.open('yss.uwaterloo.ca/yss10/dynamicdoc_app/view/dsp_mailinglabel_maker.cfm?labeltype='+level+'&labelID='+id,'help','width=500,height=550,toolbar=no,location=no,status=yes,menubar=no, scrollbars=yes,resizable=yes');
		windowName.focus(); // this brings new window to front--->
	}


function getRefToDivMod( divID, oDoc ) {
  if( !oDoc ) { oDoc = document; }
  if( document.layers ) {
    if( oDoc.layers[divID] ) { return oDoc.layers[divID]; } else {
      for( var x = 0, y; !y && x < oDoc.layers.length; x++ ) {
        y = getRefToDivMod(divID,oDoc.layers[x].document); }
      return y; } }
  if( document.getElementById ) { return oDoc.getElementById(divID); }
  if( document.all ) { return oDoc.all[divID]; }
  return document[divID];
}

function resizeWinTo( idOfDiv ) {
  var oH = getRefToDivMod( idOfDiv ); if( !oH ) { return false; }
  var oW = oH.clip ? oH.clip.width : oH.offsetWidth;
  var oH = oH.clip ? oH.clip.height : oH.offsetHeight; if( !oH ) { return false; }
  var x = window; x.resizeTo( oW + 200, oH + 200 );
  var myW = 0, myH = 0, d = x.document.documentElement, b = x.document.body;
  if( x.innerWidth ) { myW = x.innerWidth; myH = x.innerHeight; }
  else if( d && d.clientWidth ) { myW = d.clientWidth; myH = d.clientHeight; }
  else if( b && b.clientWidth ) { myW = b.clientWidth; myH = b.clientHeight; }
  if( window.opera && !document.childNodes ) { myW += 16; }
  x.resizeTo( oW + ( ( oW + 200 ) - myW ), oH + ( (oH + 200 ) - myH ) );
}

  // position of the tooltip relative to the mouse in pixel //
  var offsetx = 12;
  var offsety =  -20;
  
function newelement(newid)
  { 
      if(document.createElement)
      { 
      var el = document.createElement('div'); 
      el.id = newid;     
      with(el.style)
      { 
      display = 'none';
      position = 'absolute';
      textAlign = 'left';
      } 
      el.innerHTML = '&nbsp;'; 
      document.body.appendChild(el); 
      } 
  } 
  var ie5 = (document.getElementById && document.all); 
  var ns6 = (document.getElementById && !document.all); 
  var ua = navigator.userAgent.toLowerCase();
  var isapple = (ua.indexOf('applewebkit') != -1 ? 1 : 0);
  
  function getmouseposition(e)
  {
      if(document.getElementById)
      {
      var iebody=(document.compatMode && 
    document.compatMode != 'BackCompat') ? 
     document.documentElement : document.body;
      pagex = (isapple == 1 ? 0:(ie5)?iebody.scrollLeft:window.pageXOffset);
      pagey = (isapple == 1 ? 0:(ie5)?iebody.scrollTop:window.pageYOffset);
      mousex = (ie5)?event.x:(ns6)?clientX = e.clientX:false;
      mousey = (ie5)?event.y:(ns6)?clientY = e.clientY:false;
  
      var lixlpixel_tooltip = document.getElementById('tooltip');
      lixlpixel_tooltip.style.left = (mousex+pagex+offsetx-50) + 'px';
      lixlpixel_tooltip.style.top = (mousey+pagey+offsety+5) + 'px';
      }
  }
  function tooltip(tip)
  {
      if(!document.getElementById('tooltip')) newelement('tooltip');
      var lixlpixel_tooltip = document.getElementById('tooltip');
      lixlpixel_tooltip.innerHTML = tip;
      lixlpixel_tooltip.style.display = 'block';
      document.onmousemove = getmouseposition;
  }
  function exit()
  {
      document.getElementById('tooltip').style.display = 'none';
  }
//end of tool tip



function addRowToTable(section,loopcount)
{

  var tbl = document.getElementById('arguments' + section);
  var lastRow = tbl.rows.length;
  // if there's no header row in the table, then iteration = lastRow + 1
  var iteration = lastRow;
  var row = tbl.insertRow(lastRow);

 document.getElementById('actioncell'+section+'_'+ loopcount).parentNode.deleteCell(3);

  var nextloop = loopcount + 1;

// left cell
  var cellLeft = row.insertCell(0);
  var el = document.createElement('input');
  el.type = 'text';
  el.name = 'content_argument' + section + '_' + nextloop;
  el.id = 'content_argument' + section + '_' + nextloop;
  el.size = 20;
  cellLeft.appendChild(el);
  
   // centre cell
  var cellCenter = row.insertCell(1);
  var textNode = document.createTextNode('=');
  cellCenter.appendChild(textNode);

  // right cell
  var cellRight = row.insertCell(2);
  var el = document.createElement('input');
  el.type = 'text';
  el.name = 'argument_value' + section + '_' + nextloop;
  el.id = 'argument_value' + section + '_' + nextloop;
  el.size = 20;
  cellRight.appendChild(el);
  
   // action cell
  var actionCell = row.insertCell(3);
  actionCell.setAttribute('onclick', 'addRowToTable('+section+','+ nextloop +')');
  actionCell.setAttribute('id', 'actioncell'+section+'_'+ nextloop);
  var textNode = document.createTextNode('[+]');
  actionCell.appendChild(textNode);
}

function display_content(section)
{	document.getElementById('staticcontent' + section).style.display="none";
	document.getElementById('dynamiccontent' + section).style.display="none";
	
	var theField = 'content_type' + section;
	var theFieldValue = document.getElementById(theField).value;
	if(theFieldValue!='')
		{	var thisid = theFieldValue + 'content' + section;
			document.getElementById(thisid).style.display="block";
		}
}

function check(field)
{	var theForm = document.thisform.elements;
	var theFieldvalue = theForm[field].value;


	if (theForm[field].value==1)
		{	document.getElementById(field + 'use').style.display="none";
			document.getElementById(field + 'nouse').style.display="inline";
		}
	if (theForm[field].value==0)
		{	document.getElementById(field + 'use').style.display="inline";
			document.getElementById(field + 'nouse').style.display="none";
		}
}
	
function checkBrowser()
{
	var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]
 
};
BrowserDetect.init();

alert('You\'re using ' + BrowserDetect.browser + ' ' + BrowserDetect.version + ' on ' + BrowserDetect.OS + '!');
}

function opentree()
{	openall('filetree_sections');
	openall('filetree_nav_level1');
}

function openall(id) 
{	
	var tree = document.getElementById(id);

	if (tree.hasChildNodes()) 
	{	// Get all children of node
		var children = tree.childNodes;
		 // Loop through the children
		for(var c=0; c < children.length; c++) 
			{	
				if(children[c].tagName=='DIV')
					{
						children[c].style.display='block';
					}
				if(children[c].tagName=='SPAN')
					{
						alert(children[c].id);
						if(children[c].style.display=='inline')
							{	children[c].style.display='none;';	}
						else
							{	children[c].style.display='inline;';	}
					}
			}
	 }
 }

/* =========================================================

// jquery.innerfade.js

// Datum: 2008-02-14
// Firma: Medienfreunde Hofmann & Baldes GbR
// Author: Torsten Baldes
// Mail: t.baldes@medienfreunde.com
// Web: http://medienfreunde.com

// based on the work of Matt Oakes http://portfolio.gizone.co.uk/applications/slideshow/
// and Ralf S. Engelschall http://trainofthoughts.org/

 *
 *  <ul id="news"> 
 *      <li>content 1</li>
 *      <li>content 2</li>
 *      <li>content 3</li>
 *  </ul>
 *  
 *  $('#news').innerfade({ 
 *	  animationtype: Type of animation 'fade' or 'slide' (Default: 'fade'), 
 *	  speed: Fading-/Sliding-Speed in milliseconds or keywords (slow, normal or fast) (Default: 'normal'), 
 *	  timeout: Time between the fades in milliseconds (Default: '2000'), 
 *	  type: Type of slideshow: 'sequence', 'random' or 'random_start' (Default: 'sequence'), 
 * 		containerheight: Height of the containing element in any css-height-value (Default: 'auto'),
 *	  runningclass: CSS-Class which the container get's applied (Default: 'innerfade'),
 *	  children: optional children selector (Default: null)
 *  }); 
 *

// ========================================================= */


(function($) {

    $.fn.innerfade = function(options) {
        return this.each(function() {   
            $.innerfade(this, options);
        });
    };

    $.innerfade = function(container, options) {
        var settings = {
        		'animationtype':    'fade',
            'speed':            'normal',
            'type':             'sequence',
            'timeout':          2000,
            'containerheight':  'auto',
            'runningclass':     'innerfade',
            'children':         null
        };
        if (options)
            $.extend(settings, options);
        if (settings.children === null)
            var elements = $(container).children();
        else
            var elements = $(container).children(settings.children);
        if (elements.length > 1) {
            $(container).css('position', 'relative').css('height', settings.containerheight).addClass(settings.runningclass);
            for (var i = 0; i < elements.length; i++) {
                $(elements[i]).css('z-index', String(elements.length-i)).css('position', 'absolute').hide();
            };
            if (settings.type == "sequence") {
                setTimeout(function() {
                    $.innerfade.next(elements, settings, 1, 0);
                }, settings.timeout);
                $(elements[0]).show();
            } else if (settings.type == "random") {
            		var last = Math.floor ( Math.random () * ( elements.length ) );
                setTimeout(function() {
                    do { 
												current = Math.floor ( Math.random ( ) * ( elements.length ) );
										} while (last == current );             
										$.innerfade.next(elements, settings, current, last);
                }, settings.timeout);
                $(elements[last]).show();
						} else if ( settings.type == 'random_start' ) {
								settings.type = 'sequence';
								var current = Math.floor ( Math.random () * ( elements.length ) );
								setTimeout(function(){
									$.innerfade.next(elements, settings, (current + 1) %  elements.length, current);
								}, settings.timeout);
								$(elements[current]).show();
						}	else {
							alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
						}
				}
    };

    $.innerfade.next = function(elements, settings, current, last) {
        if (settings.animationtype == 'slide') {
            $(elements[last]).slideUp(settings.speed);
            $(elements[current]).slideDown(settings.speed);
        } else if (settings.animationtype == 'fade') {
            $(elements[last]).fadeOut(settings.speed);
            $(elements[current]).fadeIn(settings.speed, function() {
							removeFilter($(this)[0]);
						});
        } else
            alert('Innerfade-animationtype must either be \'slide\' or \'fade\'');
        if (settings.type == "sequence") {
            if ((current + 1) < elements.length) {
                current = current + 1;
                last = current - 1;
            } else {
                current = 0;
                last = elements.length - 1;
            }
        } else if (settings.type == "random") {
            last = current;
            while (current == last)
                current = Math.floor(Math.random() * elements.length);
        } else
            alert('Innerfade-Type must either be \'sequence\', \'random\' or \'random_start\'');
        setTimeout((function() {
            $.innerfade.next(elements, settings, current, last);
        }), settings.timeout);
    };

})(jQuery);

// **** remove Opacity-Filter in ie ****
function removeFilter(element) {
	if(element.style.removeAttribute){
		element.style.removeAttribute('filter');
	}
}



