//
// iTunes Client Detection code
//
// This javascript library is tied intimately to MHBrowserRedirect.
// Note also that the iTunes U team links to this file on phobos, so check w/ Sugam/Charles before changing it.
//
// @author Mark Miller

var haveITMS = true;
var agent;
var isPC = false;
var isNotIE = false;

agent=navigator.userAgent.toLowerCase();
isPC = agent.indexOf("win") != -1;

// If we are on the Mac, assume that iTunes is installed.

if (isPC)
{
	// If we are on the PC, and we are running IE, we can check for ITMS, otherwise we assume we have
	// ITMS & hope for the best

	if (navigator.appName.indexOf('Microsoft') != -1)
	{ 
		haveITMS = doDetector();
	} else {
	    isNotIE = true;
	    haveITMS = ReadCookie('iTunesPresent');
	}
}

function doDetector()
{
	var detectObj = document.getElementById('iTunesDetector');
	var returnVal = false; // If we can't load the ActiveX control, assume we do not have ITMS

	if ( (detectObj != null) && (typeof(detectObj) != "undefined" ) )
	{
		if (typeof(detectObj.IsITMSHandlerAvailable) != "undefined")
			returnVal = detectObj.IsITMSHandlerAvailable;
		if ((returnVal == null) || ( typeof ( returnVal ) == "undefined" ))
			returnVal = false;
	}
    dbg("ActiveX Control result: " + returnVal);
	return returnVal;
}

function ReadCookie(cookieName) {
    var theCookie=""+document.cookie;
    var ind=theCookie.indexOf(cookieName);
    
    if (ind==-1 || cookieName=="") {
        return false;
    }
    
    var ind1=theCookie.indexOf(';',ind);
    
    if (ind1==-1) {
        ind1=theCookie.length;
    }
    
    return 'true' == unescape(theCookie.substring(ind+cookieName.length+1,ind1));
}


function runITInstall()
{
	var		installerRun = false;

	if (isPC)
	{
		var detectObj = iTunesDetector;

		if ( (detectObj != null) && (typeof(detectObj) != "undefined" ) )
		{
			try
			{
				if (typeof(detectObj.IsiTunesInstallerAvailable) != "undefined")
				{
					var	haveInstaller = detectObj.IsiTunesInstallerAvailable;
					
					if (haveInstaller && typeof(detectObj.RuniTunesInstaller) != "undefined")
					{
						detectObj.RuniTunesInstaller();
						installerRun = true;
					}
				}
			}
			catch (exception)
			{
			}
		}
	}

	return installerRun;
}

/**
 * This is the main entry point from WebObjects code.  See MHBrowserRedirect.java
 *
 * @param url the url to open if iTunes is installed
 * @param downloadUrl the url to go to to download iTunes
 * @param overridePanelId the id to unhide if the browser is firefox/opera.
 * @param noClose if true, don't close the browser window after opening iTunes.
 */
function itmsOpen(url, downloadUrl, overridePanelId, noClose) {
    if (null != getCookie('recentlyRedirected')) noClose = true;
    setCookie('recentlyRedirected', true, 8000);

    if (haveITMS) {
        if (noClose) {
            //info("itmsOpen(): Opening " + url + "\nThis window will remain open.");
            // we can't set window.location.href directly because the current page will not
            // be rendered (at least in Safari 416.12).  The odd thing is that even a window.alert()
            // hides this bug, if it is a bug.
            setTimeout('window.location.href = "'+url+'"', 1);
            return true;
        } else {
            return _itmsOpen(url);
        }
    } else if (isNotIE) { // firefox, opera
        // let the user tell us if iTunes is installed:
        document.getElementById(overridePanelId).style.display='block';
    } else if (!runITInstall()) { // IE, no iTunes
        window.location.replace(downloadUrl);
    }
    return true;
}

function _itmsOpen(url) {
    //dbg("_itmsOpen(): " + url);
    var shouldClose = 0;
    var uA = navigator.userAgent;
    var safariPos = navigator.userAgent.indexOf('Safari');
    var safariVersion = (safariPos != -1) ? parseFloat(uA.substr(safariPos + 7)) : -1;

    if ((safariPos == -1 && window.history.length == 0) || (safariVersion > 120 && window.history.length < 2)) {
      shouldClose = 1;
    }
    if (safariPos == -1 || safariVersion > 120) {
      window.location.href = url;
      if (shouldClose == 1) {
        setTimeout('window.close()', 100);
      } else {
        setTimeout('window.history.back()', 100);
      }
    } else {
      statement = 'window.location.href = "'+url+'"';
      setTimeout(statement, 1);
    }
    return true;
  }

function setCookie(cookieName,cookieValue,expireMillis) {
  var expire = new Date();
  expire.setTime(expire.getTime() + expireMillis);
  var cookie = cookieName + "=" + escape(cookieValue) + "; expires=" + expire.toGMTString();
  //dbg("setCookie(): " + cookie);
  document.cookie = cookie;
}

function getCookie(cookieName) {
  if (null == document.cookie || null == cookieName) return null;
  var cookies = document.cookie.split(';');
  var result = null;
  for (var i=0; i < cookies.length; i++) {
    var c = cookies[i];
    //dbg("Cookie: " + c);
    var keyValue = c.split('=');
    if (-1 < keyValue[0].indexOf(cookieName)) {
      result = keyValue[1];
      break;
    }
  }
  //info("getCookie(" + cookieName + "): " + result);
  return result;
}

function dbg(str) {
  //return alert(str);
}

function info(str) {
  //return alert(str);
}

