
function IsActiveXInstaled(sActiveXIF)
{
      // Trying to create the ActiveX object, if the creation is successful it's installed. 
      var obj  = null;
      var bRet = true; 

      try
      {
            obj = new ActiveXObject(sActiveXIF); 
            obj = null;
      }
      catch(e)
      {
        bRet = false;
      }
      
      return bRet;
}; // IsActiveXInstaled


function getQTControl(targetDiv, src, startTime, applicationPath)
{
    var result = '<EMBED HEIGHT=100% WIDTH=100% ' +
                    'SRC="' + src + '" TYPE="video/quicktime" ' +
                    'CONTROLLER="false" ' +
                    'BGCOLOR="green" ' +
                    'EnableJavaScript="true" ' +
                    'name="img' + targetDiv.id + '" ' +
                    'HREF="' + applicationPath + '/InstructorViewer.aspx?startTime=' + startTime + '" />';
                    
    targetDiv.innerHTML = result;
};

function applyCustomLook(courseid, userid, pagetype)
{
    //alert(courseid + " - " + userid + " - " + pagetype);
}

function CopyLink(value)
{
    if (GetBrowser() == "IExplorer")
        window.clipboardData.setData("Text",value);
    else
        copy(value);       
}

// AS May, 14 2008
// Used by Control SendDirectLink.ascx.
// This is needed because the return value is set by checkbox on client side.
function getLinkForSession(LinkWithLogin, LinkWithoutLogin)
{
    // If user clicked on requireUserLogin , return the value of LinkWithLogin
    if(document.getElementById("CheckBoxRequireUserLogin").checked )
    {
       // var link_without_login = document.getElementById(LinkWithLogin).value;
        return LinkWithLogin ;
    }
    else
    {
        //var link_with_login = document.getElementById(LinkWithoutLogin).value;
        return LinkWithoutLogin;
    }
}


function getHelp(topic, context)
{
    var screenWidth = window.screen.width;
    var screenheight = window.screen.height;
    sProps = "left=0, top=0, height=" + screenWidth + ", width=" + screenWidth + ", status=no,location=no,menubar=no, resizable=yes, scrollbars=yes";
	
	if (context == null)
	    context = "instructor";
	
	if ((topic != null) && (topic != ""))
	{
        oWin = window.open("HelpSelect.aspx?context=" + context + "&topic=" + topic, "Help", sProps);
        if ((oWin==null) || typeof(oWin)=="undefined")
        {
	        alert("Could not open help window. Please check your popup-blocker settings");
        }
    }
    else
    {
        alert("No help is available for current screen");
    }
}

//Try to avoid Firefox software crash by using an hidden frame to open the notes application.
//Crash reason is not known
function redirectNoCrash(dest)
{
    if (navigator.appName == "Netscape")
        frmNoCrash.src = dest;
    else
        frmNoCrash.location = dest;
}

function openNotes(src, bHasNotes)
{
    if (bHasNotes == "false" && navigator.appVersion.indexOf("MSIE") > 0)
        alert("Notes application was not found");
    else if (src.getAttribute("Enabled") == "True")
    {
        redirectNoCrash("OpenNotes.aspx?sessionGUID=" + src.getAttribute("GUID"));
    }
}

function GetBrowser(){

     var nIndex1,nIndex2;

      var sIE="MSIE",sFF="Firefox",sSF="Safari",sNS="Netscape",sSemiColon=";",sSlash="/";

      if( ((nIndex1 = navigator.userAgent.indexOf(sIE)) != -1) &&

                  ((nIndex2 = navigator.userAgent.indexOf(sSemiColon, nIndex1)) != -1) )

      {
        return "IExplorer";

      }

      else if( ((nIndex1 = navigator.userAgent.indexOf(sFF)) != -1) &&

                               ((nIndex2 = navigator.userAgent.indexOf(sSlash, nIndex1)) != -1) )

      {
        
        return "FireFox";
        
      }

      else if( ((nIndex1 = navigator.userAgent.indexOf(sSF)) != -1) &&

                               ((nIndex2 = navigator.userAgent.indexOf(sSlash, nIndex1)) != -1) )

      {

         return "Safari";
        
      }

      else if( ((nIndex1 = navigator.userAgent.indexOf(sNS)) != -1) &&

                               ((nIndex2 = navigator.userAgent.indexOf(sSlash, nIndex1)) != -1) )

      {
            /*
            this.eBrowserType = this.BT_NS;
            this.sBrowserVer  = navigator.userAgent.substr(nIndex2+1, navigator.userAgent.length-nIndex2-1);
            */
            return "OTHER";
      }

      else

      {
         return "OTHER";
      }     

}


