// -----------------------------------------------------------------------------
// Script:  MiLifeUtilities.js
// Project : NPD/5994 Imperative, Imperative Health Limited.
// Copyright ©2006 Imperative Health Limited. All rights reserved. 
//
// Description:
//	    Utility functions.
//   
// Modification History
//
//  Version		Date				By			Description
//  V1R1M0		09/11/2005			MORD		Created	
//	V1R1M1		24/11/2005			MALS		Added functions for string replacing
//												and HTML entity replacings
//  V1R1M2      07/02/2006          ADCS        Added findElementById(); findPosX() and findPosY().
//  V1R1M3      01/03/2006          ADCS        Cross-browser event listeners.
//  V1R1M4      06/12/2006          GROJ        Refactored from GetActiveUtilities.js to MiLifeUtilities.js
// -----------------------------------------------------------------------------

// -----------------------------------------------------------------------------
// Description: 
//		This is the script to take querystrings from the URL and convert them into
//		a Javascript array. "?search=whatever" becomes querystring["search"] 
//   
// IN:	key				Search key	
// OUT: querystring[]	Query string contents for key
// -----------------------------------------------------------------------------
function Utilities_QueryStringKey(key)
{
	//this loads the portion of the url containing the querystring, and also
	//decodes any special character codes  
	//var que = unescape(location.search);
	var que = document.location.search ;

	//remove the ? from the beginning of the string
	que = que.substring(1, que.length);

	//detects multiple values and splits them into an array que[0], que[1] etc...
	var que = que.split("&");

	// creates the querystring array
	var querystring = new Array();

	//(for some strange reason the "for/next" loop wasn't working)
	var loop = 0;

	//This loop takes each value in the que array then seperates the "names" 
	//from the "values" by splitting it into "inter" arrays. the name becomes
	// "inter3" and the value becomes "inter2". querystring then loads the "inter2" 
	//value into a slot called "inter3"
	while (loop < que.length)
	{
		var inter = que[loop].split("=");
		var inter2 = inter[1];
		var inter3 = inter[0];
		que[loop] = inter2;
		querystring[inter3] = inter2;
		loop = loop + 1;
	} 

	return querystring[key] ;   
}

// -----------------------------------------------------------------------------
// Description: 
//		Replaces a given substring within a string by another string
//   
// IN:	string			source string
//		text			search string
//		by				string to replace search string			
// OUT: newstr			String with specified text replaced by another string
// -----------------------------------------------------------------------------
function Utilities_Replace(string,text,by) {
// Replaces text with by in string
    var strLength = string.length; 
    var txtLength = text.length;
    
    //If either the strings are empty return source string
    if ((strLength == 0) || (txtLength == 0)) {
		return string;
	}
	
	//Find out the position of the search string
    var i = string.indexOf(text,0);
    
   // If search string in source string cannot be found return source string
    if ((!i) && (text != string.substring(0,txtLength))) {
		
		return string;
	}
    
    if (i == -1){
		return string;
    }
	
	//Replace search string with replacing string 
    var newstr = string.substring(0,i) + by;
	
	//Replace search string in the rest of the source string
    if (newstr.indexOf(text,i)>-1){
		
		var remainder = Utilities_Replace(string.substring(i+txtLength,strLength),text,by);
		
		newstr = newstr + remainder ; 
				
	}else{
		newstr = newstr + string.substring(i+txtLength,strLength) ; 
	}
	
	
	 
	//return final string 
    return newstr;
}

// -----------------------------------------------------------------------------
// Description: 
//		Replaces all HTML entities within a string with the appropriate HTML characters
//		e.g. Replaces '&' with appropriate character to be rendered by HTML correctly
//   
// IN:	text	- source text	
// OUT: text	- text with entities replaced
// -----------------------------------------------------------------------------
function Utilities_ReplaceHTMLEntities(text) {
	
	text = Utilities_Replace(text,'&','&amp;');
    text = Utilities_Replace(text,'"','&quot;');
    text = Utilities_Replace(text,'<','&lt;');
    text = Utilities_Replace(text,'>','&gt;');
    text = Utilities_Replace(text,' ','&nbsp;');
    
   return text; 
}


