


/**
 * Determine the browser machine's OS
 */
function getUserOS() {

    var agt=navigator.userAgent.toLowerCase();
    var userOS="Unknown"

    if ((agt.indexOf("win95")!=-1)||(agt.indexOf("windows 95")!=-1)) {
        userOS='Windows 95';
    } else if ((agt.indexOf("win98")!=-1)||(agt.indexOf("windows 98")!=-1)) {
        userOS='Windows 98';
    } else if ((agt.indexOf("winnt")!=-1)||(agt.indexOf("windows nt")!=-1)) {
        userOS='Windows NT';
    } else if ((agt.indexOf("winnt")!=-1)||(agt.indexOf("windows xp")!=-1)) {
        userOS='Windows XP';
    } else if ((agt.indexOf("win16")!=-1)||(agt.indexOf("windows 3.1")!=-1)) {
        userOS='Windows 3.x';
    } else if (agt.indexOf("macintosh")!=-1) { 
        if (agt.indexOf("mac os x")!=-1) {
            userOS='Mac OS X';
        } else if (agt.indexOf("pc")!=-1) {
            userOS='Mac PPC';
        } else {
            userOS='Mac 68K';
        }
    } else if (agt.indexOf("sunos")!=-1) {
        userOS='Unix Sun';
    } else if (agt.indexOf("irix")!=-1) {
        userOS='Unix SGI';
    } else if (agt.indexOf("hp-ux")!=-1) { 
        userOS='Unix HP';
    } else if (agt.indexOf("aix")!=-1) {
        userOS='Unix IBM'; 
    }

    return userOS;

}

/**
 * There are the comma-separated list of supported
 * Windows NT
 * Windows 2000
 * Windows XP
 * Mac OS X
 */
var supportedOS = "Windows XP, Windows NT, Mac OS X";

/**
 * Determine whether user's machine passes minimum
 * requirements to install iTunes player
 */
function isUserMachineGood() {

    var userOS = getUserOS();

    if (supportedOS.toLowerCase().indexOf(userOS.toLowerCase()) != -1) {
        return true;
    }
    return false;
}

/**
 * Determine weather aThing is defined or not, or is null
 * @param aThing The value to test.
 * @return (Boolean)
 */
function isUndefined(aThing)
{
    return (aThing === void 0);
}

var maxParamLength = 512;

/**
 * Opens the ITMS links for artist 
 *
 * @param link the link object which opens ITMS artist link
 * @param artistId Apple supplied Id for the artist
 */
function openArtistItmsLink(link, artistId, refId, context, amgId, name, genre, country) {
    var param = "artistId="  + artistId;

    if (!isUndefined(refId) && refId.length > 0) {
        param += "&refId=" + escape(refId) ;
    }
    if (!isUndefined(context) && context.length > 0) {
        param += "&context=" + escape(context) ;
    }
    if (!isUndefined(amgId) && amgId.length > 0) {
        param += "&amgId=" + escape(amgId) ;
    }
    if (!isUndefined(name) && name.length > 0 && (param.length + name.length) < maxParamLength) {
        name = name.replace(/\'/g, '\\\'');
        param += "&name=" + escape(name);
    }
    if (!isUndefined(genre)  && genre.length > 0 && (param.length + genre.length) < maxParamLength) {
        param += "&genre=" + escape(genre);
    }
    if (!isUndefined(country) && country.length > 0) {
        param += "&countryCode=" + escape(country);
    }
   
    return openItmsLink('AR', link, param);
}

/**
 * Opens the ITMS links for album
 *
 * @param link the link object which opens ITMS album link
 * @param albumId Apple supplied Id for the album
 */