//live sessions - notify on live sessions that starts soon
function NotifyNextLiveSession()
{
     document.getElementById('liveSessionJoiner').style.visibility="visible";
     document.getElementById('liveSessionNotifier').innerHTML=notifiedLiveSessionsArr[notifyLiveSessionInd];
     document.getElementById('liveSessionNotifier').lobbyUrl="LiveSessionsLobby.aspx?sessionGUID=" + liveSessionsGuidArr[notifyLiveSessionInd];
     notifyLiveSessionInd++;
     if(notifyLiveSessionInd>=notifiedLiveSessionsArr.length)
        notifyLiveSessionInd=0;
}

//live sessions - join live session that starts soon
function JoinLiveSession()
{
    window.location=document.getElementById('liveSessionNotifier').lobbyUrl;
}


function AddMacPlugin(strUrl)
{
     if (navigator.mimeTypes)
      {
        var strObj="";

        //safari use 'x-tegrity-recorder-safari' plugin  - yossi birenboim 22/9/2009
        if (GetBrowser() == "Safari" && navigator.mimeTypes["application/x-tegrity-recorder-safari"])
            strObj = '<object class="hidden" name="MacRecPlugIn" style= "visibility:hidden;height:0px" id="MacRecPlugIn" type="application/x-tegrity-recorder-safari"> <param name="URL" value="' + strUrl + '">  </object>';
        else {
            //other browsers use 'x-tegrity-recorder' plugin  - yossi birenboim 22/9/2009
            if (navigator.mimeTypes["application/x-tegrity-recorder"])
                strObj = '<object class="hidden" name="MacRecPlugIn" style= "visibility:hidden;height:0px" id="MacRecPlugIn" type="application/x-tegrity-recorder"> <param name="URL" value="' + strUrl + '">  </object>';
        }        
        
        //alert(strObj);
        var divObj = document.getElementById('MacPlugInDiv');
        if (typeof divObj != "undefined")
        {
            divObj.innerHTML = strObj;
            var dummy = divObj.innerHTML;   // needed in order to overcome bug in Safari
            //alert("Teg Recorder Plugin was added");
        }
        else
            alert("MacPlugIn DIV not found");
      }
      /*
      else
        alert("Tegrity Recorder mime type not found");
       */  
}


function IsCriticalMacRecUpdate(latestMacBuildNum)
{
    //alert("IsCriticalMacRecUpdate - Mac version on server=" + latestMacBuildNum);
    var criticalUpdate = true;
    var tegPlugin = document.getElementById("MacRecPlugIn");
    if (tegPlugin !=null && typeof(tegPlugin) != "undefined")
    {    
        var clientVersion = tegPlugin.recorderVersion;
        //alert("IsCriticalMacRecUpdate - Mac version on client=" + clientVersion);
        if (typeof clientVersion != "undefined" && clientVersion > 0 )
            criticalUpdate = false;
    }
    return criticalUpdate;
}

function IsMacRecUpdateExists(latestMacBuildNum)
{
    //alert("Mac version on server=" + latestMacBuildNum);
    var updateExists = true;
    var tegPlugin = document.getElementById("MacRecPlugIn");
    if (tegPlugin != null && typeof tegPlugin != "undefined")
    {   
        var clientVersion = tegPlugin.recorderVersion;
        //alert("Mac version on client=" + clientVersion + " tegPlugin=" + tegPlugin);
        //alert("Mac version on client=" + clientVersion);
        if (typeof clientVersion != "undefined" &&  latestMacBuildNum <= clientVersion)
            updateExists =  false;
    }
    return updateExists;
}

function PerpetualMacRecorder(macBuildNum, skipUpdate)
{
    //alert("Perpetual: build=" + macBuildNum + " skip=" + skipUpdate);
    //AddMacPlugin();

    var updateExists = IsMacRecUpdateExists(macBuildNum);
    var criticalUpdate = IsCriticalMacRecUpdate(macBuildNum);
    if (criticalUpdate || (updateExists && !skipUpdate))
    {
        LaunchMacRecDl(criticalUpdate, "Record.aspx");
    }
    else
    {
        LaunchMacRecorder();
    }

}