// -----------------------------------------------------------------------------
// Description: 
//		Portable replacement for findElementById
//   
// IN:	id	- object id	
// OUT: obj	- object with specified id.
// -----------------------------------------------------------------------------
function findElementById(objId) {
    return document.all ? document.all[objId] : document.getElementById(objId);
}


// -----------------------------------------------------------------------------
// Description: 
//		Gets the X position
//   
// IN:	obj	- object
//      parentID - the parent ID	
// OUT: curleft - the x position in pixels
// -----------------------------------------------------------------------------
    function findPosX(obj, parentID) 
    {
        var curleft = 0;
        var isIE = document.all ? true : false;
	    if (obj.offsetParent) {
	        curleft = obj.offsetLeft;
	        
		    while (obj = obj.offsetParent) {
                if(isIE)
		        {
		    	    // IE: don't add contribution from master page
		    	    if(!(obj.id.indexOf("MasterPage") > -1))
		            {
			            curleft += obj.offsetLeft;

			        }
			    }
			    else
			    {
			    	// Firefox: exclude 'display:inline' element
			        if (obj.className != 'pagePanel0')
		            {
			            curleft += obj.offsetLeft;
			        }
			    }

		    }
	    }
	  return curleft;
    }

    
// -----------------------------------------------------------------------------
// Description: 
//		Gets the Y position
//   
// IN:	obj	- object
//      parentID - the parent ID	
// OUT: curtop - the y position in pixels
// -----------------------------------------------------------------------------
    function findPosY(obj, parentID) 
    {
        var isSafari = (navigator.userAgent.indexOf("Safari") > -1)?true:false;
	    var curtop = 0;
	    var isIE = document.all ? true : false;
	    if (obj.offsetParent) {
		    curtop = obj.offsetTop;
		    while (obj = obj.offsetParent) 
		    {
		        if(isIE)
		        {
		    	    //don't add contribution from master page
		    	    if(!(obj.id.indexOf("MasterPage") > -1))
		            {
			            curtop += obj.offsetTop;

			        }
			    }
			    else
			    {
			    	//don't add contribution from a named id in Firefox
			    	//it fixes current bugs but why it works is a mystery! (stut)
			        if(!obj.id)
		            {
			            curtop += obj.offsetTop;

			        }
			    }
		    }
	    }    
	  return curtop;	  
    }

// -----------------------------------------------------------------------------
// Description: 
//		Portable method for adding event listeners.
//
//      See pg 53-55 of "DHTML Utopia: Modern Web Design Using Javascript and
//      DOM" by Stuart Langridge.
//   
// IN:	eElement - element to attach event.
//      eType - event type.
//      fnc - event handler. (DOM listeners)
// OUT:
// -----------------------------------------------------------------------------

function AddEvent(eElement, eType, fnc)
{
    if (eElement.addEventListener)
    {
    eElement.addEventListener(eType, fnc, false);
    }
    else if (eElement.attachEvent)
    {
    return eElement.attachEvent('on'+eType, fnc);
    }
    else
    {
    eElement['on'+eType] = fnc;
    }
    
    return true;
}


// -----------------------------------------------------------------------------
// Description: 
//		Portable method for stopping event propagation.
//
//      See pg 56-58 of "DHTML Utopia: Modern Web Design Using Javascript and
//      DOM" by Stuart Langridge.
//   
// IN:	e - event object.
// OUT: none
// -----------------------------------------------------------------------------

function StopEventPropagation(e)
{
    if (!e) e = window.event;
    
    if (e && e.cancelBubble)
    {
        e.cancelBubble = true;
    }

    if (e && e.stopPropagation)
    {
        e.stopPropagation();
    }
	
    return true;
}

