var oPopup;

 // Removes leading and trailing spaces from the passed string
  function trim(inputString) 
  {
	if (inputString == null) { return inputString; }
	
	try
	{
		 //[mpyatagi] - use regex if that fails follow the below way 
		// return(inputString.replace(/^\s{0,}(.{0,}?)\s{0,}$/,"$1"));
		var retValue = inputString;
		while (retValue.substring(0, 1) == " ") 
		{ 
			retValue = retValue.substring(1, retValue.length);
		}
		while (retValue.substring(retValue.length-1, retValue.length)  == " ") 
		{ 
			retValue = retValue.substring(0, retValue.length-1);
		}
		return retValue; 
	}
	catch(ex)
	{
	}
 } 

var HelpPopupDetails = 
{
    'mainhelp' : {Page : "pdc_help.htm", IsModalLess : false },
    'changeview' : {Page : "context/changeview.htm", IsModalLess : true },
    'accesscode' : {Page : "context/accesscode.htm", IsModalLess : true },
    'applyfundedee' : {Page : "context/FundedEE.htm", IsModalLess : true },
    'targettedto' : {Page : "context/targettedto.htm", IsModalLess : true },
    'opportunitystatus' : {Page : "context/opportunitystatus.htm", IsModalLess : true },
    'trainingpref' : {Page : "context/trainingpref.htm", IsModalLess : true },
    'courselanguage': {Page : "context/courselanguage.htm", IsModalLess : true },
    'rtb': {Page : "context/richtexteditor.htm", IsModalLess : true }
}

function ShowHelp(type)
{
    var smallWindowFeatures =  "unadorned:off;center:yes;status:no;dialogWidth:200px;dialogHeight:200px;help:no;resizable=no;edge:sunken;scroll:no;";
    var helpDetails = HelpPopupDetails[type];
    if(helpDetails == null)
        helpDetails = HelpPopupDetails['mainhelp'];
    var pagePath = ApplicationPath + "/General/Help.aspx?SRC=" + helpDetails.Page;
    if(type == "mainhelp")
    {
        pagePath = MainHelpPath;
    }

    var helpWindow = null;
    if(helpDetails.IsModalLess)    
        helpWindow = window.open(pagePath,"contexthelp","height=150,width=280,help=no,status=no,menubar=no,scrollbars=yes");
    else
        helpWindow = window.open(pagePath);
        
    setFocusToWindow(helpWindow);                
}

var LearnMoreHelpPopupDetails = 
{
    'home' : {Page : "context/home.htm", IsModalLess : true },
    'profile' : {Page : "context/profile.htm", IsModalLess : true },
    'onlinecourse' : {Page : "context/onlinecourse.htm", IsModalLess : true },
    'curriculum' : {Page : "context/curriculum.htm", IsModalLess : true },
    'blendedcourse' : {Page : "context/blendedcourse.htm", IsModalLess : true },
    'instructorledsession' : {Page : "context/instructorledsession.htm", IsModalLess : true },
    'instructorled' : {Page : "context/instructorled.htm", IsModalLess : true },
    'leadership' : {Page : "context/leadership.htm", IsModalLess : true },
    'catalog' : {Page : "context/catalog.htm", IsModalLess : true },
    'calendar' : {Page : "context/calendar.htm", IsModalLess : true },
    'intactsession' : {Page : "context/intactsession.htm", IsModalLess : true },
    'resouces' : {Page : "context/Resouces.htm", IsModalLess : true },
    'competency' : {Page : "context/competency.htm", IsModalLess : true },
    'managercenter' : {Page : "context/managercenter.htm", IsModalLess : true },
    'calendarmain' : {Page : "context/calendarmain.htm", IsModalLess : true },
    'employeedevelopmentplan' : {Page : "context/employeedevelopmentplan.htm", IsModalLess : true },
    'mytraining' : {Page : "context/mytraining.htm", IsModalLess : true },
    'opportunities' : {Page : "context/opportunities.htm", IsModalLess : true },
    'accesscode' : {Page : "context/accesscode.htm", IsModalLess : true },
    'opportunitiesportlet' : {Page : "context/opportunitiesportlet.htm", IsModalLess : true },
    'recommendedtrainingportlet' : {Page : "context/recommendedtrainingportlet.htm", IsModalLess : true },
    'employeedevelopmentplanportlet' : {Page : "context/employeedevelopmentplanportlet.htm", IsModalLess : true },
    'managercenterportlet' : {Page : "context/managercenterportlet.htm", IsModalLess : true },
    'mytrainingportlet' : {Page : "context/mytrainingportlet.htm", IsModalLess : true },
    'addcontent' : {Page : "context/addcontent.htm", IsModalLess : true }, 
    'eventsportlet' : {Page : "context/myeventsportlet.htm", IsModalLess : true },
    'myevents' : {Page : "context/myevents.htm", IsModalLess : true }   ,
    'TrainingNews' : {Page : "context/TrainingNews.htm", IsModalLess : true }  ,
    'TrainingNewsPortlet' : {Page : "context/TrainingNewsPortlet.htm", IsModalLess : true },
    'careerdevelopmentplan' : {Page: "context/careerdevelopmentplan.htm", IsModalLess : true }
}