function openAlbumItmsLink(link, albumId, refId, context, amgId, albumTitle, genre, artistName, albumLabel, country) {
    var param = "albumId="  + albumId;

    if (!isUndefined(refId) && refId.length > 0) {
        param += "&refId=" + escape(refId) ;
    }
    if (!isUndefined(context) && context.length > 0) {
        param += "&context=" + escape(context) ;
    }
    if (!isUndefined(amgId) && amgId.length > 0) {
        param += "&amgId=" + escape(amgId) ;
    }
    if (!isUndefined(albumTitle) && albumTitle.length > 0 && (param.length + albumTitle.length) < maxParamLength) {
        albumTitle = albumTitle.replace(/\'/g, '\\\'');
        param += "&name=" + escape(albumTitle);
    }
    if (!isUndefined(artistName) && artistName.length > 0 && (param.length + artistName.length) < maxParamLength) {
        artistName = artistName.replace(/\'/g, '\\\'');
        param += "&artistName=" + escape(artistName);
    }
    if (!isUndefined(albumLabel) && albumLabel.length > 0 && (param.length + albumLabel.length) < maxParamLength) {
        albumLabel = albumLabel.replace(/\'/g, '\\\'');
        param += "&albumLabel=" + escape(albumLabel);
    }
    if (!isUndefined(genre) && genre.length > 0 && (param.length + genre.length) < maxParamLength) {
        param += "&genre=" + escape(genre);
    }
    if (!isUndefined(country) && country.length > 0) {
        param += "&countryCode=" + escape(country);
    }
 

    return openItmsLink('AL', link, param);
}

/**
 * Opens the ITMS links for song 
 *
 * @param link the link object which opens ITMS song link
 * @param albumId Apple supplied Id for the album
 * @param trackId Apple supplied Id for the song
 */
function openSongItmsLink(link, albumId, trackId, refId, context, albumAmgId, trackAmgId, title, trackNum, genre, artistName, albumTitle, albumLabel, country) {
    var param = "trackId=" + trackId + "&albumId="  + albumId;

    if (!isUndefined(refId) && refId.length > 0) {
        param += "&refId=" + escape(refId) ;
    }
    if (!isUndefined(context) && context.length > 0) {
        param += "&context=" + escape(context) ;
    }
    if (!isUndefined(albumAmgId) && albumAmgId.length > 0) {
        param += "&albumAmgId=" + escape(albumAmgId) ;
    }
    if (!isUndefined(trackAmgId) && trackAmgId.length > 0) {
        param += "&trackAmgId=" + escape(trackAmgId) ;
    }
    if (!isUndefined(title) && title.length > 0 && (param.length + title.length) < maxParamLength) {
        title = title.replace(/\'/g, '\\\'');
        param += "&name=" + escape(title) ;
    }
    if (!isUndefined(trackNum) && trackNum.length > 0 && (param.length + trackNum.length) < maxParamLength) {
        param += "&trackNum=" + escape(trackNum) ;
    }
    if (!isUndefined(albumTitle) && albumTitle.length > 0 && (param.length + albumTitle.length) < maxParamLength) {
        albumTitle = albumTitle.replace(/\'/g, '\\\'');
        param += "&albumTitle=" + escape(albumTitle);
    }
    if (!isUndefined(artistName) && artistName.length > 0 && (param.length + artistName.length) < maxParamLength) {
        artistName = artistName.replace(/\'/g, '\\\'');
        param += "&artistName=" + escape(artistName);
    }
    if (!isUndefined(albumLabel) && albumLabel.length > 0 && (param.length + albumLabel.length) < maxParamLength) {
        albumLabel = albumLabel.replace(/\'/g, '\\\'');
        param += "&albumLabel=" + escape(albumLabel);
    }
    if (!isUndefined(genre) && genre.length > 0 && (param.length + genre.length) < maxParamLength) {
        param += "&genre=" + escape(genre);
    }
    if (!isUndefined(country) && country.length > 0) {
        param += "&countryCode=" + escape(country);
    }
    
    return openItmsLink('TR', link, param);
}