// -----------------------------------------------------------------------------
// Description: 
//		Register a funtion to execute when the page loads (i.e., like
//      window.onload = myFunction() or <body onload="myFunction()"> except
//      safe for all browsers and without all the problems associated with
//      registering multiple functions.
//   
//      Register a new "onload" function named 'myFunction' with:
//          AddWindowOnloadHandler( myFunction )
//      or:
//          AddWindowOnloadHandler(function(){ myFunction('My arguments') })
//
// IN:	fnc - JS function.
// OUT: none
// -----------------------------------------------------------------------------

function AddWindowOnloadHandler(fnc)
{
  if ( typeof window.addEventListener != "undefined" )
  {
    window.addEventListener( "load", fnc, false );
  }
  else if ( typeof window.attachEvent != "undefined" )
  {
    window.attachEvent( "onload", fnc );
  }
  else
  {
    if ( window.onload == null )
    {
      window.onload = fnc;
    }
    else
    {
      var previousOnload = window.onload;
      window.onload = function ( evt )
      {
        previousOnload( evt );
        window[fnc]();
      };
    }
  }
  
  return;
}

function Hide(id)
{
  var element= findElementById(id);
  element.style.display ='none';
}

function Unhide(id)
{
  var element= findElementById(id);
  element.style.display ='block';
}



function __doNamedPostBack(eventTarget, eventArgument) 
{
   var test = document.getElementsByName(eventTarget)[0];
	/*var qualified_id = document.getElementsByName(eventTarget)[0].id;
	while (qualified_id.indexOf("-")>=0)
	{
	qualified_id=qualified_id.replace("-","$");
	}*/
	
	/*__doPostBack(eventTarget, eventArgument);*/
}


 // Get elements by class by Dustin Diaz.
  function getElementsByClass(searchClass)
  {	  
        var classElements = new Array();      
		 var node = document;     		
		 var tag = '*';
	     var els = node.getElementsByTagName(tag);
	     var elsLen = els.length;
	     var pattern = new RegExp("(^|\s)"+searchClass+"(\s|$)");

	     for (i = 0, j = 0; i < elsLen; i++)
      {
		        if(pattern.test(els[i].className))
          {
			           classElements[j] = els[i];
			           j++;
		        }
	     }

	     return classElements;
  }

// -----------------------------------------------------------------------------
// Description: 
//		Does navigation on a page between anchors. Can be used with SystemLink
//   
// IN:	anchorID, event
// OUT: none
// -----------------------------------------------------------------------------

function anchorNavigation(hashID, evnt)
{
    
    var isIE = document.all ? true : false;
    //navigate
    location.hash = hashID;
    //prevent postback
    if(isIE)
    {
      evnt.returnValue = false;
    }
    else
    {
        evnt.preventDefault();
    }    
    
    return false;
}
// -----------------------------------------------------------------------------
// Description: 
//		opens a new browser window with new url . Can be used with SystemLink
//   
// IN:	anchorID, event
// OUT: none
// -----------------------------------------------------------------------------
function linkNavigation(url, evnt)
{
    
    var isIE = document.all ? true : false;
    var newWindow = window.open(url);
    
    //prevent postback
    if(isIE)
    {
      evnt.returnValue = false;
    }
    else
    {
        evnt.preventDefault();
    }        
    return false;
}

// -----------------------------------------------------------------------------
// Description: 
//		provides a confirm dialog on site logout
//   
// IN:	none
// OUT: none
// -----------------------------------------------------------------------------
function confirmLogout()
{
    if (!confirm("Are you sure you want to logout?"))
    {
        return false;
    }
    else
    {
        return true;
    }
}

//href source for logout event
var source;

// -----------------------------------------------------------------------------
// Description: 
//		pop up for log out
//   
// IN:	event
// OUT: none
// -----------------------------------------------------------------------------