function ShowLearnMore(type)
{
    var features = "unadorned:off;center:yes;status:no;dialogWidth:500px;dialogHeight:400px;help:no;resizable=no;edge:sunken;scroll:no;";
    var helpDetails = LearnMoreHelpPopupDetails[type.toLowerCase()];
    if(helpDetails == null)
        helpDetails = HelpPopupDetails['mainhelp'];
    var pagePath = ApplicationPath + "/General/Help.aspx?SRC=" + helpDetails.Page;        
    //var pagePath = GetPage(helpDetails.Page);

    var helpWindow = null;
    if(helpDetails.IsModalLess)    
    {
        helpWindow = window.open(pagePath,"learnmore","height=250,width=400,help=no,status=no,menubar=no,scrollbars=yes");
    }
    else
        helpWindow = window.open(pagePath);    
        
    setFocusToWindow(helpWindow);
}

function openLegend(value)
{        
    var legendUrl = IndicatorLegendURL;   
    
    if(value==1) //Dashboard
    {
        legendUrl = legendUrl + "/IndicatorLegend.aspx";
        window.open(legendUrl ,'Legend',"'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,height=500,width=825,left=170,top=160'");          
    }
    else if (value == 2) //Details page
    {
        legendUrl = legendUrl + "/IndicatorDetailsLegend.aspx";        
        window.open(legendUrl ,'Legend',"'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=no,height=580,width=737,left=170,top=50'");          
    }
}

//************* Highlight Table Cells Script **********************************
//Specify highlight behavior. "TD" to highlight table cells, "TR" to highlight the entire row:
var highlightbehavior="TD"

var ns6=document.getElementById&&!document.all
var ie = document.all

function changeto(e,highlightClass){
	source=ie? event.srcElement : e.target
	if (source.tagName=="TABLE")
	return
	while(source.tagName!=highlightbehavior && source.tagName!="HTML")
		source=ns6? source.parentNode : source.parentElement
	if (source.className!=highlightClass&&source.id!="ignore") {
	    source.className=highlightClass
	}
}

function contains_ns6(master, slave) { //check if slave is contained by master
	while (slave.parentNode)
	if ((slave = slave.parentNode) == master)
	return true;
	return false;
}

function changeback(e,originalcolor){
	if (ie&&(event.fromElement.contains(event.toElement)||source.contains(event.toElement)||source.id=="ignore")||source.tagName=="TABLE")
	return
	else if (ns6&&(contains_ns6(source, e.relatedTarget)||source.id=="ignore"))
	return
	if (ie&&event.toElement!=source||ns6&&e.relatedTarget!=source)
	source.className=originalcolor
}

// function related to Getting, Deleting and setting cookies
function getCookieValue(Name) 
{   
	var search = Name + "=";
	if (document.cookie.length > 0) 
	{ 
		offset = document.cookie.indexOf(search);
		if (offset != -1) 
		{
			offset += search.length ; 
			end = document.cookie.indexOf(";", offset); // set index of beginning of value
			// set index of end of cookie value
			if (end == -1) 
				end = document.cookie.length;
			return unescape(document.cookie.substring(offset, end));      
		}    
	}
	return null;
}
	
function setCookie(name, value, expire) 
{   
	document.cookie = name + "=" + escape(value) + "; domain=.intel.com; path=/" + ((expire == null) ? "" : ("; expires=" + expire.toGMTString()))
}

