//
// 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 before changing it.
//
// @author Mark Miller

var BROWSER_SAFARI = 1;
var BROWSER_FIREFOX = 2;
var BROWSER_INTERNET_EXPLORER = 3;
var BROWSER_OTHER = 4;


function iTunesDetected() {

  // If we are on the Mac, assume that iTunes is installed.
  if (-1 != navigator.userAgent.indexOf("Macintosh")) return true;

  if (BROWSER_INTERNET_EXPLORER == detectedBrowser()) {
    return iTunesActiveXComponentInstalled();
  }

  else {
    // rely on what, if anything,  the user has already told us in a prior session
    return ('true' == getCookie('iTunesPresent'));
  }
}

function detectedBrowser() {
  if (-1 != navigator.userAgent.indexOf("AppleWebKit")) return BROWSER_SAFARI;
  if (-1 != navigator.userAgent.indexOf("Firefox")) return BROWSER_FIREFOX;
  if (-1 != navigator.userAgent.indexOf("Microsoft")) return BROWSER_INTERNET_EXPLORER;
  else return BROWSER_OTHER;
}

/**
 * We interpret the presence of the iTunes ActiveX Component to mean that iTunes itself has been installed.
 * @return true if the iTunes ActiveX Component was successfully loaded.
 */
function iTunesActiveXComponentInstalled() {
	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;
      dbg(typeof(detectObj.IsITMSHandlerAvailable));
    }

    if ((returnVal == null) || (typeof (returnVal) == "undefined")) returnVal = false;
	}
  dbg("ActiveX Control result: " + returnVal);
	return returnVal;
}

/**
 * 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 (iTunesDetected()) {
    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 replaceCurrentPageWithUrl(url);
    }
  }
  else {
    if (BROWSER_INTERNET_EXPLORER == detectedBrowser()) {
      // take IE users straight to the download page because we're sure they don't
      // have iTunes installed (they would have had the ActiveX component show up)
      window.location.replace(downloadUrl);
    }
    else { // for all other browsers, let the user tell us if iTunes is installed:
      document.getElementById(overridePanelId).style.display='block';
    }
  }
  return true;
}

/**
 * Open the given url (using iTunes) and make a best effort to close or go back in the current window.
 */
function replaceCurrentPageWithUrl(url) {

  window.location.href = url;

  info("Window History Length: " + window.history.length);
  if (window.history.length < 2) {
    setTimeout('window.close()', 100);
  } else {
    setTimeout('window.history.back()', 100);
  }
  return true;
}

function setCookie(cookieName,cookieValue,expireMillis) {
  var expire = new Date();
  expire.setTime(expire.getTime() + expireMillis);
  var cookie = cookieName + "=" + escape(cookieValue) + "; expires=" + expire.toGMTString();
  info("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 = unescape(keyValue[1]);
      break;
    }
  }
  info("getCookie(" + cookieName + "): " + result);
  return result;
}

function dbg(str) {
//  return alert(str);
}

function info(str) {
//  return alert(str);
}