function UpdateMacRecordButton(macBuildNum, btnId, skipUpdate, comeFromPage, buttonText)
{
    //alert("Enter UpdateMacRecordButton");
    //AddMacPlugin();

    //yossi birenboim - 10/12/2008 (there is no record button on the page (student,unknown user ...))
    if(document.getElementById(btnId)==null)
      return;
    
    var updateExists = IsMacRecUpdateExists(macBuildNum);
    var criticalUpdate = IsCriticalMacRecUpdate(macBuildNum);
                    
    if (criticalUpdate || (updateExists && !skipUpdate))
    {
        document.getElementById(btnId).value = "Download Recorder";
        document.getElementById(btnId).style.fontSize='20px';
        document.getElementById(btnId).title = "Click to download Tegrity Recorder";
        document.getElementById(btnId).onclick = function(){LaunchMacRecDl(criticalUpdate, comeFromPage);};
    }
    else
    {
        document.getElementById(btnId).value = buttonText;
        document.getElementById(btnId).title = "Click to record a new Tegrity class";
        document.getElementById(btnId).onclick = function(){LaunchMacRecorder();};
    }
}



function LaunchMacRecorder()
{
    //alert("LaunchMacRecorder");
    
    //bug 6560 fix - mac recorder does not support Tiger (mac os ver 10_4_...) 
    if (navigator.userAgent.indexOf("10_4") != -1) {
        alert("The Tegrity Recorder does not support your OS.");
        return;
    }
    
    var errMsg = "";
    var tegPlugin = document.getElementById("MacRecPlugIn");
    if (tegPlugin !=null && typeof tegPlugin != "undefined")
    {    
        var rc = tegPlugin.launchRecorder();
        switch (rc)
        {
            case -1:
                errMsg = "unknown error";
                break;
            case -2:
                errMsg = "application cannot be found";
                break;
            case -3:
                errMsg = "application version is not available (application corrupted)";
                break;
            case -4:
                errMsg = "application cannot open url";
                break;
            case -5:
                errMsg = "application is recording";
                break;
            default:
        }
    }
    else
        errMsg = "Failed to find Mac Recorder Plugin";
        
    if (errMsg != "")
        alert("Tegrity Recorder Plugin failed with error: " + errMsg); 
}
    
    
function LaunchMacRecDl(critical, comeFromPage)
{
    //alert("LaunchMacRecDl " + critical + " " + comeFromPage);
    
    //bug 6560 fix - mac recorder does not support Tiger (mac os ver 10_4_...) 
    if (navigator.userAgent.indexOf("10_4") != -1) {
        alert("The Tegrity Recorder does not support your OS.");
        return;
    }
    
    var url = "MacRecDl.aspx?ComeFromPage=" + comeFromPage;
    
    if (!critical)
        url = url + "&NotCritical=true";
        
    window.location = url;
}

function TestAlert(msg)
{
    alert("TestAlert:" + msg);
}


//returns true if pressed key is a digit (0-9) or system key (TAB,DELETE,BACKSPACE...) else false
 function IsDigit(e){   
   var keyPressed;
   var keychar;
   var numcheck;
   
    if(window.event)
        keyPressed = window.event.keyCode; // IE
    else
        keyPressed = e.which; // Firefox
                                                 /*TAB,DELETE ...*/ /*BACKSPACE*/      
    if (((keyPressed>=48) && (keyPressed<=57)) || keyPressed==0 || keyPressed==8)
        return true;
    else
        return false;
}

//returns true if pressed key is spacebar else false
function IsSpaceBar(e){

    if(window.event)
        keyPressed = window.event.keyCode; // IE
    else
        keyPressed = e.which; // Firefox
    if(keyPressed==32)  
        return true;
    else
        return false;
}

//Open the "Me 2" server main page
function openMe2()
{
    var screenWidth = window.screen.width;
    var screenheight = window.screen.height;
    var sProps = "left=0, top=0, height=" + screenWidth + ", width=" + screenWidth + ", status=no,location=no,menubar=no, resizable=yes";
    var oWin = window.open("http://me2.tegrity.com", "Me2", sProps);
}