function deleteCookie(name) 
{
      document.cookie = name + "=" +
      "; domain=.intel.com; path=/" + 
      ";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// Removes leading and trailing spaces from the passed string
function trimInputString(inputString) 
{
    return trim(inputString);
} 

var weekday = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday")
var monthname = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
var longmonth = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");

function localizeDateAndTime(datetime)
{
	var d = new Date(datetime + " UTC");
	return d.toLocaleString();
}

function localizeDate(datetime)
{
	var d = new Date(datetime + " UTC");
	var output = weekday[d.getDay()] + ", " + longmonth[d.getMonth()] + " " + d.getDate() + ", " + d.getFullYear();
	return output;
}

function GetUTCDate(datetime)
{
    return new Date(datetime + " UTC");
}
function localizeTime(datetime)
{
	var d = new Date(datetime + " UTC");
	var h = d.getHours();
	var m = d.getMinutes();
	var label = "AM";
	if (h >= 12)
	{
		label = "PM";
		if (h > 12)
			h = h - 12;
	}
	else if (h == 0)
		h = 12;
	if (m < 10) m = "0" + m;
	return (h + ":" + m + " " + label);
}

function GetFormattedTime(datetime)
{
	var d = new Date(datetime);
	var h = d.getHours();
	var m = d.getMinutes();
	var label = "AM";
	if (h >= 12)
	{
		label = "PM";
		if (h > 12)
			h = h - 12;
	}
	else if (h == 0)
		h = 12;
	if (m < 10) m = "0" + m;
	return (h + ":" + m + " " + label);
}

function localizeDate_CompactStyle(datetime)
{
	var d = new Date(datetime + " UTC");
	var output = monthname[d.getMonth()] + " " + d.getDate() + " " +  d.getFullYear() + " " +  localizeTime(datetime);
	return output;
}

function GetDate_CompactStyle(datetime)
{
	var d = new Date(datetime);
	var output = monthname[d.getMonth()] + " " + d.getDate() + " " +  d.getFullYear() + " " +  GetFormattedTime(datetime);
	return output;
}
 
function GetNodeValue(name,xmlObj)
{
    var value = "";
   var REQUIRED_BROWSER = "microsoft internet explorer";
  
   if(REQUIRED_BROWSER == navigator.appName.toLowerCase())
  { 
   if(xmlObj.selectSingleNode(name) != null)
		value = xmlObj.selectSingleNode(name).text;
   }
    else
     {
       if(xmlObj.getElementsByTagName(name)[0] != null)
   	        value = xmlObj.getElementsByTagName(name)[0].childNodes[0].nodeValue;
     } 
   
   	return value;
}

function getToolTipHTML(header, text)
{
	var html = "<table cellpadding='0' cellspacing='0' class='InfoPopup'>";
	
	if((header != null) && (header != ""))
    {
	    html += "<tr><td nowrap  class='InfoPopupHeader'>&nbsp;<strong>";
	    html += header + "</strong></td></tr>";
	}
	html += "<tr><td >" + text;
	html += "</td></tr></table>";
	
	return html;
}
function HideToolTip()
{
   //debugger;
 var REQUIRED_BROWSER = "microsoft internet explorer";
  
   if(REQUIRED_BROWSER == navigator.appName.toLowerCase())
  { 
   var obj = document.getElementById('InfoPopup');
    obj.style.display = "none";
    
    if(oPopup != null)oPopup.hide();
    }
}

function ShowToolTip(header, text, noWrapper, overrideWidth,currentWindow,mouseXPosition, mouseYPosition)
{   
  //debugger;
  var REQUIRED_BROWSER = "microsoft internet explorer";
  
   if(REQUIRED_BROWSER == navigator.appName.toLowerCase())
  { 
	var obj = document.getElementById('InfoPopup');
	var window = currentWindow == null? this: currentWindow;
	obj.innerHTML =  getToolTipHTML(header, text);
	
	obj.style.cssText = 'display: block;Position:absolute ;z-index:10;';
	obj.style.width = overrideWidth == null ? 400 : overrideWidth;

	var height = obj.clientHeight;
	var width = obj.clientWidth;
	
	var x = (mouseXPosition == null?window.event.clientX:mouseXPosition);
	var y = (mouseYPosition == null?window.event.clientY:mouseYPosition);

	x += document.body.scrollLeft;
	
	if (width+10 > document.body.clientWidth - window.event.clientX)
	{
		if (window.event.clientX > document.body.clientWidth - window.event.clientX)
		{
			x -= (width+15);
		} 
	}
	x += 10;
    y += document.body.scrollTop;
    
    // if there is not enough room to display below.
    if (height+10 > document.body.clientHeight - window.event.clientY)
    {
		// then determine if there is more room above.
		if (window.event.clientY > document.body.clientHeight - window.event.clientY)
		{
			y -= (height+15);
		} 
	}
	y += 15;
	var style = 'display: block;Position:absolute; Left:' + x + 'px; Top:' + (y-1) + 'px;z-index:10;';
	if( overrideWidth != null) 
		style += "width:" + overrideWidth + ";" ;
    obj.style.cssText = style 
    obj.style.display = "none" ;
        
    oPopup = window.createPopup();
    var oPopBody = oPopup.document.body;
    oPopBody.innerHTML = "<body><link rel='stylesheet' href='" + CommonStylePath + "' type='text/css'><div class='InfoPopup'>" + getToolTipHTML(header, text) + "</div></body>";
    oPopup.show(x, (y-1) , overrideWidth, obj.clientHeight, document.body);
    return oPopup;
    }
}

 function setTimeZoneOffsetCookie()
 {
     //create a cookie for the user timezone
     var expires = new Date();
     var today = new Date();
     expires.setTime(today.getTime() + 1000*60*60*24*1); //set expiry to 1 days
     setCookie("TimeZoneOffset_TODAY_ONLY", -(today.getTimezoneOffset()), expires);  
 } 
 
 //In Subpages also, Timzone needs tobe set when deeplinks are used
 setTimeZoneOffsetCookie();
 
function Left(str, n){
	if (n <= 0)
	    return "&nbsp;";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n) + "...";
}

function OpenCofirmationModalDialog(type,masterId,languageId)
{
    var url="";

    url = "Confirmation&ItemMasterId=" + masterId;
    url += "&LanguageId=" + languageId ;  	                
    
    var returnValue = OpenModal(url,type);
    if(typeof returnValue == 'undefined')
    {
	    
        if(typeof(RemoveActionComplete) == 'function')
            RemoveActionComplete(type);
    } 
}