function LogOut(evnt, logoutID)
{
      var isIE = document.all ? true : false;
      var logoutElement = findElementById(logoutID);
      //get logout control id
      if(isIE)
      {
        source = evnt.srcElement.href;
      }
      else
      {
        source = evnt.target.href;
      }
        //draw pop up with buttons
        var messageTxt = "<table><tr><td colspan=\"2\">Are you sure you want to log out ?</td></tr><tr><td align=\"right\" ><input type=\"button\" class=\"btnstylelogout\" value=\"YES\" onclick=\"DoLogOut('yes')\"/></td>" +
                     "<td align=\"left\"><input type=\"button\" class=\"btnstylelogout\" value=\"NO\" onclick=\"DoLogOut('no')\"/></td></tr></table>";
        help.autoHide=false;
        help.autoAway=false;
        help.showAnchor=false;
        help.helpPopUpPanelClassHeight = "helpPopupHeight_logout";
        help.helpPopUpPanelClassWidth = "helpPopupWidth_logout";
        help.Show({message:messageTxt, anchor:logoutElement,top:50,left:-150});

            //prevent postback
    if(isIE)
    {
      evnt.returnValue = false;
    }
    else
    {
        evnt.preventDefault();
    }        
    return false;
}
// -----------------------------------------------------------------------------
// Description: 
//		handles button clicks for log out pop up
//   
// IN:	event
// OUT: none
// -----------------------------------------------------------------------------

function DoLogOut(logout)
{
   if(logout == 'yes')
   {
    //postback request to log out   
     window.location.href = source;
   }
   else
   {
        //close pop up
      help.Hide();
   }
}

// -----------------------------------------------------------------------------
// Description: 
//		formats a number for output
//   
//IN -       num:            the number to be formatted
//           decimalNum:     the number of decimals after the digit
//           bolLeadingZero: true / false to use leading zero
//           bolParens:      true / false to use parenthesis for - num
//
//OUT - formatted number
// -----------------------------------------------------------------------------

function FormatNumber(num, decimalNum, bolLeadingZero, bolParens)
{
       var tmpNum = num;

       // Return the right number of decimal places
       tmpNum *= Math.pow(10,decimalNum);
       tmpNum = Math.floor(tmpNum);
       tmpNum /= Math.pow(10,decimalNum);

       var tmpStr = new String(tmpNum);

       // See if we need to hack off a leading zero or not
       if (!bolLeadingZero && num < 1 && num > -1 && num !=0)
           if (num > 0)
               tmpStr = tmpStr.substring(1,tmpStr.length);
           else
               // Take out the minus sign out (start at 2)
               tmpStr = "-" + tmpStr.substring(2,tmpStr.length);                        


       // See if we need to put parenthesis around the number
       if (bolParens && num < 0)
           tmpStr = "(" + tmpStr.substring(1,tmpStr.length) + ")";


       return tmpStr;
}

// -----------------------------------------------------------------------------
// Description: 
//		Displays a popup asking for confirmation of addition of solution to home page
//   
//IN -       evnt: The event
//           clientID: The link button ID that was clicked.
//
//OUT - none
// -----------------------------------------------------------------------------
function SelectedSolution(evnt, clientID)
{
      var isIE = document.all ? true : false;
      //get logout control id
      if(isIE)
      {
        source = evnt.srcElement.href;
      }
      else
      {
        source = evnt.target.href;
      }
        var messageTxt = "<table><tbody><tr><td colspan=\"2\">Click OK to add this solution to your activity homepage. You can use it to remember how you'll overcome the exercise barrier. Click Cancel to look for another solution.</td></tr><tr><td align=\"right\"><input align=\"center\" type=\"button\" class=\"btnstylelogout\" value=\"OK\" onclick=\"systemButtonClickedSolution('" + clientID + "','');help.Hide();return true;\"/></td> " +
                     " <td align=\"left\"><input align=\"center\" type=\"button\" class=\"btnstylelogout\" value=\"Cancel\" onclick=\"help.Hide();return false;\"/></td></tr></tbody></table>";
        help.autoHide=false;
        help.autoAway=false;
        help.showAnchor=false;
        help.width=400;
        //help.helpPopUpPanelClassWidth="helpPopUpWidth";
        help.helpPopUpPanelClassHeight="assessorPopUpHeight";
        var anchorObject = findElementById(clientID)
        help.Show({message:messageTxt,anchor:anchorObject});
        
        //prevent postback
    if(isIE)
    {
      evnt.returnValue = false;
    }
    else
    {
        evnt.preventDefault();
    }        
    return false;
}