function getAbsoluteLeft(objectId) {
	// Get an object left position from the upper left viewport corner
	// Tested with relative and nested objects
	o = document.getElementById(objectId)
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	// Return left postion
	return oLeft
}

function getAbsoluteTop(objectId) {
	// Get an object top position from the upper left viewport corner
	// Tested with relative and nested objects
	o = document.getElementById(objectId)
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	// Return top position
	return oTop
}

//Copy to Clipboard
function copy(text) {  
    var flashcopier = 'flashcopier';
    if(!document.getElementById(flashcopier)) {
      var divholder = document.createElement('div');
      divholder.id = flashcopier;
      document.body.appendChild(divholder);
    }
    document.getElementById(flashcopier).innerHTML = '';
    var divinfo = '<embed src="_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(text)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
    document.getElementById(flashcopier).innerHTML = divinfo;
}


//checks if text box or text area contains dangerous text ('<','>','&#',etc...)
function IsCtrlContainsDangerousInput(ctrlID){

    if(document.getElementById(ctrlID)==null) 
      return false;
    
    if (document.getElementById(ctrlID).value.indexOf("<")>-1 || 
        document.getElementById(ctrlID).value.indexOf(">")>-1 ||
        document.getElementById(ctrlID).value.indexOf("&#")>-1)
        return true;
    else
        return false;
}

//gets cookie name , returns its value
function GetCookie( name ) {
		var start = document.cookie.indexOf( name + "=" );
		var len = start + name.length + 1;
		if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
			return null;
		}
		if ( start == -1 ) return null;
		var end = document.cookie.indexOf( ';', len );
		if ( end == -1 ) end = document.cookie.length;
		return unescape( document.cookie.substring( len, end ) );
}

//sets cookie 
function SetCookie( name, value, expires, path, domain, secure ) {
		var today = new Date();
		today.setTime( today.getTime() );
		if ( expires ) {
			expires = expires * 1000 * 60 * 60 * 24;
		}
		var expires_date = new Date( today.getTime() + (expires) );
		//alert(name+'='+escape( value ) +
		//	( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
		//	( ( path ) ? ';path=' + path : '' ) +
		//	( ( domain ) ? ';domain=' + domain : '' ) +
		//	( ( secure ) ? ';secure' : '' ));
		document.cookie = name+'='+escape( value ) +
			( ( expires ) ? ';expires='+expires_date.toGMTString() : '' ) + //expires.toGMTString()
			( ( path ) ? ';path=' + path : '' ) +
			( ( domain ) ? ';domain=' + domain : '' ) +
			( ( secure ) ? ';secure' : '' );
}

//Handle redirection of sessions feed content for mobile devices
function openSessionFeed(url)
{
    if (url == "NO_FEED_AVAILABLE")
        alert("This session could not be displayed on this device");
    else
        window.location = url;        
}


function IsImportedUsers(chkImportUsersCID,str)
{
    var oCheckBoxImported;
    
    if (confirm("Showing imported users may take several minutes to render"))   
        setTimeout(str,0); 
    else
    {
        oCheckBoxImported = document.getElementById(chkImportUsersCID);
        oCheckBoxImported.checked  = false;
        setTimeout(str,0);
    }
}

if(!String.prototype.trim){
  String.prototype.trim = function () {  return this.replace(/^\s*(\S*(\s+\S+)*)\s*$/, "$1");};
}

//navigate to CourseSearch.aspx page (txtSearchElement.value is the searched text)
function SearchText(txtSearchElement, isProctTestsMode)
{
    if (txtSearchElement.value.trim() != "") {
        if (txtSearchElement.value.indexOf(">") == -1 && txtSearchElement.value.indexOf("<") == -1)
            location.href = "CourseSearch.aspx?txtToSearch=" + txtSearchElement.value.trim() + "&isProctTestsMode=" + isProctTestsMode;
        else
            alert("search phrase contains invalid chars : '< >'");
    }
    else
        alert("Please insert search text.");
}

//occurs when key is pressed on txtSearch text box
function SearchTextKeyPressed(txtSearchElement, e, isProctTestsMode) {
  
  if(window.event)
    keyPressed = window.event.keyCode; // IE
  else
    keyPressed = e.which; // Firefox
  if (keyPressed==13) {
    SearchText(txtSearchElement, isProctTestsMode);
    if(window.event)
      window.event.returnValue = false; 
    else
      e.preventDefault() 
  }
}