//This is the master function to open the model window
function OpenModalDialog(url,type)
{
    var returnValue; 
    if(document.getElementById("MODALURL") != null)
    {
	    var modalurl = document.getElementById("MODALURL").value + "?Target=";
	    modalurl= modalurl + url  + "&Type=" + type;
	    returnValue = showModalDialog(modalurl,window,'dialogHeight:210px;dialogWidth:580px;center:yes;scroll:no;status:no;help:no;');
	}
	return returnValue;
}

function ValidateDate(startDate,endDate)
{
	var valid = true;
	if(startDate.value == ""
		&&  endDate.value == "")
		return true;
	if(startDate.value != ""
		&& endDate.value != "")
	{
		var startdate = new Date(startDate.value);
		var enddate = new Date(endDate.value);
		
		if(startdate > enddate)
		{
			valid = false; 
		}
	}
	return valid;
}

function enableObject(objectID)
{
    var obj = document.getElementById(objectID);
    obj.disabled = false;
}

function disableObject(objectID)
{
    var obj = document.getElementById(objectID);
    obj.disabled = true;
}

function showObject(objectID)
{
    var obj = document.getElementById(objectID);
    obj.style.display = "block";
}

function hideObject(objectID)
{
    var obj = document.getElementById(objectID);
    obj.style.display = "none";
}

/* Function used for Sorting Records */
function onPageSortAction(ClientID, SortKey)
{    
    if(typeof(pageClientId) != "undefined")
        ClientID = pageClientId + ClientID;
        
    var sPreviousSortKey = document.getElementById(ClientID +"_SortKey").value;
    var sPreviousSortOrder = document.getElementById(ClientID +"_SortOrder").value;

    if(sPreviousSortKey == SortKey)
        document.getElementById(ClientID +"_SortOrder").value = (sPreviousSortOrder == "ASC") ? "DESC" : "ASC"; 
    else
        document.getElementById(ClientID +"_SortOrder").value = "ASC";

    document.getElementById(ClientID +"_SortKey").value = SortKey;
   
    RenderPaging_Async(ClientID);
    return false;
}

function setFocusToWindow(win)
{
    try
    {    
        win.focus();                
    }catch(ex){}      
}

function getQueryString(variable) 
{
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) 
    {
        var pair = vars[i].split("=");
        if (pair[0] == variable) 
        {
            return pair[1];
        }
    } 
    return '';
}

function getNoOfRecordsToDisplay(clientID,inPortlet)
{
    var noOfRecordToDisplay = "40";
    if(inPortlet == "true")
    {
        noOfRecordToDisplay = "20";
        var dropDown = document.getElementById(clientID + "_PageSize");
        if(dropDown != null)
        {
            var selectedIndex = dropDown.options.selectedIndex;
            if(selectedIndex == (dropDown.options.length - 1))
            { 
               noOfRecordToDisplay = "50";//ALL
            }
        }
    }
    return noOfRecordToDisplay;
}

