/**
* Common client javascript library
*
* see http://www.javascripttoolbox.com/bestpractices/
*
* Organized by sections:
*  cookies
*  formating   
*  navigation
*  pageinit
*  printing
*  utf8
*  wiki
*  ajax
*/


/**
* section: controls
*/

/**
* Returns array of checkboxes that are children of objCheckbox. 
* Checkboxes identify their parent with checkboxParent custom attribute.
* Checkboxes identify themselves as parents with jwCheckboxChildren custom attribute.
*/
function getCheckboxChildren(objCheckbox)
{
   var aChildren = new Array();

   strChildren = objCheckbox.getAttribute('jwCheckboxChildren');
   if(strChildren != null && strChildren != '0')
   {
      var aInputs = document.getElementsByTagName("input");
      for(var i=0; i<aInputs.length; i++)
      {
         if(aInputs[i].type == 'checkbox' &&  aInputs[i].getAttribute('jwCheckboxParent') == objCheckbox.id)
            aChildren.push(aInputs[i]);
      }
   }
   
   return aChildren;
}


/**
* Returns parent checkbox of objCheckbox. 
* Checkboxes identify their parent with jwCheckboxParent custom attribute.
*/
function getCheckboxParent(objCheckbox)
{
   strParent = objCheckbox.getAttribute('jwCheckboxParent');
   return (strParent != null && strParent != '') ? document.getElementById(strParent) : null;
}


/**
* Refresh checked state of a checkbox tree from objCheckbox's reference. 
*/
function refreshCheckboxTree(objCheckbox)
{
   refreshCheckboxTreeParent(objCheckbox);
   refreshCheckboxTreeChildren(objCheckbox);
}


/**
* Refresh checked state of objCheckbox's parent checkboxes. 
*/
function refreshCheckboxTreeParent(objCheckbox)
{
   objParent = getCheckboxParent(objCheckbox);
   if(objParent == null)
      return;

   var blChecked = true;
   var aChildren = getCheckboxChildren(objParent);
   for(var i=0; i<aChildren.length; i++)
   {
      if(!aChildren[i].checked)
      {
         blChecked = false;
         break;
      }         
   }   
   objParent.checked = blChecked;

   refreshCheckboxTreeParent(objParent);
}   
   
   
/**
* Refresh checked state of objCheckbox's children checkboxes. 
*/
function refreshCheckboxTreeChildren(objCheckbox)
{
   var aChildren = getCheckboxChildren(objCheckbox);

   for(var i=0; i<aChildren.length; i++)
   {
      aChildren[i].checked = objCheckbox.checked;

      refreshCheckboxTreeChildren(aChildren[i]);
   }
}   


/**
* set the class and status bar text on a page element
*/
function setObjClass(objElement, strClass, strStatusText)
{
   window.status = strStatusText;
   objElement.className = strClass;
}


/**
* Toggle display of a tree node when +/- image is clicked
*/
function toggleTreeNode(strNodeID) 
{
   if(!document.getElementById) 
      return;

   var strImageID = "img" + strNodeID;
   var strDivID = "div" + strNodeID;
   var objImage = document.getElementById(strImageID);
   var objDiv = document.getElementById(strDivID);

   if(objImage && objDiv)
   {
      if(objDiv.style.display == "")
      {   
         objDiv.style.display = "none";
         objImage.src = "images/tree-plus.gif";
      }
      else
      {   
         objDiv.style.display = "";
         objImage.src = "images/tree-minus.gif";
      }
   }
}


/**
* section: cookies
*/

/**
*  Deletes cookie by setting past expire time
*/
function deleteCookie(strName, strPath, strDomain)
{
   if (getCookie(strName))
      document.cookie = escape(strName) + "="
                      + ((strPath) ? ";path=" + strPath : "")
                      + ((strDomain) ? ";domain=" + strDomain : "")
                      + ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}


