//
// 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/ them before changing it.
//

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

var ITUNES_INSTALLED_COOKIE_NAME="iTunesPresent";

function iTunesDetected() {

  // if we've already figured out that iTunes is present, rely on that data:
  if ('true' == getCookie(ITUNES_INSTALLED_COOKIE_NAME)) return true;

  // 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();
  }
  
  // last chance:
  return iTunesMozillaPluginDetected();
}

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("MSIE ")) 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('iTunesDetectorIE');
  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;
}

/**
 * We interpret the presence of the iTunes Firefox plugin to mean that iTunes itself has been installed.
 * @return true if the iTunes Firefox plugin was successfully loaded.
 */
function iTunesMozillaPluginDetected() {
  var result = false;
  if (navigator.plugins && navigator.plugins.length > 0) {
    for (var i=0; i < navigator.plugins.length; i++ ) {
      var plugin = navigator.plugins[i];
      var pluginName = plugin.name;
      if (pluginName.indexOf("iTunes Application Detector") > -1) { result = true }
    }
  }
  info("FF plugin detected: " + result);
  return result;
}

/**
 * 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) {
  url = url.replace(/^http/,"itms");
  // remove the trailing anchor indicator if necessary
  var hashIndex = url.indexOf("#");
  if (hashIndex > -1) { url = url.substring(0, hashIndex) }

  var affCookie = getCookie("a"); // <rdar://problem/7174153>
  if (affCookie) {
	  var separator = (url.indexOf("?") === -1) ? "?" : "&";
	  url += separator + "affC=" + encodeURIComponent(affCookie);
  }


  info("Trying to open " + url);

  if (getCookie('recentlyRedirected')) return false;
  setCookie('recentlyRedirected', true, 4000);

  if (iTunesDetected()) {
    setCookie(ITUNES_INSTALLED_COOKIE_NAME, true, 9999999999); 

    // 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. 
    // [2009-08 mjm: not sure this still applies, but it shouldn't hurt]
    setTimeout(function() { window.location.href = url; }, 1);
  }
  else {
    var b = detectedBrowser();
    if (BROWSER_INTERNET_EXPLORER == b || BROWSER_FIREFOX == b || BROWSER_SAFARI == b) {
      // 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 false;
}

function setCookie(cookieName,cookieValue,ttlMillis) {
  var expire = new Date();
  expire.setTime(expire.getTime() + ttlMillis);
  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];
    var keyValue = c.split('=');
    if (-1 < keyValue[0].indexOf(cookieName)) {
      result = unescape(keyValue[1]);
      break;
    }
  }
  dbg("getCookie(" + cookieName + "): " + result);
  return result;
}

function dbg(str) { /* try { return console.debug(str) } catch(e) { }; /**/ }

function info(str) { /* try { return console.info(str) } catch(e) { }; /**/ }