function GetClickMoreInfo(sTitle,sDescription,id,iCredit,sCourseCategory,sTrainers,sRoom,sTime,sStatus,iWaitList,tid,track,powerSession,sPreWork,sPostWork,sAbstract)
{
	var html = '<table border="0" width="100%" height="100%" cellpadding="0" cellspacing="0">';
	html += '<tr class="GridHeader">';
	html += '<td ><strong>Details</strong></td>';
	html += '<td align="right"><span class="HeaderHover" onclick="document.getElementById(\'PowerSessionCourseDetailDiv\').style.display= \'none\';" ><strong>(X) close</strong></span></td>';
	html += '</tr>';
	
	html += '<tr>';
	html += '<td align="center" width="100%" valign="top" height="100%" colspan="2">';
	html += '<table border="0" width="100%" cellpadding="5" cellspacing="0">';
	
	if(sTitle !=null || sDescription != null || sAbstract != null)	
	{	html += '<tr>';
		html += '<td>';
		
		if(sTitle != null)
		{
			html += '<span class="BoldBlackText" id="title">' + sTitle + '</span><br>';
		}
		
		if(sDescription != null)
		{	
			var height = GetRowDisplayHeight(sDescription);
			html += '<div style="overflow-y:auto;height: ' + height + 'px;">'+ sDescription + '</div>';
		}
		
		if(sAbstract != null)
		{
			var height = GetRowDisplayHeight(sAbstract);
			html += '<div style="overflow-y:auto;height: ' + height + 'px;">'+ sAbstract + '</div>';
		}
		
		html += '</td></tr>';
	}

	if(id != null)
	{	html += '<tr>';
		html += '<td width="100%">';
		html += '<table width="100%" border="0" cellpadding="4" cellspacing="1" bgcolor="#d5d5d5">';
		html += '<tr>';
		html += '<td nowrap valign="top" align="right" class="EventGridHeader"><strong>ID</strong></td>';
		html += '<td  width="100%" bgcolor="#ffffff">' + id + '</td>';
		html += '</tr>';
	}

	if(iCredit != null)
	{	html += '<tr>';
		html += '<td nowrap valign="top" align="right" class="GridHeader"><strong>Credits</strong></td>';
		html += '<td  width="100%" bgcolor="#ffffff">' + iCredit + '</td>';
		html += '</tr>';
	}

	if(sCourseCategory != null)
	{	html += '<tr>';
		html += '<td nowrap valign="top" align="right" class="EventGridHeader"><strong>Category</strong></td>';
		html += '<td  width="100%" bgcolor="#ffffff">' + sCourseCategory + '</td>';
		html += '</tr>';
	}
	if(sTrainers != null)
	{
		html += '<tr>';
		html += '<td nowrap valign="top" align="right" class="GridHeader"><strong>Instructor</strong></td>';
		html += '<td  width="100%" bgcolor="#ffffff">' + sTrainers + '</td>';
		html += '</tr>';
	}
	if(sRoom != null)
	{
		html += '<tr>';
		html += '<td nowrap valign="top" align="right" class="GridHeader"><strong>'+info_popup_room+'</strong></td>';
		html += '<td width="100%" bgcolor="#ffffff">' + sRoom + '</td>';
		html += '</tr>';
	}
	if(sTime != null)
	{
		html += '<tr>';
		html += '<td nowrap valign="top" align="right" class="GridHeader"><strong>'+info_popup_time+'</strong></td>';
		html += '<td width="100%" bgcolor="#ffffff">' + sTime + '</td>';
		html += '</tr>';
	}
	if(sStatus != null)
	{
		html += '<tr>';
		html += '<td nowrap valign="top" align="right" class="GridHeader"><strong>'+info_popup_status+'</strong></td>';
		html += '<td width="100%" bgcolor="#ffffff">' + sStatus + '</td>';
		html += '</tr>';
	}
	if(iWaitList != null)
	{
		html += '<tr>';
		html += '<td nowrap valign="top" align="right" class="GridHeader"><strong>'+info_popup_waitlist+'</strong></td>';
		html += '<td width="100%" bgcolor="#ffffff">' + iWaitList + '</td>';
		html += '</tr>';
	}
	if(track != null && track.length > 0)
	{
		html += '<tr>';
		html += '<td nowrap valign="top" align="right" class="GridHeader"><strong>'+info_popup_track+'</strong></td>';
		html += '<td width="100%" bgcolor="#ffffff">' + track + '</td>';
		html += '</tr>';
	}
	if(powerSession != null && powerSession.length > 0)
	{
		html += '<tr>';
		html += '<td nowrap valign="top" align="right" class="GridHeader"><strong>'+info_popup_powersession+'</strong></td>';
		html += '<td width="100%" bgcolor="#ffffff">' + powerSession + '</td>';
		html += '</tr>';
	}
	
	if(sPreWork != null)
	{
		html += '<tr>';
		html += '<td nowrap valign="top" align="right" class="GridHeader"><strong>'+info_popup_pre_work+'</strong></td>';
		html += '<td width="100%" bgcolor="#ffffff">' + sPreWork + '</td>';
		html += '</tr>';
	}
	if(sPostWork != null)
	{
		html += '<tr>';
		html += '<td nowrap valign="top" align="right" class="GridHeader"><strong>'+info_popup_post_work+'</strong></td>';
		html += '<td width="100%" bgcolor="#ffffff">' + sPostWork + '</td>';
		html += '</tr>';
	}

	if(id != null)
	{	
		html += '</table>';
		html += '</td>';
		html += '</tr>';
	}
	

		
	html += '</table>';
	html += '</td>';
	html += '</tr>';
	html += '</table>';

	/*var div = document.getElementById("PowerSessionCourseDetailDiv");
	div.style.height = 309;

	var divWidth = parseInt(div.style.width.replace("px",""));
	div.innerHTML = html;*/

	/*if(isNaN(divWidth) == false) //ROSHNI - TO CHECK THIS
	    div.style.left = (document.body.clientWidth/2)-309;  //(divWidth/2);
	else
	    div.style.left = (document.body.clientWidth/2);*/

	//div.style.left = 190;	
	
	//div.style.top = document.body.clientHeight/3; //document.body.scrollTop + document.body.clientHeight/3;
	//div.style.display = "inline"; 
	//div.style.overflowY= "hidden";
	
	var div = document.getElementById("PowerSessionCourseDetailDiv");

	var divWidth = parseInt(div.style.width.replace("px",""));
	div.innerHTML = html;
	
	if(isNaN(divWidth) == false) //ROSHNI - TO CHECK THIS
	    div.style.left = (document.body.clientWidth/2)-309;  //(divWidth/2);
	else
	    div.style.left = (document.body.clientWidth/2);
	    
	//div.style.left = (document.body.clientWidth/2)-(divWidth/2);
	div.style.top = document.body.scrollTop + document.body.clientHeight/3;
	div.style.display = "inline"; 
	div.style.overflowY= "hidden";
}