/**
*  Retrieves cookie
*/
function getCookie(strName)
{
   var strCookie = unescape(document.cookie.replace(/\+/g, " "));

   var intStart = strCookie.indexOf(strName + "=");
   var intLen = intStart + strName.length + 1;

   if (!intStart && strName != strCookie.substring(0, strName.length) )
      return "";

   if (intStart == -1)
      return "";

   var intEnd = strCookie.indexOf("; ", intLen);

   if (intEnd == -1)
      intEnd = strCookie.length;

   return utf8Decode(strCookie.substring(intLen, intEnd));
}


/**
* Sets cookie value.
* Must set w/same defaults as server-side equivalent to avoid duplicate cookes.
*/
function setCookie(strName, strValue, dtmExpires, strPath, strDomain, strSecure)
{
   document.cookie = escape(strName) + "=" + escape(strValue)
                   + ((dtmExpires) ? ";expires=" + dtmExpires.toGMTString() : "")
                   + ((strPath) ? ";path=" + strPath : ";path=/")
                   + ((strDomain) ? ";domain=" + strDomain : "")
                   + ((strSecure) ? ";secure" : "");
}


/**
* section: formating
*/

/**
* decodes common HTML entities
*/
function decodeHTMLEntities(strVal)
{
   strVal = strVal.replace("&nbsp;", " "); // unicode non-breaking space
   strVal = strVal.replace("&quot;", "\"");
   strVal = strVal.replace("&lt;", "<");
   strVal = strVal.replace("&gt;", ">");
   return strVal;
}


/**
* Enclose selected text from a text/textarea (strInputID) 
* input between strPrefix & strSuffix
*/
function encloseSelection(strInputID, strPrefix, strSuffix) 
{
   if(!document.getElementById) 
      return;

   var objInput = document.getElementById(strInputID);
   if(!objInput)
      return;
      
   objInput.focus();
   
   if(typeof(document["selection"]) != "undefined")
   {
      var strSel = document.selection.createRange().text;
   }
   else if(typeof(objInput["setSelectionRange"]) != "undefined")
   {
      var intStart = objInput.selectionStart;
      var intEnd = objInput.selectionEnd;
      var scrollPos = objInput.scrollTop;
      var strSel = objInput.value.substring(intStart, intEnd);
   }

   if(strSel.match(/ $/)) 
   { 
      strSel = strSel.replace(/ $/, "");
      strSuffix = strSuffix + " ";
   }
   
   var strSub = strPrefix + strSel + strSuffix;

   if(typeof(document["selection"]) != "undefined")
   {
      document.selection.createRange().text = strSub;
   }
   else if(typeof(objInput["setSelectionRange"]) != "undefined")
   {
      objInput.value = objInput.value.substring(0, intStart) + strSub +
                       objInput.value.substring(intEnd);
                       
      objInput.scrollTop = scrollPos;
      if(strSel) 
         objInput.setSelectionRange(intStart + strSub.length, intStart + strSub.length);
      else
         objInput.setSelectionRange(intStart + strPrefix.length, intStart + strPrefix.length);
   }

   objInput.focus();
}


/**
* section: navigation
*/

/**
* sets new language cooke and refreshes page in new language 
* with specified URL
*/
function changeSiteLanguage(strCookie, strLangCode, strRefreshURL)
{
   var now = new Date();
   now.setTime(now.getTime() + 1000 * 60 * 60 * 24 * 365);
   setCookie(strCookie, strLangCode, now);

   //make form to submit the refresh URL with the new cookie value
   var strForm = "frm" + strCookie + strLangCode;
   if(!document.forms[strForm] )
   {
      var objForm = document.createElement("form");
      objForm.id = strForm;
      objForm.method = "post";
      objForm.action = strRefreshURL;
      objForm.acceptCharset = "utf-8";
      document.body.appendChild(objForm);
   }

   //submit the form
   document.forms[strForm].submit();
}


/**
* Shows confirm message box. Call submitAction() if confirmed.
*/
function confirmSubmitAction(strConfirm, strForm, strAction)
{
   if (confirm(decodeHTMLEntities(strConfirm))) 
      submitAction(strForm, strAction); 
}