// -----------------------------------------------------------------------------
// Description: 
//		Displays a popup asking for confirmation of addition of solution to home page
//   
//IN -       evnt: The event
//           clientID: The link button ID that was clicked.
//
//OUT - none
// -----------------------------------------------------------------------------
function SelectedHabitSolution(evnt, clientID)
{
      var isIE = document.all ? true : false;
      //get logout control id
      if(evnt.srcElement)
      {
        source = evnt.srcElement.href;
      }
      else
      {
        source = evnt.target.href;
      }
        var messageTxt = "<table><tbody><tr><td colspan=\"2\">Click OK to add this solution to your plan."
                        +" You can use it to remember how you'll overcome your habit/challenge."
                        +" Click Cancel to look for another solution.</td></tr>"
                        + "<tr><td align=\"right\"><input align=\"center\" type=\"button\" class=\"btnstylelogout\" value=\"OK\"     onclick=\"systemButtonClickedHabit('" + clientID + "','');help.Hide();return true;\"/></td> "
                        +    " <td align=\"left\"> <input align=\"center\" type=\"button\" class=\"btnstylelogout\" value=\"CANCEL\" onclick=\"help.Hide();return false;\"/></td></tr>"
                        +"</tbody></table>";
        help.autoHide=false;
        help.autoAway=false;
        help.showAnchor=false;
        help.width=400;
        //help.helpPopUpPanelClassWidth="helpPopUpWidth";
        help.helpPopUpPanelClassHeight="assessorPopUpHeight";
        var anchorObject = findElementById(clientID)
        help.Show({message:messageTxt,anchor:anchorObject});
        
        //prevent postback
    if(isIE)
    {
      evnt.returnValue = false;
    }
    else
    {
        evnt.preventDefault();
    }        
    return false;
}


// -----------------------------------------------------------------------------
// Description: 
//      Trims a string of white spaces (can be split into LTrim and RTrim functions)
//   
//IN - a string
//OUT - a trimmed string
// -----------------------------------------------------------------------------

function trimAll(sString) 
{
    while (sString.substring(0,1) == ' ')
    {
    sString = sString.substring(1, sString.length);
    }
    while (sString.substring(sString.length-1, sString.length) == ' ')
    {
    sString = sString.substring(0,sString.length-1);
    }
    return sString;
}


// -----------------------------------------------------------------------------
// Description: 
//     stops postback on enter key being pressed - add to keypress event as
//      "StopEnterKeyPostBack(event)"
//   
//IN - event
//OUT - false to prevent propagation of events
// -----------------------------------------------------------------------------

function StopEnterKeyPostBack(evnt)
{
         //prevent postback
    if(isIE)
    {
      if(evnt.keyCode == 13)
        evnt.returnValue = false;
       return false;
    }
    else
    {
        if(evnt.charCode == 13)
            evnt.preventDefault();
        return false;

    }        
    return true;

}


// -----------------------------------------------------------------------------
// Description: 
//      Prevents a postback
//   
//IN - the event
// -----------------------------------------------------------------------------
function PreventPostBack(evnt)
{
    if(isIE)
    {
      evnt.returnValue = false;
    }
    else
    {
        evnt.preventDefault();
    }        
    return false;
}
    
// -----------------------------------------------------------------------------
// Description:
//		prints the Window
//		
// IN:	none
// OUT: none
// -----------------------------------------------------------------------------
function printWindow()
{
    window.print();  
    return false;
}