function GetRowDisplayHeight(sContent)
{
		var height = 150;
		var totalLength = 0;
		
		
		sContent = sContent.toLowerCase();
		strArr = sContent.split("<br>");
		var i;
		
		for(i=0;i<strArr.length;i++)
		{
			totalLength += Math.ceil(strArr[i].length/60)==0?1:Math.ceil(strArr[i].length/60);
		}
		
		if(totalLength < 1)
		{
			height = 20;
		}
		else if(totalLength < 11) 
		{
			totalLength = Math.ceil(totalLength);
			height = totalLength * 16;
		}
	return height;
}

function IsImageOk(img)
{
    // During the onload event, IE correctly identifies any images that
    // weren't downloaded as not complete. Others should too. Gecko-based
    // browsers act like NS4 in that they report this incorrectly.
    if (!img.complete)
        return false;

    // However, they do have two very useful properties: naturalWidth and
    // naturalHeight. These give the true size of the image. If it failed
    // to load, either of these should be zero.
    if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0)
        return false;

    // No other way of checking: assume it's ok.
    return true;
}

//ROSHNI - Check if this function is being used
var DefaultFullPath = '/Portal/webdocs/Views/EventSessions/Default'; //TODO: Pick from web helper

addEvent(window, 'load', function()
{
    for (var i = 0; i < document.images.length; i++)
        if (!IsImageOk(document.images[i]))
        {
			var s = document.images[i].src.lastIndexOf("/") + 1;
			var imageName = trim(document.images[i].src.substring(s));
			if (imageName.length > 0)
			{
				document.images[i].src = DefaultFullPath + "/images/" + imageName;
			}
        }
});

function addEvent(obj, evType, fn)
{ 
	if (obj.addEventListener)
	{ 
		obj.addEventListener(evType, fn, true); 
		return true; 
	} 
	else if (obj.attachEvent)
	{ 
		var r = obj.attachEvent("on"+evType, fn); 
		return r; 
	} 
	else  
		return false; 
}

var StartTime;

function StartTimer()
{
	StartTime = (new Date()).getTime();
}

function EndTimer()
{
	var EndTime = (new Date()).getTime();
	var diff = EndTime - StartTime;
	var secs = diff/1000;
	alert(secs + " seconds ");
}

function BuildInfoPopupHTML(cid, sid, showMatches)
{
	var item = CourseByID[cid];
	

	var html = "<table cellpadding='0' cellspacing='0' class='InfoPopup'>";
	html += "<tr><td nowrap colspan='2' class='InfoPopupHeader'><strong>";
	html += info_popup_further_information + "</strong></td></tr>";
	var idText = item['sCourseID'] != null ? " ( " +  item['sCourseID'] + " )" : " ( " + item['iCourseID'] + " )";
	if(item["bHighLight"]=="True" || item["bHighLight"]==1)
		{
			if(item['sType'] == "1")
			{
				if (showMatches) html += BuildInfoRow(info_popup_course, item['sTitleMatch']+idText);
				else html += BuildInfoRow(info_popup_meeting, item['sTitle']+idText);
				html += BuildInfoRow(info_popup_room, item['sRoomName']);
				html += BuildInfoRow(info_popup_time, item['sTime']);
				html += BuildInfoRow(info_popup_status, item['sRegistration']);	
				html += "</table>"
				return html;
			}			
			html += BuildInfoRow("Description:", SafeCell(item['sAbstract']));
			html += "</table>"
			return html;
		}
	if (showMatches) html += BuildInfoRow(info_popup_course, item['sTitleMatch']+idText);
	else html += BuildInfoRow(info_popup_course, item['sTitle']+idText);
	if (sid != null) 
	{
		var se = SessionByID[sid]
		html += BuildInfoRow(info_popup_room, se['sRoomName']);
		html += BuildInfoRow(info_popup_time, se['dtStartTime']);
		var sRegistrationStatus = "Open";
		if(parseFloat(se['iOpen']) == 0)
			{
			sRegistrationStatus = "Full";
			}
		html += BuildInfoRow(info_popup_registration, sRegistrationStatus);
		
		if(se['iWaitlisted'] != null)
			{
			html += BuildInfoRow(info_popup_waitlist, se['iWaitlisted']);
			}
	}
	
	var tid = item['iTrackID'];
	var track = "";
	if (tid != null && tid.length > 0)
	{
		track_obj = TrackByID[tid];
		track = track_obj['sTitle'];
		html += BuildInfoRow(info_popup_track, track);
	}
	tid="";
	tid=item['sTrack'];
	if(tid != null && tid.length > 0)
	{
		html += BuildInfoRow(info_popup_track, tid);
	}
	var powerSession = "";
	powerSession = item['sPowerSession'];
	if(powerSession != null && powerSession.length > 0)
	{
		html += BuildInfoRow(info_popup_powersession, powerSession);
	}
	//html += BuildInfoRow(info_popup_registration, "");
	//html += BuildInfoRow(info_popup_waitlist, "");
	html += BuildInfoRow(info_popup_pre_work, SafeCell(item['sPreWork']));
	html += BuildInfoRow(info_popup_post_work, SafeCell(item['sPostWork']));
	if (showMatches) html += BuildInfoRow(info_popup_abstract, SafeCell(item['sAbstractMatch']));
	else html += BuildInfoRow(info_popup_abstract, SafeCell(item['sAbstract']));
	html += "</table>";
	
	return html;
}