/**
* open general popup window
*/
function openPopup(strURL, intWidth, intHeight)
{
   return window.open(strURL, 'objPopup', 'width=' + intWidth + ',height=' + intHeight + ',top=50,left=50,resizable=yes,scrollbars=yes');
}


/**
* Shows a "Please Wait. Processing..." message box and disables the specified 
* button object.
*/
function showProcessingMessage(objButton)
{
   if(!document.getElementById) 
      return;

   objButton.disabled = true;

   var objDiv = document.getElementById("msgProcessing");  
   if(objDiv)
      objDiv.style.display='block';
}


/**
* set value of txtAction, submit form
*/
function submitAction(strForm, strAction)
{
   if(document.forms[strForm])
   {
      if(document.forms[strForm].elements["txtAction"])
      {
         document.forms[strForm].elements["txtAction"].value = strAction;   
         document.forms[strForm].submit();
      }   
   }
}


/**
* submit form with a paged list navigation action
*/
function submitListPage(intPage, strForm, strAction)
{
   if(document.forms[strForm])
   {
      if(document.forms[strForm].elements["txtListPage"])
      {
         document.forms[strForm].elements["txtListPage"].value = intPage;
         submitAction(strForm, strAction);
      }
   }
}


/**
* section: pageinit
*/

/**
* things done on every page initialization
*/
function initPage(setform)
{
   if(window.appInitPage)
      appInitPage();

   pageHeight();
   placeCursor();
   isJScriptEnabled();
   if (!setform){
   setupform(); }
  // include('scripts/refresh.js');
  setRefreshTimer();  
  refreshclock();
  clock()
}

function setRefreshTimer(){
	setInterval("refreshclock()", 100000);
}

/**
These two are for the clock and calendar
*/
function refreshclock() {
xmlHttpRefresh=GetXmlHttpObjectRefresh()
var url='scripts/refresh.asp';
url=url+"?sid="+Math.random();
xmlHttpRefresh.onreadystatechange=stateChangedRefresh;
xmlHttpRefresh.open("GET",url,true);
xmlHttpRefresh.send(null);
} 


function clock() {
var digital = new Date();
var hours = digital.getHours();
var minutes = digital.getMinutes();
var seconds = digital.getSeconds();
var amOrPm = "AM";
if (hours > 11) amOrPm = "PM";
if (hours > 12) hours = hours - 12;
if (hours == 0) hours = 12;
if (minutes <= 9) minutes = "0" + minutes;
if (seconds <= 9) seconds = "0" + seconds;
dispTime = displayDate()+' '+hours + ":" + minutes + ":" + seconds + " " + amOrPm;
document.getElementById('clockdiv').innerHTML = dispTime;
setTimeout("clock()", 1000);
}

function displayDate() {
  var now = new Date();
  var today = now.getDate();
  var month = now.getMonth();
    var monthName = new Array(12)
      monthName[0]="January ";
      monthName[1]="February ";
      monthName[2]="March ";
      monthName[3]="April ";
      monthName[4]="May ";
      monthName[5]="June ";
      monthName[6]="July ";
      monthName[7]="August ";
      monthName[8]="September ";
      monthName[9]="October ";
      monthName[10]="November ";
      monthName[11]="December ";
  var year = now.getFullYear();

  return monthName[month]+today+ ", "+year
}


function stateChangedRefresh() 
{   
if (xmlHttpRefresh.readyState==4)
{ 
i=1;//document.getElementById('clockdiv').innerHTML=xmlHttpRefresh.responseText;
}}