function GoPrev()
{
  history.go(-1);
}
  
function GoNext()
{
  history.go(1);
}

//opens browser window in full screen mode (was written for bug 5764 fix)
function OpenFullScreenWin(url,name) {
  var screenWidth = window.screen.width;
  var screenheight = window.screen.availHeight - 30;//.height;
  var sProps = "left=0,top=0,height=" + screenheight + ",width=" + screenWidth;
  window.open(url, name, sProps);
}


//returns week of year for a given date
function GetWeekOfYear(dt) {

    if (isNaN(dt))
        return -1;

    var DOb = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate());

    var D = DOb.getDay();
    //if (D == 0) 
    //D = 7;
    DOb.setDate(DOb.getDate() + (4 - D));
    var YN = DOb.getFullYear();
    var ZBDoCY = Math.floor((DOb.getTime() - new Date(YN, 0, 1, -6)) / 864e5);
    var weekOfYear = Math.floor(ZBDoCY / 7) + 1;
    return weekOfYear
}

var oPopupWin = null;

function OpenBookmarks() {

    if (oPopupWin == null || oPopupWin.closed) {
        var nWidth = 320;
        var nHeight = 462;
        var nX = parseInt(window.screen.width) / 2 - nWidth / 2;
        var nY = parseInt(window.screen.height) / 2 - nHeight / 2;
        var nTop = (nY < 0) ? 10 : nY; ;
        var nLeft = (nX < 0) ? 10 : nX;
        var sWindowProps = "menubars=no,titlebar=no ,scrollbars=no,toolbars=no,resizable=no,status=no,channelmode=no,top=" + nTop + "px,left=" + nLeft + "px,width=" + nWidth + "px,height=" + nHeight + "pt";
        var sPopupName = "TegrityBookmarks";

        oPopupWin = window.open("BookmarksRecorder.aspx", sPopupName, sWindowProps);
    }

    if (oPopupWin != null && oPopupWin.focus) {
        oPopupWin.focus();
    }
}

function lbCourses_change(source) {    
    var obj;
    obj = document.getElementById('aMP3');
    obj.href = source.options[source.selectedIndex].getAttribute('MP3Link');
    disableAnchor(obj, obj.href.indexOf("getCourseRSS.aspx") == -1);
    obj = document.getElementById('aRSS');
    obj.href = source.options[source.selectedIndex].getAttribute('RSSLink');
    disableAnchor(obj, obj.href.indexOf("getCourseRSS.aspx") == -1);
    obj = document.getElementById('aVideoPodcasts');
    obj.href = source.options[source.selectedIndex].getAttribute('M4VLink');
    disableAnchor(obj, obj.href.indexOf("getCourseRSS.aspx") == -1);
    obj = document.getElementById('aAudioPodcasts');
    obj.href = source.options[source.selectedIndex].getAttribute('iPodLink');
    disableAnchor(obj, obj.href.indexOf("getCourseRSS.aspx") == -1);
}

function disableAnchor(obj, disable) {
    if (disable) {
        obj.className = "clsCtrlBtn DisabledLink";
        obj.href = "http://";
        obj.onclick = function() { return false; };
    }
    else {
        obj.className = "clsCtrlBtn";
        obj.onclick = function() { };
    }
}


function DoWordWrap(max_not_wrapped_chars) {

    ////if (GetBrowser() != "IExplorer") {
        var oPs = document.getElementsByTagName("P");

        //iterate through all 'P' elements
        for (ind = 0; ind < oPs.length; ind++) {

            var str = oPs[ind].innerHTML;

            //do not wrap if paragraph text allready contains line break
            if (str.indexOf("<br") != -1)
                continue;

            for (charInd = max_not_wrapped_chars; charInd < str.length; charInd += max_not_wrapped_chars) {
                var j = charInd;
                while (str.charAt(j) != ' ') {
                    j--;
                }
                var strPrefix = str.substring(0, j);
                var strSuffix = str.substring(j, str.length);
                str = strPrefix + "<br>" + strSuffix;
            }
            oPs[ind].innerHTML = str;
        }
    ////}
}