function BuildInfoRow(title, text)
{
	html = "<tr><td valign=top nowrap><strong>" + unescape(title) + "</strong></td><td width='100%'>";
	html += Left(unescape(text),255) + "</td></tr>";
	return html;
}

function BuildSessionInfoIcon(sid)
{
	var cid = SessionByID[sid]['iCourseID'];
	return BuildInfoIcon(cid, sid, false);
}

function BuildCourseInfoIcon(cid, showMatches)
{
	return BuildInfoIcon(cid, null, showMatches);
}

function BuildInfoIcon(cid, sid, showMatches)
{
	var html = "<img style='cursor: hand;' ";
	html += " onMouseMove='InfoMouseMove(" + cid + ", ";
	html += showMatches + ", " + sid + ")' ";
	html += " onMouseOut='InfoMouseOut()' ";
	html += " src='" + info_gif + "'>";
	return html;
}

function InfoMouseMove(cid, showMatches, sid)
{
	if (typeof(sid) == "undefined") 
		sid = null;

    ShowAllDropDowns(true);
    ShowToolTip(null, BuildInfoPopupHTML(cid, sid, showMatches), false,250);
    ShowAllDropDowns(false);
}

function InfoMouseClick(cid, showMatches, sid)
{
	if (typeof(sid) == "undefined") 
		sid = null;

    ShowAllDropDowns(true);
    BuildClickInfoPopup(cid, sid, showMatches);
    ShowAllDropDowns(false);
}

function BuildClickInfoPopup(cid, sid, showMatches)
{
	var item = CourseByID[cid];
	var idText = item['sCourseID'] != null ? item['sCourseID'] :item['iCourseID'];
	var sTitle;
	var sRoom;
	var sTime;
	var sStatus;
	var iWaitList;
	var track;
	var powerSession;
	var sPreWork;
	var sPostWork;
	var sAbstract;
	
	if(item["bHighLight"]=="True" || item["bHighLight"]==1)
	{
		if(item['sType'] == "1")
		{
			if (showMatches)
			{
				 sTitle = unescape(item['sTitleMatch']);
			}
			else 
			{
				sTitle = unescape(item['sTitle']);
			}
			
			sRoom = unescape(item['sRoomName']);
			sTime =  unescape(item['sTime']);
			sStatus = unescape(item['sRegistration']);	
			GetClickMoreInfo(sTitle,null,idText,null,null,null,sRoom,sTime,sStatus)
			return;
		}
		GetClickMoreInfo(null,unescape(SafeCell(item['sAbstract'])))			
		return;
	}
		
	if (showMatches)
	{
		 sTitle = unescape(item['sTitleMatch']);
	}
	else 
	{
		sTitle = unescape(item['sTitle']);
	}
	
	if (sid != null) 
	{
		var se = SessionByID[sid]
		sRoom =unescape(se['sRoomName']);
		sTime = unescape(se['dtStartTime']);
		sStatus = "Open";
		if(parseFloat(se['iOpen']) == 0)
		{
			sStatus = "Full";
		}
				
		if(se['iWaitlisted'] != null)
			{
				iWaitList = unescape(se['iWaitlisted']);
			}
	}
	
	track=unescape(item['sTrack']);

	powerSession = "";
	powerSession = unescape(item['sPowerSession']);
	sPreWork = unescape(SafeCell(item['sPreWork']));
	sPostWork =unescape(SafeCell(item['sPostWork']));
	if (showMatches) 
	{	
		sAbstract = unescape(SafeCell(item['sAbstractMatch']));
	}
	else
	{	
		 sAbstract = unescape(SafeCell(item['sAbstract']));
	}

	GetClickMoreInfo(sTitle,null,idText,null,null,null,sRoom,sTime,sStatus,iWaitList,null,track,powerSession,sPreWork,sPostWork,sAbstract);
	return;
}

function InfoMouseOut()
{
	HideToolTip();
	ShowAllDropDowns(true);
}

function ShowAllDropDowns(show)
{
	HideDropDown("ViewByDropDown", show);
	HideDropDown("CatalogDropDown", show);
	HideDropDown("TrackDropDown", show);
}

function HideDropDown(name, show)
{
	var obj = document.getElementById(name);
	if (obj != null) 
	{
		if (show) obj.style.display = 'block';
		else 
		{
			var popupObj = document.getElementById('InfoPopup');
			var obj_y = GetOffsetTop(obj);
			var obj_h = obj.clientHeight;
			var popupObj_y = GetOffsetTop(popupObj);
			var popupObj_h = popupObj.clientHeight;
			if (popupObj_y > obj_y+obj_h) return;
			if (popupObj_y + popupObj_h < obj_y) return;
			obj.style.display = 'none';
		}
	}
}