// -----------------------------------------------------------------------------
// Description: 
//		prints the iframe of the tree search pages (hints and tips, news and articles...)
//		
// IN:	none
// OUT: none
// -----------------------------------------------------------------------------
function printPlanIFrame()
{
    var iframe = findElementById("ifrm");
    if(iframe)
    {
        if (isIE) 
        { 
        document.ifrm.focus(); 
        document.ifrm.print(); 
        } 
        else 
        { 
            //assumes only one frame in window
            window.frames[0].focus(); 
            window.frames[0].print(); 
        } 
    }
    else
    {
        window.print();  
    }
    return false;
}

// -----------------------------------------------------------------------------
// Description: 
//		prints the iframe of the tree search pages (hints and tips, news and articles...)
//		
// IN:	text - the text shown in the popup
//      clientID - the Id of the client control
// OUT: none
// -----------------------------------------------------------------------------
function ShowCertificatePopup(text, clientID)
{
    var messageTxt = "<table class=\"certificatePopupBackground\"><tbody><tr><td class=\"certificateCell\"><div class=\"certificatePopupText\"><p>" + text + "</p></div></td></tr>" +
                     "</tbody></table>";
        help.autoHide=false;
        help.autoAway=false;
        help.showAnchor=false;
        help.width=400;
        //help.helpPopUpPanelClassWidth="helpPopUpWidth";
        help.helpPopUpPanelClassHeight="certificatePopUpHeight";
        var anchorObject = findElementById(clientID);
        var vLeft = -400;
        help.Show({message:messageTxt,left:vLeft,anchor:anchorObject});
             
    return false;
}

// -----------------------------------------------------------------------------
// Description: 
//		Shows the user introduction and photo in a pop-up
//		
// IN:	introduction - the introduction
//      forumName - the forum name for the user
//      forumID - the forum ID for the photo (if negative no photo is shown)
//      clientID - the Id of the client control
// OUT: none
// -----------------------------------------------------------------------------
function ShowUserIntroduction(introduction, forumName, forumID, clientID)
{
    var messageHdr = 
        "About " + forumName;
    var messageTxt = 
        "<table class=\"introductionPopupBackground\">" +
        "<tbody><tr>";
        
    messageTxt +=
        "<td class=\"introductionPhotoCell\">" +
            "<img class=\"introductionPopupPhoto\" src=\"UserPhoto.aspx?size=128&id=" + forumID + "\"/>" +
        "</td>";
        
    messageTxt +=       
        "<td class=\"introductionCell\"><div class=\"introductionPopupText\">" +
            introduction + 
            //"<p>" + introduction + "</p>" +
        "</div></td>" +
        "</tr></tbody></table>";
                     
    help.autoHide=false;
    help.autoAway=false;
    help.showAnchor=false;
    help.width=400;
    //help.helpPopUpPanelClassWidth="introductionPopUpWidth";
    help.helpPopUpPanelClassHeight="introductionPopUpHeight";
    var anchorObject = findElementById(clientID)
    help.Show({title:messageHdr,message:messageTxt,anchor:anchorObject});
             
    return false;
}

// -----------------------------------------------------------------------------
// Description: 
//		Checks if the user has typed in 4 characters to the promo code box
//		
// IN:	destID - the ID of the conrtol to give focus to
//      clientID - the Id of the client control
// OUT: none
// -----------------------------------------------------------------------------
function CodeLengthCheck(clientID, destID)
{
    var box = findElementById(clientID);
    var dest = findElementById(destID);
    if (box.value.length >= 4)
    {
        box.value = box.value.substring(0, 4);
        dest.focus();
    }
    else
    {
        box.focus();
    }
    
    return false;
}

//-----------------------------------------------------------------------------
// Description: 
//      Set of function for working with cookie
//
//-----------------------------------------------------------------------------

// Set cookie
function setCookie(name, value, expires, path, domain, secure) {
    var curCookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
    document.cookie = curCookie;
}

// Get cookie
function getCookie(name) {
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    } else
        begin += 2;
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
        end = dc.length;
    return unescape(dc.substring(begin + prefix.length, end));
}

// Delete cookie
function deleteCookie(name, path, domain) {
    if (getCookie(name)) {
        document.cookie = name + "=" +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