function GetXmlHttpObjectRefresh()
{
var xmlHttpRefresh=null;
try
  {
  // Firefox, Opera 8.0+, Safari
  xmlHttpRefresh=new XMLHttpRequest();
  }
catch (e)
  {
  // Internet Explorer
  try
    {
    xmlHttpRefresh=new ActiveXObject("Msxml2.XMLHTTP");
    }
  catch (e)
    {
    xmlHttpRefresh=new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
return xmlHttpRefresh;
}
/** 
* set initial page height
*/
function pageHeight()
{
   if(!document.getElementById) 
      return;

   var frame = document.getElementById("wrap");  /* wrapper ID */
   var htmlheight = document.body.parentNode.scrollHeight;  
   var windowheight = window.innerHeight;
   if (frame) 
   {
      if (htmlheight < windowheight) 
      { 
         document.body.style.height = windowheight + "px"; 
         frame.style.height = windowheight + "px"; 
      }  
      else 
      { 
         document.body.style.height = htmlheight + "px"; 
         frame.style.minHeight = htmlheight + "px"; 
      }
   }  
}


/**
* is the form element able to receive focus?
*/
function isFocusable(objElement) 
{
   if(objElement.type == null || objElement.disabled || objElement.style.display == "none")
      return false;

   strType = objElement.type;
   if (strType != "text" && strType != "textarea" && strType != "password" && 
       strType != "radio" && strType != "checkbox" && strType != "reset" && 
       strType != "select-multiple" && strType != "select-one") 
      return false;

   return true;  
}


/**
* does browser have jscript enabled?
*/
function isJScriptEnabled()
{
   if (!document.getElementById) 
      return;

   var objElement = document.getElementById("txtIsJScript");
   if(objElement)
      objElement.value = "1";

   var objElement = document.getElementById("JScriptEnabled");
   if(objElement)
      objElement.style.display = "none";
}


/**
* set focus on first editable form input, or input named in 
* optional txtSetFocus hidden input 
*/
function placeCursor() 
{
   if(!document.getElementById) 
      return;
      
   if (document.forms.length < 1)
      return;
         
   self.focus();
   var objElement = document.getElementById("txtSetFocus");
   if(objElement)
   {
      document.getElementById(objElement.value).focus();
      return;               
   }
 
   objElements = document.forms[0].elements;
   for(i=0; i< objElements.length; i++)
   {
      if (!isFocusable(objElements.item(i))) 
         continue;

      objElements.item(i).focus();
      return;               
   }
}


/**
* section: printing
*/

/**
* prints page contents
*/
function printPage() 
{
   if(window.print) 
      window.print();
   else 
   {     
      // mstrNoPrintSupport should already be set by pagebuilder.php
      if(!mstrNoPrintSupport) 
         mstrNoPrintSupport = "Your browser doesn't support this feature. Please use File/Print.";
      alert(mstrNoPrintSupport);
   }
}


/**
* section: utf8
*/

/**
* decodes string with encoded utf8 characters (ex: %C3) to actual utf8 charcaters
*/
function utf8Decode(utftext) 
{
   var string = "";
   var i = 0;
   var c = c1 = c2 = 0;

   while ( i < utftext.length ) 
   {
      c = utftext.charCodeAt(i);

      if (c < 128) 
      {
          string += String.fromCharCode(c);
          i++;
      }
      else if((c > 191) && (c < 224)) 
      {
          c2 = utftext.charCodeAt(i+1);
          string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
          i += 2;
      }
      else
      {
          c2 = utftext.charCodeAt(i+1);
          c3 = utftext.charCodeAt(i+2);
          string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
          i += 3;
      }

   }

   return string;
}


/**
* encodes string with actual utf8 characters to encoded utf8 characters (ex: %C3)
*/
function utf8Encode(string) 
{
   string = string.replace(/\r\n/g,"\n");
   var utftext = "";

   for (var n = 0; n < string.length; n++) 
   {
      var c = string.charCodeAt(n);

      if (c < 128) 
      {
          utftext += String.fromCharCode(c);
      }
      else if((c > 127) && (c < 2048)) 
      {
          utftext += String.fromCharCode((c >> 6) | 192);
          utftext += String.fromCharCode((c & 63) | 128);
      }
      else 
      {
          utftext += String.fromCharCode((c >> 12) | 224);
          utftext += String.fromCharCode(((c >> 6) & 63) | 128);
          utftext += String.fromCharCode((c & 63) | 128);
      }

   }

   return utftext;
}


/**
* section: wiki
*/

/**
* open popup window with wiki preview of the value in strPreviewInput 
*/
function popupWikiPreview(strURL, strPreviewInput)
{
   if (!document.getElementById) 
      return;

   //make form if doesn't yet exist in document
   if(!document.forms["frmWikiPreview"])
   {
      var objForm = document.createElement("form");
      objForm.id = "frmWikiPreview";
      objForm.method = "post";
      objForm.action = strURL;
      objForm.target = "wikiPreview";
      objForm.acceptCharset = "utf-8";
      var objInput = document.createElement("input");
      objInput.type = "hidden";
      objInput.id = objInput.name = "txtWikiPreview";
      objForm.appendChild(objInput);
      document.body.appendChild(objForm);
   }

   //copy value of desired input to preview forms hidden input
   var objPreviewInput = document.getElementById(strPreviewInput);
   document.forms["frmWikiPreview"].elements["txtWikiPreview"].value = objPreviewInput.value;
   
   //open the popup
   if(window.objWin)
      window.objWin.close()         //forces focus - .focus() did not work
   window.objWin = window.open("", 'wikiPreview', 'width=700,height=500,top=50,left=50,resizable=yes,scrollbars=yes');
   
    //submit the preview
   document.forms["frmWikiPreview"].submit();
}

function bf(ele){
ele.style.background = "#ffe2ca";
}

function bb(ele){
ele.style.background = "#ffffff";
} 

var changesmade=false
function sr(){
	changesmade=true;
	if(document.getElementById('SaveCallDetailsT')){document.getElementById('SaveCallDetailsT').style.visibility='visible'}
	if(document.getElementById('SaveCallDetailsB')){document.getElementById('SaveCallDetailsB').style.visibility='visible'}
	if(document.getElementById('SaveCallDetailsT')){document.getElementById('SaveCallDetailsT').style.display='block'}
	if(document.getElementById('SaveCallDetailsB')){document.getElementById('SaveCallDetailsB').style.display='block'}
}

function cr(){
	changesmade=false;
}

function checkgoodbye(){
	if (changesmade){goodbye()}
}

function goodbye(e) {
	if(!e) e = window.event;
	//e.cancelBubble is supported by IE - this will kill the bubbling process.
	e.cancelBubble = true;
	e.returnValue = 'Changes have been made to this form\nIf you leave without saving them they will be lost forever'; //This is displayed on the dialog

	//e.stopPropagation works in Firefox.
	if (e.stopPropagation) {
		e.stopPropagation();
		e.preventDefault();
	}
}
window.onbeforeunload=checkgoodbye;


function setupform() { 
if(document.forms[0]){
var elem = document.forms[0].elements;
for(var i = 0; i < elem.length; i++)
if (!(elem[i].type=='submit')){
//elem[i].onchange = sr;
addEvent(elem[i],'change',sr)
}
}
}



// capture the onsubmit event on all forms
//addEvent(document.getElementById('form1'),'submit', newsubmit);
function addEvent( obj, type, fn ) {
  if ( obj.attachEvent ) {
    obj['e'+type+fn] = fn;
    obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
    obj.attachEvent( 'on'+type, obj[type+fn] );
  } else
    obj.addEventListener( type, fn, false );
}

function removeEvent( obj, type, fn ) {
  if ( obj.detachEvent ) {
    obj.detachEvent( 'on'+type, obj[type+fn] );
    obj[type+fn] = null;
  } else
    obj.removeEventListener( type, fn, false );
}

function include(filename)
{
	var head = document.getElementsByTagName('head')[0];
	
	script = document.createElement('script');
	script.src = filename;
	script.type = 'text/javascript';
	
	head.appendChild(script)
}

function ce(user,host,elink){
if (!elink){elink = user + "@" + host;} 
var hlink = "<a hre" + "f=ma" + "ilto:" + user + "@" + host + ">" + elink + "</a>"
return hlink
}