/**
 * Opens the ITMS links for the artist and/or album and/or song searches 
 *
 * @param link the link object which opens ITMS artist link
 * @param artistTerm search term for artist
 * @param albumTerm search term for album
 * @param songTerm search term for song
 */
function openSearchItmsLink(link, artistTerm, albumTerm, songTerm, refId, context, country) {
    var param = '';
    var append = false;
    if (!isUndefined(artistTerm) && artistTerm.length > 0) {
        artistTerm = artistTerm.replace(/\'/g, '\\\'');
        param = "artistTerm=" + escape(artistTerm);
        append = true;
    }
    if (!isUndefined(albumTerm) && albumTerm.length > 0) {
        albumTerm = albumTerm.replace(/\'/g, '\\\'');
        if (append) {
            param += "&albumTerm=" + escape(albumTerm);
        } else {
            param = "albumTerm=" + escape(albumTerm);
            append = true;
        }
    }
    if (!isUndefined(songTerm) && songTerm.length > 0) {
        songTerm = songTerm.replace(/\'/g, '\\\'');
        if (append) {
            param += "&songTerm=" + escape(songTerm);
        } else {
            param = "songTerm=" + escape(songTerm);
            append = true;
        }
    }
    if (!isUndefined(refId) && refId.length > 0) {
        param += "&refId=" + escape(refId) ;
    }
    if (!isUndefined(context) && context.length > 0) {
        param += "&context=" + escape(context) ;
    }

    if (!isUndefined(country) && country.length > 0) {
        param += "&countryCode=" + escape(country);
    }

    return openItmsLink('SS', link, param);
}

/**
 * Opens the ITMS links for generic search
 *
 * @param link the link object which opens ITMS song link
 * @param albumId Apple supplied Id for the album
 * @param songId Apple supplied Id for the song
 */
function openGenericSearchItmsLink(link, searchTerm, refId, context, country) {
    searchTerm = searchTerm.replace(/\'/g, '\\\'');
    var param = "term=" + escape(searchTerm);
    if (!isUndefined(refId) && refId.length > 0) {
        param += "&refId=" + escape(refId) ;
    }
    if (!isUndefined(context) && context.length > 0) {
        param += "&context=" + escape(context) ;
    }
    if (!isUndefined(country) && country.length > 0) {
        param += "&countryCode=" + escape(country);
    }
    return openItmsLink('GS', link, param);
}

function isAOLClient() {
    var agent = navigator.userAgent.toLowerCase();
    return (agent.indexOf('aol') != -1);
}

function isAOL9OrAbove() {

    var agent = navigator.userAgent.toLowerCase();
    if (agent.indexOf('aol') == -1) return false;

    if ((agent.indexOf('aol 3') != -1) || (agent.indexOf('aol/3')) != -1) return false;
    if ((agent.indexOf('aol 4') != -1) || (agent.indexOf('aol/4')) != -1) return false;
    if ((agent.indexOf('aol 5') != -1) || (agent.indexOf('aol/5')) != -1) return false;
    if ((agent.indexOf('aol 6') != -1) || (agent.indexOf('aol/6')) != -1) return false;
    if ((agent.indexOf('aol 7') != -1) || (agent.indexOf('aol/7')) != -1) return false;
    if ((agent.indexOf('aol 8') != -1) || (agent.indexOf('aol/8')) != -1) return false;
    return true;
}