function GetOffsetTop(obj)
{
	var top = obj.offsetTop;
	while (obj.offsetParent != null) 
	{
		obj = obj.offsetParent;
		top += obj.offsetTop;
	}
	return top;
}


function SafeCell(text)
{
	if (text != null && typeof(text) != "undefined" && text.length > 0) return unescape(text);
	else return "&nbsp;";
}

function HighlightWord(text, word)
{
	var i = text.toLowerCase().indexOf(word.toLowerCase());
	if (i < 0) return text;

	var beforeText = text.substring(0, i);
	var matchText = text.substring(i, i+word.length);
	var newMatchText = "<span class='HighlightClass'>" + matchText + "</span>";
	var afterText = text.substring(i+word.length, text.length);

	if (afterText.length > 0) afterText = HighlightWord(afterText, word);
	var ret = beforeText + newMatchText + afterText;
	
	return ret;
}

function SelectOptionByValue(dropDown, value)
{
	for(var i = 0; i < dropDown.options.length; i++)
	{
		if(dropDown.options[i].value == value)
		{
			dropDown.options[i].selected = true;
			break;
		}
	}
}


function GetMessage(messageId)
{
	if(document.getElementById(messageId.toLowerCase())!= null)
	{
		return 	document.getElementById(messageId.toLowerCase()).value;
	}	
	else if(document.getElementById(messageId.toUpperCase())!=null)	
	{
		return 	document.getElementById(messageId.toUpperCase()).value;
	}
	else
	{
		return messageId;
	}		
}	

function GetHttpObject()
{
	var xmlhttp;
	try {
		xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
	}
	catch(e) {
		try {
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(i) {
			xmlhttp = (typeof(XMLHttpRequest) != undefined) ? new XMLHttpRequest() : false;
		}
	}
	return xmlhttp;
}

function GetResponseXml(sUrl,sParams)
{
var objXmlHttp = GetHttpObject();
	if(objXmlHttp) {
		objXmlHttp.open("POST", sUrl, false);
		objXmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
		objXmlHttp.send(sParams);
	}
return objXmlHttp.responseXml;
}

var oPopup = null;
function GetPopUp()
{
	return oPopup;
}
function ShowPopUp(message)
{

    if(window.ActiveXObject)
   { 
	    if(message == null)
	    {
		    message = "Saving Data......";
	    }

	    var popupMessage = "";
	    oPopup = window.createPopup();
	    var oPopBody = oPopup.document.body;
	    oPopBody.style.backgroundColor = "blue";
	    oPopBody.style.border = "solid black 1px";
	    popupMessage = "<html>";
	    popupMessage += "<body><table width=100%><tr><th bgcolor='blue'><font face='arial' size='3' color='white'>" + unescape(message) +  "</font></th></tr>";
	    popupMessage += "</table></body></html>";
	    oPopBody.innerHTML = popupMessage;
	    var xAxis = (document.body.clientWidth-210)/2;
	    var yAxis = (document.body.clientHeight-50)/2;
	    oPopup.show(xAxis, yAxis, 210, 50, document.body);
	    return oPopup;
	}
}

function HidePopUp()
{
	if(oPopup != null)oPopup.hide();

}

function Left(str, n){
	if (n <= 0)
	    return "&nbsp;";
	else if (n > String(str).length)
	    return str;
	else
	    return String(str).substring(0,n) + "...";
}


function Sleep(gap)
{
var then,now; 
then=new Date().getTime();
now=then;

while((now-then) < gap)
	{
	now=new Date().getTime();
	}
}

//used by intact session and instructor led course
function ApplyTimeZoneOffset(topicStartDateTime)
{
    var formattedStartDate = new Date(topicStartDateTime.getFullYear(),topicStartDateTime.getMonth(),topicStartDateTime.getDay());
    var offsetValue = formattedStartDate.getTimezoneOffset();
    
    var hours = (Math.abs(offsetValue) > 59) ? Math.ceil(offsetValue/60) : 0;
    var minutes = (Math.abs(offsetValue) > 59) ? offsetValue % 60 : offsetValue;    
    hours = hours * -1; 
    minutes = minutes * -1;    
    if((topicStartDateTime.getHours() + hours) > 23 ) hours * -1; //if hours >23, it has to spill over to the next day
    topicStartDateTime.setHours(topicStartDateTime.getHours() + hours, topicStartDateTime.getMinutes() + minutes,topicStartDateTime.getSeconds());
    return topicStartDateTime;
}

//used by intact session and instructor led course
function extractHoursMinutes(timeString)
{
    var index = timeString.lastIndexOf(':');    
    var hoursMinutesString = timeString.substring(0,index);
    if(index < 5) hoursMinutesString = "0" + hoursMinutesString; //prepend 0 if hours less than 10 
    hoursMinutesString = hoursMinutesString + timeString.substr(index + 3, 3);
    return hoursMinutesString;
}