function openItmsLink(linkType, link, params) {
    //  var redirectServer = "http://musicsearch.staging.digitalcity.com/itms.adp";
    //  var redirectServer = "https://mftickets.office.aol.com/itunes/itms.adp";
        var redirectServer = "http://itunes.aol.com/itms.adp";
    
    var aolParams = "_AOLFORM=w1.h1.p9.R1";
    var itmsUrl;
    if (linkType == 'SS') {
        itmsUrl = "itms://phobos.apple.com/WebObjects/MZSearch.woa/wa/advancedSearchResults";
    } else if (linkType == 'AR') {
        itmsUrl = "itms://phobos.apple.com/WebObjects/MZStore.woa/wa/viewArtist";
    } else if (linkType == 'AL') {
        itmsUrl = "itms://phobos.apple.com/WebObjects/MZStore.woa/wa/viewAlbum";
    } else if (linkType == 'TR') {
        itmsUrl = "itms://phobos.apple.com/WebObjects/MZStore.woa/wa/viewAlbum";
    } else if (linkType == 'GS') {
        itmsUrl = "itms://phobos.apple.com/WebObjects/MZSearch.woa/wa/search";
    } else {
        // not a valid link type
        return false;
    }
    /*
    if (params != null && params != "") {
        params += "%26partnerId=1";
    } else {
        params = "partnerId=1";
    }
    itmsUrl += "?" + params; 
    */
    // var customHref = redirectServer + '?url=' + escape(itmsUrl) + '&' + aolParams;
    params = params.replace(/\'/g, '\\\'');
    var customHref = redirectServer + '?type=' + linkType + '&' + params + '&' + aolParams;
    // document.write(customHref);
    if (isAOL9OrAbove()) {
        link.href = customHref;
        return true;
    } else {
        // window.open(customHref, 'iTunes','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=1,height=1,bottom=20,bottom=20');
        // link.href = "javascript:void window.open('" + customHref + "', 'iTunes','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=1,height=1,bottom=20,bottom=20')";
        link.href = "javascript:void window.open('" + customHref + "', 'iTunes','toolbar=no,location=no,directories=no,scrollbars=yes,menubar=no,status=yes,resizable=yes,width=330,height=135,bottom=0')";
        return true;
    }
}

/**
 * Detect the presence of the iTunes player using the iTunes dectector ActiveX control.
 * The calling page needs to include the <object> tag containing the ActiveX.
 * Details are in: http://www.apple.com/itunes/linkmaker/ 
 *
 * Logic used from http://ax.phobos.apple.com.edgesuite.net/detection/itmsCheck.js 
 */
function doDetector() {
    var detectObj = iTunesDetector;
    var returnVal = true; // If we can't load the ActiveX control, assume we have ITMS

    if ( (detectObj != null) && (typeof(detectObj) != "undefined" ) ) {
        if (typeof(detectObj.IsITMSHandlerAvailable) != "undefined")
            returnVal = detectObj.IsITMSHandlerAvailable;

        if ((returnVal == null) || ( typeof ( returnVal ) == "undefined" ))
            returnVal = true;

    }

    return returnVal;
}

/**
 * If iTunes installer is present already - from AOL Client - run the installer
 * to install iTunes client. Also check for updates to the iTunes player.
 *
 * Logic used from http://ax.phobos.apple.com.edgesuite.net/detection/itmsCheck.js 
 */
function runITInstall()
{
	var		installerRun = false;

    var agent = navigator.userAgent.toLowerCase();
    var isPC = false;
    isPC = agent.indexOf("win") != -1;
	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;
}

/**
 * Starts the iTunes player and deep links to it.
 * Details are in: http://www.apple.com/itunes/linkmaker/ 
 *
 * Depends on doDetector() and runITInstall()
 * Logic used from http://ax.phobos.apple.com.edgesuite.net/detection/itmsCheck.js 
 */
function doITMSClick(itmsurl, downloadurl, country) {

    var haveITMS = true;
    var agent;
    var isPC = false;

    if (country == null || country == undefined) {
        var thiscountry = "US";
    } else {
        var thiscountry = country;
    }

    agent=navigator.userAgent.toLowerCase();
    isPC = agent.indexOf("win") != -1;
    var isMac = navigator.userAgent.indexOf("Mac") != -1
    // If we are on the Mac, we just assume we have an ITMS handler

    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 (isPC) {
            if (navigator.appName.indexOf('Microsoft') != -1) { 
                haveITMS = doDetector();
                isPC = doDetector();
            }
        }
    }

    if (haveITMS) {
        var oframe = document.getElementById("objFrame");
        if (oframe != null) {
            try {
                oframe.contentWindow.location = itmsurl;
            } catch (exception) { ; }
        } else {
            window.location = itmsurl;
        }
        var thiswin = parent.self;
        if (isAOLClient()) {
            if (!isUndefined(thiswin)) {
                thiswin.opener = parent.self;
                setTimeout('try { thiswin.close(); } catch(exception) { ; }', 5000); 
            }
            setTimeout('parent.close()', 5000);
        }
        setTimeout('window.close()', 5000);
    } else {
             
        if (!runITInstall()) {
            if (isAOL9OrAbove()) {
                var thiswin = parent.self;
                thiswin.opener = parent.self;
                if (isUserMachineGood()) {
                    // window.location = "http://www.apple.com/itunes/download/?_AOLFORM=w900.h900.p1.R1";
                    //window.location = "http://channelevents.aol.com/music/iTunes/bbc.adp?_AOLFORM=w900.h900.p1.R1";
                    window.location = "aol://1722:ituneswelcome";
                } else {
                    // thiswin.location = "http://musicsearch.staging.digitalcity.com/itunes_promo.adp?_AOLFORM=w700.h400.p1.R1";
                    if (thiscountry == "UK") {
                          window.location = "aol://1722:itunes";
                      } else if (thiscountry == "FR") {
                          window.location = "aol://4344:998.itreq.1587367.773485097";
                      } else if (thiscountry == "DE") {
                          window.location = "http://channel1.aolsvc.de/index.jsp?sg=Musik_iTunes&cid=1264543";
                      } else {
                          window.location = "http://itunes.aol.com/itunes_promo.adp?_AOLFORM=w700.h400.p1.R1";
                   }
                }
                if (isAOLClient()) {
                    if (!isUndefined(thiswin)) {
                        setTimeout('try { thiswin.close(); } catch(exception) { ; }', 5000);
                    }
                    setTimeout('parent.close()', 5000);
                }
                setTimeout('window.close()', 5000);
            } else {
                if (isUserMachineGood()) {
                    window.resizeTo(900,900);
                    // window.location = "http://www.apple.com/itunes/download/?_AOLFORM=w900.h900.p1.R1";
                    // window.location = "http://channelevents.aol.com/music/iTunes/bbc.adp?_AOLFORM=w900.h900.p1.R1";
                    if (isAOLClient()) {
                        window.location = "aol://1722:ituneswelcome";
                    } else {
                        window.location = "http://www.apple.com/itunes/download/";
                    }
                } else {
                    window.resizeTo(700,400);
                    // window.location = "http://musicsearch.staging.digitalcity.com/itunes_promo.adp?_AOLFORM=w700.h400.p1.R1";
                    if (thiscountry == "UK") {
                          window.location = "aol://1722:itunes";
                      } else if (thiscountry == "FR") {
                          window.location = "aol://4344:998.itreq.1587367.773485097";
                      } else if (thiscountry == "DE") {
                          window.location = "http://channel1.aolsvc.de/index.jsp?sg=Musik_iTunes&cid=1264543";
                      } else {
                          window.location = "http://itunes.aol.com/itunes_promo.adp?_AOLFORM=w700.h400.p1.R1";
                   }
                }
            }
        }
    }
    return true;
    
}

function openItmsBlank(link) {
    var redirectServer = "http://itunes.aol.com/itms.adp";
    
    var aolParams = "_AOLFORM=w1.h1.p9.R1";
    var itmsUrl;

    var customHref = redirectServer + '?' + aolParams;
    if (isAOL9OrAbove()) {
        link.href = customHref;
        return true;
    } else {
        link.href = "javascript:void window.open('" + customHref + "', 'iTunes','toolbar=no,location=no,directories=no,scrollbars=yes,menubar=no,status=yes,resizable=yes,width=330,height=135,bottom=0')";
        return true;
    }
}

