<!--
/************************************************************************

FILE: kdx.js
DESCRIPTION: Utility functions used by the KDM 4.02.

Copyright (c) 2004-2005 Kontiki Inc.

*************************************************************************/

//////////////////////////////////////////////////////////////////////////
//
// Include file.
//
//////////////////////////////////////////////////////////////////////////
document.write('<script src="kdx_init.js"><\/script>');

//////////////////////////////////////////////////////////////////////////
//
// Initalization of global keyboard events handler.
//
//////////////////////////////////////////////////////////////////////////

function catchKey(e)
{
	if(!e) e = window.event;
	
	if(e.altKey){
		if(e.keyCode == 77){
			getApi().downloadMonitor(true);
		}
	}
}

document.attachEvent("onkeydown", catchKey);

//////////////////////////////////////////////////////////////////////////
//
// Enable logging
//
//////////////////////////////////////////////////////////////////////////
var gWriteLog = true;

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getApi()
//
// DESCRIPTION: Instantiate global API object.
//
//////////////////////////////////////////////////////////////////////////

var gKDXApi = null;
function getApi()
{
	if (gKDXApi == null)
	{
        var api = new ActiveXObject("KDX.SecureApi");
        api.authorize(gAuthToken, gAuthSignature); 
        gKDXApi = api;
	}
	return gKDXApi;
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getPref(i_name, i_default)
//
// DESCRIPTION: Generic get pref method. You can supply a default
// in case it fails.
//
//////////////////////////////////////////////////////////////////////////
function getPref(i_name, i_default)
{
    var theValue = i_default;
    try
    {
        theValue = getApi().pref( i_name );
    }
    catch( e ){}
    
    return theValue;
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: setPref(i_name, i_value)
//
// DESCRIPTION: Generic set pref "i_name" with value "i_value".
//
//////////////////////////////////////////////////////////////////////////
function setPref(i_name, i_value)
{
	var theValue;
    try
    {
        theValue = getApi().pref( i_name ) =  i_value;
    }
    catch( e ){}
    
    return theValue;
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getPrefAsString(i_name)
//
// DESCRIPTION: Converts pref value to string.
//
//////////////////////////////////////////////////////////////////////////
function getPrefAsString(i_name)
{
    try
    {
        return getApi().prefstr( i_name );
    }
    catch( e )
    {
        return "";
    }
}

function getBoolValue(str){
	if(str && (str == "true" || str == "1" || str == 1))
		return true;
	else
		return false;
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: isPrefLocked(i_name)
//
// DESCRIPTION: Returns true if pref is locked by NetManager.
//
//////////////////////////////////////////////////////////////////////////
function isPrefLocked(i_name)
{
    return getApi().isPrefLocked( i_name );
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getFrame(i_moid, i_name)
//
// DESCRIPTION: Returns null if KFrame window does not exist.
//
//////////////////////////////////////////////////////////////////////////
function getFrame(i_moid, i_name)
{
    try
    {
        return getApi().getFrame(i_moid,  i_name );
    }
    catch(e)
    {
        return null;
    }
}

//////////////////////////////////////////////////////////////////////////
//
// Central place to launch key system elements.
//
//////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: launchAbout()
//
// DESCRIPTION: Launches About dialog.
//
//////////////////////////////////////////////////////////////////////////
function launchAbout()
{
    getApi().launchTemplate( "cache:kdmx_about.html", "class=dialog,width=380,height=210,position=1,resize=0,maxbtn=0,visible=false", "", "about");
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: launchComplete(i_moid)
//
// DESCRIPTION: Launches Delivery Complete dialog for a given delivery,
// passed in via "i_moid".
//
//////////////////////////////////////////////////////////////////////////
function launchComplete(i_moid)
{
	try{
		if(window.external.ui.moid != null)
			launchDM(window.external.ui.moid);
	}catch(e){
		return 0;
	}
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: launchEmail(i_moid, i_url)
//
// DESCRIPTION: Launches Email This dialog for a given delivery,
// passed in via "i_moid". The Email This URL is also passed in.
//
//////////////////////////////////////////////////////////////////////////
function launchEmail(i_moid, i_url)
{
    if (checkOnlineState() && i_url != "")
    {
		try{
			var windowManager = getFrame("", "windowManager");
			if(windowManager != null) windowManager.document.parentWindow.launchEmailWindow(i_moid, i_url);
			else {
				var tmpUrl = i_url + i_moid;
				emailWindow = window.open(tmpUrl, "emailthis", "height=640,width=460,status=no,toolbar=no,location=no,scrollbars=yes,maxbtn=0", true);
			}
		}catch(e){}
    }
    else launchOffline();
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: launchError(data)
//
// DESCRIPTION: Launches Error dialog for a given error, passed in via
// "data" object.
//
//////////////////////////////////////////////////////////////////////////
function launchError(data, i_moid)
{
    //stash the event data away for use in the following page...
	if(i_moid){
		var errorWindow = getApi().launchTemplate("cache:kdmx_error.html", "class=dialog,position=1,resize=0,maxbtn=0,visible=false,width=400,height=125", i_moid, "error");
		errorWindow.ui.param("eventData") = data;
	}else{
		var errorWindow = getApi().launchTemplate("cache:kdmx_error.html", "class=dialog,position=1,resize=0,maxbtn=0,visible=false,width=400,height=125", "", "error");
	}
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: launchDM()
//
// DESCRIPTION: Launches Delivery Status.
//
//////////////////////////////////////////////////////////////////////////

function launchDM(moid)
{
	if(moid != null){

		var dlitem = null;
		try
		{
			dlitem = new KDXDownload(moid);
		}
		catch (e) 
		{   
			return; 
		}
		
		if(dlitem.isSubscription())
			return;

		if(getApi().valueExists(moid, "ad"))
		if(parseInt(getApi().value(moid, "ad"))){
			getApi().value(moid, "hidden") = "true";
			return;
		}

		if(getApi().valueExists(moid, "playlist"))
		if(parseInt(getApi().value(moid, "playlist"))){
			getApi().value(moid, "hidden")="true";
			return;
		}
		
		if(getApi().valueExists(moid, "hidden"))
		if(getBoolValue(getApi().value(moid, "hidden"))){
			getApi().value(moid, "hidden")="true";
			return;
		}

		var frameObj = getFrame("", "dm");
		if(frameObj)
			frameObj.navigate("cache:kdmx_dm.html?moid="+moid);
		else
			getApi().launchTemplate("cache:kdmx_dm.html?moid="+moid, "class=dialog,width=475,height=140,position=2,resize=0,maxbtn=0,visible=false", "", "dm");
	}
}


//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: showCompleted()
//
// DESCRIPTION: Launches Main Tabs.
//
//////////////////////////////////////////////////////////////////////////

function showCompleted(tabNum){
	if(!tabNum)
		tabNum = 0;
	if(checkOnlineState()){
		var url = "cache:kdmx_loader.html";
		var style = "class=dialog,visible=false,tabNum="+tabNum;
	
		getApi().launchTemplate( url, style, "", "loader");
	}
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getEm()
//
// DESCRIPTION: Returns link to Experience Manager instance.
//
//////////////////////////////////////////////////////////////////////////

function launchEMframe() {
	var expMgr = false;
	var EMframe = getFrame("", "EMframe");
	if(!EMframe) {
		var url = "cache:kdmx_EM.html";
		var style = "class=dialog,visible=0";

		getApi().launchTemplate( url, style, "", "EMframe");
	}
}

function getEm() {
	var expMgr = false;
	var EMframe = getFrame("", "EMframe");
	if(!EMframe) {		
		launchEMframe();
		try{
			var EMframe = getFrame("", "EMframe");
			expMgr = EMframe.document.parentWindow.initEm();
		}catch(e){expMgr = false;};
	} else {
		try {
			expMgr = EMframe.document.parentWindow.initEm();
		}catch(e){expMgr = false;}		
	}
	return expMgr;
}


//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: launchEM(moid, expMgr)
//
// DESCRIPTION: get ad list and start downloading
//
//////////////////////////////////////////////////////////////////////////
function launchEM(moid, expMgr) {

	try{
	  	var downloadItem = new KDXDownload(moid);
	} catch (e) {
		return; 
	}
	
	if(!downloadItem.isSubscription()){
		if(getApi().valueExists(moid, "ad")){
			if(1 != parseInt(getApi().value(moid, "ad"))){
				
				var expMgr = getEm();
				if(!expMgr) return;

				var downloadList = expMgr.GetContentList(franId).toArray();
				var downloadListLength = downloadList.length;
				for(var i=0; i<downloadListLength; i++) {
					if(downloadList[i].indexOf("http://") < 0){
						try{
							var downloadItem = new KDXDownload(downloadList[i]);
							if(downloadItem.isComplete())
								updateAdStatus(downloadList[i], 1);
							else
							if(!downloadItem.isSubscription())
								getApi().loadAsynch(downloadList[i], 10);
						} catch (e) {
							getApi().loadAsynch(downloadList[i], 10);
						}
					}
				}
				//checkAd(expMgr);
			}
		}
	}
}

function checkAd(expMgr) {
	var contentArray = getApi().getDownloadItems(true, false).toArray();
	var contentArrayLength = contentArray.length;
	for (var i=0; i<contentArrayLength; i++) {
		if(getApi().valueExists(contentArray[i], "ad")){
			if(parseInt(getApi().value(contentArray[i], "ad")) == 1){
				expMgr.UpdateDownloadStatus(contentArray[i], (getApi().getStrValue("download_state") == "Complete"));
			}
		}
	}
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: buildPlayList(i_moid, expMgr)
//
// DESCRIPTION: takes playlist moid and fire KDMX_STATE_PLAYABLE
//
//////////////////////////////////////////////////////////////////////////
function buildPlayList(i_moid, expMgr) {
	var urn = getTopOrderedList(i_moid, expMgr);
	if(!urn){
		urn = getSimpleOderedList(i_moid, expMgr);
	}
	setTimeout("launchEM(\""+i_moid+"\");", 10000);
	if(urn) getApi().play(urn);
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getTopOrderedList(i_moid, expMgr)
//
// DESCRIPTION: create TopTen playlist
//
//////////////////////////////////////////////////////////////////////////
function getTopOrderedList(i_moid, expMgr){

	//alert("Starting build list!");
	var playlistMoid = "";
	if(getApi().valueExists(i_moid, "parent_id"))
		subMoid = getApi().value(i_moid, "parent_id");
	else return false;
	//alert("subMoid "+subMoid);

	if(playlistMoid = getSubscriptionPlaylist(subMoid)){

		var ksxString  = "<ASX version = \"3.0\">\r\n";
		var xmlDoc = new ActiveXObject("Msxml.DOMDocument");
		var playlistPath = getApi().value(playlistMoid, "filename_physical");
	    xmlDoc.async = false;
		var itemMoid = 0;
		var dlitem;
		var itemCount = 0;
		var itemfounded = false;
		var playlistObj = null;

		if(xmlDoc.load(playlistPath)){
			var root = xmlDoc.documentElement;
	        if( root != null ){
	            var nodes = root.childNodes;
	            if( nodes != null ){

					//search Item Number
					var countDownItem = findNodeItem(nodes, i_moid)
					if(countDownItem < nodes.length) {
						var contentObj = getCompleteItemsArray(nodes, i_moid);
						var itemsArray = contentObj.contentArray;
						var itemsArrayLength = itemsArray.length;
						for(var i=0; i<itemsArrayLength; i++){
							itemMoid = itemsArray[i];
							if(i_moid != itemMoid){
								playlistObj = getAdPlayList(itemMoid, expMgr);
								ksxString += playlistObj.playList;
								if(!itemfounded) itemCount += playlistObj.totalItems;
							} else {
								setPref("ui.fistItemMoid", itemMoid);
								playlistObj = getAdPlayList(itemMoid, expMgr);
								ksxString += playlistObj.playList;
								itemfounded = true;
							}
						}
					} else return false;
				}
			}
		}
	} else
		return false;
	ksxString += "</ASX>";
	try{
		playListUrn = getApi().createPlaylist("MyPlayList", ksxString, true);
	} catch(e) {
		alert("Can't play this file. Folder 'My deliveries\\KDX' is deleted or renamed");
		return false;
	}
	setTempVars(itemCount);
	return playListUrn;
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: findNodeItem(nodes, i_moid)
//
// DESCRIPTION: find node item in XML playlist for subscription
//
//////////////////////////////////////////////////////////////////////////
function findNodeItem(nodes, i_moid) {
	var countDownItem = nodes.length;
	var nodesLength = nodes.length;
	for(var lNode=0; lNode<nodesLength; lNode++ ){
		if(nodes.item(lNode).nodeName == "item"){
			if(i_moid == nodes.item(lNode).getAttribute("moid")){
				countDownItem = lNode;
				break;
			}
		}
	}
	return countDownItem;
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getItemNum(nodes, i_moid)
//
// DESCRIPTION: find node item in XML playlist for subscription
//
//////////////////////////////////////////////////////////////////////////
function getCompleteItemsArray(nodes, i_moid){
	var dlitem = null;
	var itemMoid = null;
	var itemNum = null;
	var itemsArray = new Array();
	var itemFounded = false
	for(var lNode=nodes.length-1; lNode>=0; lNode--){
		if(nodes.item(lNode).nodeName == "item"){
			itemMoid = nodes.item(lNode).getAttribute("moid");
			try {
				dlitem = new KDXDownload(itemMoid);
			} catch (e) { continue; }
		
			if(dlitem.isComplete()){
				itemsArray[itemsArray.length] = itemMoid;
				if(i_moid == itemMoid) itemFounded = true;
				if(!itemFounded) itemNum++;
			}
		}
	}
	
	var returnObj = new Object();
	returnObj.contentArray = itemsArray;
	returnObj.contentNum = itemNum;
	return returnObj;
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getSimpleOderedList(i_moid, expMgr)
//
// DESCRIPTION: create playlist for one item
//
//////////////////////////////////////////////////////////////////////////
function getSimpleOderedList(i_moid, expMgr) {
	//var expMgr = getEm();

	var ksxString;
	ksxString = "<ASX version = \"3.0\">\r\n";
	var playListObj = getAdPlayList(i_moid, expMgr); 
	ksxString += playListObj.playList;
	
	if(ksxString.indexOf(i_moid)<0){
		ksxString += getPlaylistItem(i_moid, null, false);
	}
	ksxString += "</ASX> ";
	try {
		var playListUrn = getApi().createPlaylist("MyPlayList", ksxString, true);
	} catch(e) {
		alert("Can't play this file. Folder 'My deliveries\\KDX' is deleted or renamed");
		return false;
	}
	setTempVars(0);
	setPref("ui.fistItemMoid", i_moid);
	return playListUrn;
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getAdPlayList(i_moid, expMgr)
//
// DESCRIPTION: return XML playlist conten+ads
//
//////////////////////////////////////////////////////////////////////////
function getAdPlayList(i_moid, expMgr) {

	var tempMoid = i_moid + " "; // reSaved Moid in other memory area
	var contentTitle = getApi().value(i_moid, "short_title");
	try{
		var playList = expMgr.GetPlayList(franId, tempMoid.slice(0, i_moid.length)).toArray();		
		if(gWriteLog) for(var i=0; i<playList.length; i++)	getApi().log("!!!!!!! getAdPlayList REPORTS:  For content=" + contentTitle + " GetPlayList returned item["+i+"] is "+playList[i]);
	} catch(e) {
		if(gWriteLog) getApi().log("!!!!!!! getAdPlayList REPORTS:  For content=" + contentTitle + "Exception while GetPlayList");
		var ksxString = getPlaylistItem(i_moid, null, false);
		var returnObj = new Object();
		returnObj.playList = ksxString;
		returnObj.totalItems = 1;
		return returnObj;
	}

	var ksxString = "";
	var testDlItem;
	var returnObj = new Object();
	var itemsCount = 0;

	for(var i=0; i<playList.length; i++){
		if(playList[i].indexOf("http://") < 0) {
			try {			
				testDlItem = new KDXDownload(playList[i]);
				if(testDlItem.isComplete()){
					if(i_moid != playList[i]) {
						ksxString += getPlaylistItem(playList[i], playList[i+1]?playList[i+1]:null, true);
					} else {
						ksxString += getPlaylistItem(playList[i], playList[i+1]?playList[i+1]:null, false);
					}
					itemsCount++;
				}
			}
			catch (e) {
				getApi().loadAsynch(playList[i], 10);
				continue; 
			}
		}
	}
	returnObj.playList = ksxString;
	returnObj.totalItems = itemsCount;
	return returnObj;
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getPlaylistItem(i_moid, bannnerURL, ad)
//
// DESCRIPTION: return string XML for playlist item
//
//////////////////////////////////////////////////////////////////////////
function getPlaylistItem(i_moid, bannnerURL, ad) {
	var ksxString = "";
	ksxString += "<Entry>\r\n";
	ksxString += "<Param Name = \"ad\" Value = \""+ad+"\" />\r\n";
	if(bannnerURL) if(bannnerURL.indexOf("http://") > -1){
		ksxString += "<Param Name = \"banner\" Value = \""+bannnerURL+"\" />\r\n";
	}
	ksxString += "<Param Name = \"moid\" Value = \""+i_moid.slice(3, i_moid.length)+"\" />\r\n";
	if(!ad) {
		try{
			var downloadItem = new KDXDownload(i_moid);
			if(downloadItem.isHttpStreaming()) ksxString += "<Ref href = \""+downloadItem.getValue("streaming_url")+"\" />\r\n";
			else ksxString += "<Ref href = \"" +i_moid+ "\" />\r\n";
		} catch(e) {
			ksxString += "<Ref href = \"" +i_moid+ "\" />\r\n";
		}
	} else {
		ksxString += "<Ref href = \"" +i_moid+ "\" />\r\n";
	}
	ksxString += "</Entry>\r\n";
	if(gWriteLog)	getApi().log("!!!!!!! getPlaylistItem REPORTS: returned following ksxString:\n"+ksxString);
	return ksxString;
}

function checkMoid(moid) {
	var contentArray = getApi().getDownloadItems(true, false).toArray();
	for(var i=0; i<contentArray.length; i++) {
		if(contentArray[i] == moid) return true;
		else return false;
	}
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: updateAdStatus(moid, status)
//
// DESCRIPTION: Update download status for ads
//
//////////////////////////////////////////////////////////////////////////
function updateAdStatus(moid, status) {
	var expMgr = getEm();
	if(!expMgr) return;

	if(gWriteLog) getApi().log("!!!!!!! kdx.js REPORTS: updateAdStatus(" + moid + ", " + franId + ", "+ status + ")");	
	expMgr.UpdateDownloadStatus(moid, franId, status);
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: launchOffline()
//
// DESCRIPTION: Launches Offline dialog.
//
//////////////////////////////////////////////////////////////////////////
function launchOffline(error, i_moid)
{
	if(error == "playerError" && i_moid)
    	getApi().launchTemplate( "cache:kdmx_offline.html", "class=dialog,position=1,resize=0,maxbtn=0,width=400,height=125,visible=false,playerError='true',ext_moid="+i_moid, "", "offline");
	else
		getApi().launchTemplate( "cache:kdmx_offline.html", "class=dialog,position=1,resize=0,maxbtn=0,width=400,height=125,visible=false", "", "offline");
}


//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: launchPlayer(i_moid)
//
// DESCRIPTION: Launches Player for a given delivery, passed in via
// "i_moid".
//
//////////////////////////////////////////////////////////////////////////
function launchPlayer(i_moid){
	if(!checkOnlineState()){
		launchOffline("playerError", i_moid);
		return;
	}

	var expMgr = getEm();
	if(!expMgr) return;

	buildPlayList(i_moid, expMgr)
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: setTempVars(tempVar)
//
// DESCRIPTION: Launches KDX Secure Frame, and saave in this frame temp param that can be used in player
//
//////////////////////////////////////////////////////////////////////////
function setTempVars(tempVar){
	setPref("ui.tempVariable", String(tempVar));
}

function getSubscriptionList(i_moid){
	var items = getApi().getDownloadItems(true, false).toArray();
	var subscriptionItems = new Array();
	var j = 0;
	for(i=0; i< items.length; i++){
			try
		  {
			  dlitem = new KDXDownload(items[i]);
		  }
		  catch (e) { continue; }

		if(getApi().valueExists(items[i], "parent_id"))
		if(getApi().value(items[i], "parent_id") == i_moid)
		if(dlitem.isComplete()){
			subscriptionItems[j] = items[i];
			j++;
		}
	}
	if(j>0)
		return subscriptionItems;
	else
		return false;
}

function getSubscriptionPlaylist(i_moid){

	try	{
		dlitem = new KDXDownload(i_moid);
	} catch (e) { return false; }

	var items = getApi().getDownloadItems(true, false).toArray();
	var currentPlayList = false;
	for(i=0; i< items.length; i++){
		try
		  {
			  dlitem = new KDXDownload(items[i]);
		  }
		  catch (e) { continue; }

		if(getApi().valueExists(items[i], "parent_id"))
		if(getApi().value(items[i], "parent_id") == i_moid)
		if(getApi().valueExists(items[i], "playlist"))
		if(parseInt(getApi().value(items[i], "playlist")))
		if(dlitem.isComplete()) {
			if(!currentPlayList) currentPlayList = items[i];
			else if(parseInt(getApi().valueStr(items[i], "file_modified_time")) >=
				parseInt(getApi().valueStr(currentPlayList, "file_modified_time")))
				currentPlayList = items[i];
		}
	}
	
	return currentPlayList;
}

function getSubscriptionPlaylists(i_moid){

	try	{
		dlitem = new KDXDownload(i_moid);
	} catch (e) { return false; }

	var items = getApi().getDownloadItems(true, false).toArray();
	var playlistsArray = new Array();
	var playlistsCount = 0;
	var currentPlayList = false;
	for(i=0; i< items.length; i++){
		try
		  {
			  dlitem = new KDXDownload(items[i]);
		  }
		  catch (e) { continue; }

		if(getApi().valueExists(items[i], "parent_id"))
		if(getApi().value(items[i], "parent_id") == i_moid)
		if(getApi().valueExists(items[i], "playlist"))
		if(parseInt(getApi().value(items[i], "playlist"))){
			playlistsArray[playlistsCount] = items[i];
			playlistsCount++;
		}
	}
	
	return playlistsArray;
}

// Empty playlists deleting related code

// Returns an array of moids of items in the given playlist
function getPlaylistItems(dlitem){
	var moids = new Array();
	var xmlDoc = new ActiveXObject("Msxml.DOMDocument");
	var playlistPath = dlitem.getValue("filename_physical");
    xmlDoc.async = false;

	if(xmlDoc.load(playlistPath)){
		var root = xmlDoc.documentElement;
        if( root != null ){
            var nodes = root.childNodes;
            if( nodes != null ){
				for( lNode=0; lNode<nodes.length; lNode++ ){
	                key = nodes.item(lNode).nodeName;
					if(key == "item"){
						attrs = nodes.item(lNode).attributes;
						for( k=0; k < attrs.length; k++ ){
							if(attrs.item(k).nodeName == "moid"){
								itemMoid = attrs.item(k).text;
								moids.push(itemMoid);
							}
						}
					}
				}
			}
		}
	}
	return moids;
}

// Checks if playlist is empty
// Returns true if playlist was parsed successfully and is empty, false otherwise
function isPlaylistEmpty(dlitem){
	var moids = getPlaylistItems(dlitem);
	if(moids.length == 0)
		return true;
	for(var i = 0; i < moids.length; i++){
		if(checkMoid(moids[i]))
			return false;
	}
	return true;
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: launchDownloadMonitor()
// 
// DESCRIPTION: Launches the Download Monitor.
//
//////////////////////////////////////////////////////////////////////////
function launchDownloadMonitor()
{
	getApi().downloadMonitor(true);
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: launchDeleteDialog(i_moid)
//
// DESCRIPTION: Launches Delete Confirmation dialog for a given delivery,
// passed in via "i_moid".
//
//////////////////////////////////////////////////////////////////////////
function launchDeleteDialog(i_moid, typeToDelete)
{
    var confirmDelete = getPref("ui.confirm-before-delete", true);
	var playedFrame = getFrame("", "Played");
	var dlitem = new KDXDownload(i_moid);

	if(dlitem.isSubscription())
		typeToDelete == "subscription";
		
    //alert("confirmDelete: " + confirmDelete);
	if(cancelDeleteViaPlayer(i_moid)){

		if(playedFrame) playedFrame.closeWindow();
		var deleteFrame = getFrame("", "Delete");

		if(!typeToDelete)
			typeToDelete = "delete";

		if (confirmDelete){
			if(deleteFrame){
				if(typeToDelete != null) deleteFrame.param("typeToDelete") = typeToDelete;
				deleteFrame.navigate("cache:kdmx_delete.html?"+i_moid);				
			} else {
				var params = "class=dialog,position=1,resize=0,visible=0,maxbtn=0,visible=false";
				if(typeToDelete != null) params += ",typeToDelete=" + typeToDelete;
				getApi().launchTemplate("cache:kdmx_delete.html?"+i_moid, params, "", "Delete");
			}
		}else {			
			if(typeToDelete == "subscription") {				
				var playlistArray = getSubscriptionPlaylists(i_moid);
				for(i=0; i<playlistArray.length; i++)
					getApi().deleteMoid(playlistArray[i]);
			}

			if(parseInt(dlitem.getValue(i_moid, "ad")))
				updateAdStatus(i_moid, 0);

			getApi().deleteMoid(i_moid);
			if(deleteFrame) deleteFrame.closeWindow();
		}
	} else {
		if(playedFrame) playedFrame.navigate("cache:kdmx_played.html?"+i_moid);
		else getApi().launchTemplate("cache:kdmx_played.html?"+i_moid, "class=dialog,position=1,resize=0,visible=false,maxbtn=0,width=400,height=125", "", "Played");
	}
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: launchDialog(dialogType)
//
// DESCRIPTION: dialog for common tasks
//
//////////////////////////////////////////////////////////////////////////

function launchDialog(dialogType, dialogData){
		getApi().launchTemplate("cache:kdmx_dialog.html", "class=dialog,position=1,resize=0,maxbtn=0,width=400,height=125,visible=false,dialogType="+dialogType+",dialogData="+dialogData, "", "Delete");
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: launchChooseDeliveryMethod(i_moid)
//
// DESCRIPTION: dialog for choosing of delivery method
//
//////////////////////////////////////////////////////////////////////////

function launchChooseDeliveryMethod(i_moid){
		getApi().launchTemplate("cache:kdmx_streamOrDl.html", "class=dialog,position=1,resize=0,maxbtn=0,width=330,height=225,visible=false", i_moid, "chooseDeliveryMethod");
}

function cancelDeleteViaPlayer(i_moid){
	var playerFrame = getFrame("", "player");
	if(playerFrame != null) {
		var moidString = playerFrame.param("cur_moid");
		if(moidString != null && moidString != "undefined"){
			var moidArray = moidString.split(";");
			if(moidArray != null){
				for(var i=0; i<moidArray.length; i++){
					if(i_moid  == moidArray[i]) return false;
				}
			}
		} else return false;
	}
	return true;
}
//////////////////////////////////////////////////////////////////////////
//
// Central place for frequently used methods.
//
//////////////////////////////////////////////////////////////////////////

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getThumbLarge(i_moid)
//
// DESCRIPTION: Gets 158x118 Large Thumbnail (aka Medium Icon in NetPub)
// for a given delivery, passed in via "i_moid".
//
//////////////////////////////////////////////////////////////////////////
function getThumbLarge(i_moid)
{
    var dlitem = new KDXDownload(i_moid);
    var url = dlitem.getStrValue("file_thumbnail");
    if(url == "") url = dlitem.getStrValue("image");
    if(url == "") url = dlitem.getStrValue("smallIcon");
    return url;
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: menuover( o )
//
// DESCRIPTION: Used by tray menu and context menus.
//
//////////////////////////////////////////////////////////////////////////
function menuover( o )
{
    o.style.backgroundColor = "#003366";
    o.style.color = "white";
	
	var menuButton = getChild(o, "menuButton");	
	if(menuButton){
		menuButton.style.backgroundColor = "#003366";
		menuButton.style.color = "white";
		menuButton.focus();
	}
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: menuover( o )
//
// DESCRIPTION: Used by tray menu and context menus.
//
//////////////////////////////////////////////////////////////////////////
function menuout( o )
{
    o.style.backgroundColor = "#FFFFFF";
    o.style.color = "black";
	
	var menuButton = getChild(o, "menuButton");
	if(menuButton){
		menuButton.style.backgroundColor = "#FFFFFF";
		menuButton.style.color = "black";
	}

}

//////////////////////////////////////////////////////////////////////////
//
// Media types
//
//////////////////////////////////////////////////////////////////////////
var kPlayerType_Unknown         = 0;
var kPlayerType_WMP             = 1;
var kPlayerType_WMP6            = 2;
var kPlayerType_Real            = 3;
var kPlayerType_Quicktime       = 4;
var kPlayerType_Acrobat         = 5;
var kPlayerType_Winzip          = 6;

//////////////////////////////////////////////////////////////////////////
//
// Throttle Events
//
//////////////////////////////////////////////////////////////////////////
var KDX_THROTTLE_STATE_UNKNOWN      = -1;
var KDX_THROTTLE_STATE_NOTTHROTTLED = 0;
var KDX_THROTTLE_STATE_USERACTIVITY = 1 << 0;
var KDX_THROTTLE_STATE_NETACTIVITY  = 1 << 1;
var KDX_THROTTLE_STATE_ENFORCED     = 1 << 2;
var KDX_THROTTLE_STATE_NOTIN        = 1 << 3;
var KDX_THROTTLE_STATE_GENERIC      = 1 << 7;
var KDX_THROTTLE_STATE_ACCELERATED  = 1 << 8;

//////////////////////////////////////////////////////////////////////////
//
// Load Flags
//
//////////////////////////////////////////////////////////////////////////
var KDX_LOAD_FLAG_NONE				= 0;
var KDX_LOAD_FLAG_ISSTREAMABLE		= 1;

//////////////////////////////////////////////////////////////////////////
//
// Download Events
//
//////////////////////////////////////////////////////////////////////////
var KDX_STATE_NEW              = 0;
var KDX_STATE_QUEUED           = 1;
var KDX_STATE_CONNECTING       = 2;
var KDX_STATE_BACKOFF          = 3;
var KDX_STATE_PROGRESS         = 4;
var KDX_STATE_UNPACKING        = 5;
var KDX_STATE_COMPLETE         = 6;
var KDX_STATE_UPDATE           = 7;
var KDX_STATE_DELETED          = 8;
var KDX_STATE_PLAYABLE         = 9;
var KDX_STATE_PRIORITIZED      = 10;
var KDX_STATE_UNPRIORITIZED    = 11;
var KDX_STATE_DODEFAULTACTION  = 12;
var KDX_STATE_ERROR            = 13;
var KDX_STATE_PAUSE            = 14;
var KDX_STATE_RESUME           = 15;

var KDX_STATE_ATTACHED         = 16;
var KDX_STATE_PASSWORD         = 17;
var KDX_STATE_CHANGEPASSWORD   = 18;
var KDX_STATE_SHOWHELPERAPP    = 19;
var KDX_STATE_SELECTSTREAMING  = 20; 
var KDX_STATE_EMBARGOED        = 21;
var KDX_STATE_STREAMABLE       = 22;

var KDX_CURRENT_PLAYLIST = null;

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: getEventData(obj)
//
// DESCRIPTION: Returns map of data passed via an event.
//
//////////////////////////////////////////////////////////////////////////
function getEventData(obj)
{     
    try 
    {
        var map = new Array();
        var m = obj.toArray();
        for (var i = 0; i < m.length; i+=2 )
            map[m[i]] = m[i+1];
        return map;
    }
    catch (e)
    {
        return obj;
    }      
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: KDXDownloadStatusMessage(i_kdxevent, i_eventdata, i_default)
//
// DESCRIPTION: Handles UI for the different download states.
//
//////////////////////////////////////////////////////////////////////////
function KDXDownloadStatusMessage(i_kdxevent, i_eventdata, i_default)
{
    switch (i_kdxevent)
    {
        case KDX_STATE_PAUSE: return "Paused";
        case KDX_STATE_RESUME:
        case KDX_STATE_QUEUED: return "Waiting";
        case KDX_STATE_CONNECTING: return "Connecting";
        case KDX_STATE_ERROR: 
        {
            var errorMap = getEventData(i_eventdata);
            var errorType = errorMap["errorType"];    
            var errorText = gErrorMsgMap[errorType];
            if (errorText != "") return errorText;
        }
    }
    return (i_default == null? "": i_default);
}

function fromSecToTime(sec){
	var secs = sec%60;
	var mins = ((sec-secs)/60)%60;
	var hours = (sec-(mins*60+secs))/3600;
	if(secs <= 9)
		secs="0"+secs;
	if(mins <= 9)
		mins="0"+mins;
	if(hours <= 9)
		hours="0"+hours;			
	return hours+":"+mins+":"+secs;
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: checkForExpired(i_moid)
//
// DESCRIPTION: Check for expired content
//
//////////////////////////////////////////////////////////////////////////

function checkForExpired(i_moid){
	
	var nowDate = new Date();
	var expDate = null;
	var isExpired = false;
	
	var dlitem;
	try {		
		dlitem = new KDXDownload(i_moid);
		expDate = kdxutil.getExpDate(dlitem);
		if(expDate != null){
			if(expDate.getTime() <= nowDate.getTime()){				
				isExpired = true;
			}
		}
	} catch (e) {
	}
	
	if(isExpired){		
		launchDialog("expiredContent", dlitem.getShortTitle());
		if(dlitem.isHttpStreaming() || dlitem.isGridStreamNoSave()){			
			var emailThisPage = getFrame(i_moid, "emailThis");
			if(emailThisPage != null) emailThisPage.closeWindow();
			
			if(!cancelDeleteViaPlayer(i_moid)){
				var playerFrame = getFrame("", "player");
				if(playerFrame) playerFrame.closeWindow();
			}
		}
		try{
			getApi().deleteMoid(i_moid);
		}catch(e){
		}
	}
		
	return isExpired;
}

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: KDXDefaultEventHandler(i_moid, i_event, i_data)
//
// DESCRIPTION: Default event handler for the different states of the
// client. Acts as "switchboard" that redirects user to different pages
// driven by events.
//
//////////////////////////////////////////////////////////////////////////
function KDXDefaultEventHandler(i_moid, i_event, i_data)
{    
    switch(i_event)
    {
        case KDX_STATE_NEW:
        {
			// No splash dlg for streamed files.
			if(getApi().valueExists(i_moid, "ad"))
			if(parseInt(getApi().value(i_moid, "ad"))){
				getApi().value(i_moid, "hidden") = "true";
				getApi().value(i_moid, "cstore_purge_policy") = -1;
				break;
			}

			if(getApi().valueExists(i_moid, "playlist"))
			if(parseInt(getApi().value(i_moid, "playlist"))){
				getApi().value(i_moid, "hidden") = "true";
				break;
			}

			if(getApi().valueExists(i_moid, "short_title"))
			if(getApi().value(i_moid, "short_title") == "MyPlayList"){
				getApi().value(i_moid, "hidden") = "true";
				break;
			}
			
			var dlitem =null;
			
			if(i_moid != null){				
				try {
					dlitem = new KDXDownload(i_moid);
				} catch (e) {break;}
			}else
				break;
				
			if(!dlitem.isGridStreamNoSave())
			if(getApi().valueExists(i_moid, "hidden"))
			if(getBoolValue(getApi().value(i_moid, "hidden"))){
				getApi().value(i_moid, "hidden")="true";
				break;
			}					
			
			if(checkForExpired(i_moid))
				break;				
			
			var nowDate = new Date().getTime();
			getApi().value(i_moid, "delivery_start_time") = nowDate.toString();

			// Don't show splash/progress dlg during blackout.
			
			if (getApi().isBlackout())
			{
				var error = new Array();
				error["errorType"] = "ERROR_BLACKOUT"; 
				launchError(error, i_moid);
			}
			else if(!dlitem.isStreaming() || dlitem.isGridStreamSave())
			{
				getApi().value(i_moid, "cstore_purge_policy") = 1;
				launchDM(i_moid);
				setTimeout("launchEM(\""+i_moid+"\");", 10000);
				var authWindow = getFrame(i_moid, "Authentication");
				if(authWindow) authWindow.closeWindow();
			}				
            break;
        }
        case KDX_STATE_PROGRESS:
        {			
			if(getApi().valueExists(i_moid, "ad"))
			if(parseInt(getApi().value(i_moid, "ad"))){
				break;
			}

			if(getApi().valueExists(i_moid, "playlist"))
			if(parseInt(getApi().value(i_moid, "playlist"))){
				break;
			}

			if(getApi().valueExists(i_moid, "hidden"))
			if(getBoolValue(getApi().value(i_moid, "hidden")))
				break;
				
			var dataMap = getEventData(i_data);
			var filled = dataMap["byteCount"];
			var total = dataMap["byteTotal"];
			var timeLeft = fromSecToTime(dataMap["eta"]);

			if (total > 0){
				getApi().value(i_moid, "percentsLoaded") = kdxutil.toFixed((filled*100)/total, 0);
				getApi().value(i_moid, "timeEstimated") = timeLeft;
				getApi().value(i_moid, "totalBandwidth") = kdxutil.bandwidth2bps(dataMap["totalbw"]);
				
				getApi().value(i_moid, "bytesLoaded") = filled;
				getApi().value(i_moid, "bytesTotal") = total;
			}
			
            break;
        }
        
        case KDX_STATE_DELETED:
		{
			var emailThisPage = getFrame(i_moid, "emailThis");
			if(emailThisPage != null) emailThisPage.closeWindow();

			if(!cancelDeleteViaPlayer(i_moid)){
				var playerFrame = getFrame("", "player");
				if(playerFrame) playerFrame.closeWindow();
			}			
			break;
		}
		case KDX_STATE_PAUSE:
		{
			if(!cancelDeleteViaPlayer(i_moid)){
				var playerFrame = getFrame("", "player");
				if(playerFrame) playerFrame.closeWindow();
			}
			break;
		}
        case KDX_STATE_EMBARGOED:
        {
            // Close window for deleted and embargoed deliveries           
            break;
        }
        case KDX_STATE_UNPACKING:
        {
			break;
        }
        case KDX_STATE_COMPLETE:
        {			
			if(getApi().valueExists(i_moid, "ad"))
			if(parseInt(getApi().value(i_moid, "ad"))){
				getApi().value(i_moid, "hidden") = "true";
				updateAdStatus(i_moid, 1);
				getApi().value(i_moid, "cstore_purge_policy") = -1;
				break;
			}

			if(getApi().valueExists(i_moid, "playlist"))
			if(parseInt(getApi().value(i_moid, "playlist"))){
				getApi().value(i_moid, "hidden")="true";
				break;
			}

			if(getApi().valueExists(i_moid, "hidden"))
			if(getBoolValue(getApi().value(i_moid, "hidden")))
				break;

			if(i_moid != null){
				try {
					var dlitem = new KDXDownload(i_moid);
				} catch (e) {break;}
			}else
				break;			

			if(dlitem.getStrValue("short_title") == "MyPlayList"){
				getApi().value(i_moid, "hidden")="true";
				break;
			}
				
			if(!dlitem.isHttpStreaming() && !dlitem.isMetaDataReload() || dlitem.isGridStreamSave())
			{
				// Don't show sub activated dlg during blackout.
				if (dlitem.isSubscription() && getApi().isBlackout())
				{
					var error = new Array();
					error["errorType"] = "ERROR_BLACKOUT"; 
					launchError(error, i_moid);
				}
				else
				{
					if(dlitem.isSubscription()){
						showCompleted(2);
					}else{
						launchDM(i_moid); 
					}

				}
			}
		
		// Don't show complete dlg for mandatory subs, http-streams,
		// and gridstream-nonsave files
		break;
        }
        case KDX_STATE_PASSWORD:
            // Stash the event data away for use in the following page.
			var dopreauth = getPref("download.preAuthenticationEnabled", false);
			var preauthUrl = getPref("download.preAuthenticationUrl","");
            if (dopreauth && preauthUrl != ""){
				var authWindow = getApi().launchTemplate("cache:kdmx_preauth.html", "class=dialog,position=2,resize=0,maxbtn=0,visible=false,width=400,height=125", i_moid, "Authorize");
				authWindow.ui.param("eventData") = i_data;
			} else {
				var authWindow = getApi().launchTemplate("cache:kdmx_auth.html", "class=dialog,position=2,resize=0,maxbtn=0,visible=false,width=400,height=125", i_moid, "Authorize");
				authWindow.ui.param("eventData") = i_data;
			}
            break;
        case KDX_STATE_CHANGEPASSWORD:
            // Stash the event data away for use in the following page.
            window.external.ui.param("eventData") = i_data;
            window.external.navigate("cache:kdmx_changepassword.html");
            break;
		case KDX_STATE_STREAMABLE:
			getApi().value(i_moid, "playable") = 1;
			break;
        case KDX_STATE_PLAYABLE:
            // If this is an external play, simply close the window.
			if(i_moid != null){
			try {
				var dlitem = new KDXDownload(i_moid);
			} catch (e) {break;}
			}else
				break;

			if(dlitem.getStrValue("short_title") == "MyPlayList"){
				getApi().value(i_moid, "hidden") = "true";
			} else  if(getApi().valueExists(i_moid, "playlist")){
				if(parseInt(getApi().value(i_moid, "playlist"))){
					getApi().value(i_moid, "hidden") = "true";
				}
			}
		
			var playerFrame = getFrame("", "player");
			if(playerFrame == null) {
				var width = screen.width;
				var height = screen.height;
				if(width<800||height<600){
					width = 320;
					height = 240;
				} else {
					width = 640;
					height = 480;
				}
				height += 65 + 25;
				width += 117 + 6;
				
				getApi().launchTemplate("cache:kdmx_player.html", "class=dialog,maxbtn=false,width="+width+",height="+height+",position=1,visible=0,ext_moid="+i_moid, "", "player");
			} else if(i_moid != playerFrame.param("ext_moid")){
				playerFrame.param("ext_moid") = i_moid;
				getApi().fireEvent("newPlayList", "");
				playerFrame.showWindow(1);
			}
            break;
        case KDX_STATE_SELECTSTREAMING:
			launchChooseDeliveryMethod(i_moid);
            break;  
        case KDX_STATE_ERROR:
			try{
				if(i_moid)
				if(getApi().valueExists(i_moid, "ad"))
				if(parseInt(getApi().value(i_moid, "ad"))){
					updateAdStatus(i_moid, 0);
					 break;
				}
			}
			catch(e){}
			
			launchError(i_data, i_moid);
        break;       
    }    
}

//////////////////////////////////////////////////////////////////////////
//
// Download Objects
//
//////////////////////////////////////////////////////////////////////////

//download type
var ZMD_DownloadType              = "download_type";
var ZMD_DownloadType_Subscription = "KontikiSubscriptionType";
var ZMD_DownloadType_Known        = "KontikiKnownType";
var ZMD_DownloadType_Streaming    = "KontikiStreamingType";

//schema types
var ZMD_SchemaType							= "schema_type";
var ZMD_SchemaType_FileDescription			= "FileDesc";
var ZMD_SchemaType_ContentDescription		= "ContentDesc";
var ZMD_SchemaType_SubscriptionDescription	= "Subscription";

// delivery method
var ZMD_DeliveryMethod_Streaming      = "Streaming";
var ZMD_DeliveryMethod_GridStreaming  = "GridStreaming";
var ZMD_DeliveryMethod_Standard	      = "Standard";

//////////////////////////////////////////////////////////////////////////
//
// FUNCTION: KDXDownload(i_moid)
//
// DESCRIPTION: Instantiates a Download Object for a given delivery,
// passed in via "i_moid". This object can be used to get metadata and
// other info about the delivery
//
//////////////////////////////////////////////////////////////////////////
function KDXDownload(i_moid)
{
    // Member variables.
    this.mMoid = null;
    this.mIsSubscription = false;
    this.mDownloadType = null;
    this.mIsSubscriptionContent = -1;
    this.mIsSecure = -1;
    
    // Initialization function.
    this.init = function KDXDownload_initialize(i_moid)
    {
	    var schemaType = getApi().value(i_moid, ZMD_SchemaType);
	    if (schemaType == ZMD_SchemaType_FileDescription)
	    {
		    var formatMoid =  getApi().value(i_moid, "child_id");
		    if (formatMoid == "")
			    throw "FormatlessContent:" + i_moid;
    		
		    this.mMoid = i_moid;	
	    }
	    else if (schemaType == ZMD_SchemaType_SubscriptionDescription)
	    {	
		    this.mMoid = i_moid;
		    this.mIsSubscription = true;
	    }
	    else
		    throw "UnknownMoid:" + i_moid;
    }
    
    // Returns moid.
    this.getMoid = function() {return this.mMoid;} 

    // Generic get method for any property.
    this.getValue = function(i_prop) 
    { 
        if (getApi().valueExists(this.mMoid, i_prop))
            return getApi().value(this.mMoid, i_prop);
        else return null;
    }
    
    // Returns value of property as a string.
    this.getStrValue = function (i_prop)
    {
        if (getApi().valueExists(this.mMoid, i_prop))
            return getApi().valuestr(this.mMoid, i_prop);
        else return "";
    }

    // Returns values of property as an array.
    this.getMap  = function(i_prop) 
    {
       var val = getApi().value(this.mMoid, i_prop);
       var map = new Array();
       try 
       {
          var m = val.toArray();
          for (var i = 0; i < m.length; i+=2 )
              map[m[i]] = m[i+1];
       }
       catch (e) {}
       return map;
    }

    // Returns true if delivery is a Kontiki Package.
    this.isPackageReaderFile = function()
    {
        var str = this.getStrValue("filename_physical");
        var ext = '.kpg';
        return ((str.lastIndexOf(ext) + ext.length) == str.length);
    }

    // Returns true if Kontiki Package is unpacking.
    this.isKPGUnPacking = function()
    {
        return getApi().isKPGUnPacking(this.mMoid);
    }

    // Returns true if download is prioritized.
    this.isPrioritized = function()
    {
        return getApi().isPrioritized(this.mMoid);
    }

    // Returns true if delivery is a subscription.
    this.isSubscription = function () 
    { 
        return this.mIsSubscription;
    }
    
    // Returns true if delivery is a mandatory subscription.
    this.isMandatory = function () 
    { 
        return (this.isSubscription() && this.getValue("isMandatory") == 1);
    }
	
	this.isPlayable = function(){
		var playable = 0;
		if(getApi().valueExists(this.mMoid, "playable"))
			playable = getApi().value(this.mMoid, "playable");
		return playable;
	}

    // Returns true if content has been delivered as part of a subscription.
    this.isSubscriptionContent = function()
    {
        if (this.mIsSubscriptionContent == -1)
            this.mIsSubscriptionContent = (getApi().valueExists(this.mMoid, "parent_id"))?1:0;
        return (this.mIsSubscriptionContent == 1);
    }

    // Returns true if delivery is a secure item (ACL).
    this.isSecureItem = function()
    {
        if (this.mIsSecure == -1)
            this.mIsSecure = (getApi().valueExists(this.mMoid, "secure"))?1:0;
        return (this.mIsSecure == 1);
    }

    // Returns true if delivery is locked from automatic deletion.
    this.isLockedItem = function()
    {
        if (getApi().valueExists(this.mMoid, "cstore_purge_policy"))
            return (getApi().value(this.mMoid, "cstore_purge_policy") == -1);
        return false;
    }

    // Locks delivery against being automatically deleted.
    this.lockItem = function (dolock)
    {
	    if (this.isSubscription() == false)
            getApi().value(this.mMoid, "cstore_purge_policy") = (dolock?-1:0);
    }
    
    // Returns download type of the delivery.
    this.getDownloadType = function()
    {
        if (this.mDownloadType == null) 
            this.mDownloadType = getApi().value(this.mMoid, "delivery_method");
        return this.mDownloadType;
    }

    // Returns true if download is in paused state.
    this.isPaused = function()
    {
        return this.getValue("download_state") == "Suspended";
    }

    // Returns true if delivery is complete for the item. Note: All subscriptions
    // are considered "complete".
    this.isComplete = function()
    {
        return (this.isSubscription() || this.getStrValue("download_state") == "Complete");
    }

    // Returns true if download has failed for the item.
    this.isFailedDownload = function()
    {
        return (this.getStrValue("download_state") == "Error");
    }    
    
    // Returns true if metadata needs to be reloaded because we are missing
    // information. For example, we need to revisit authentication for ACL subs
    // after user has cleared all passwords.
    this.isMetaDataReload = function()
    {
       return (this.isSubscription() && this.getStrValue("get_metadata_again") == "true");
    }    

    // Returns true if delivery is a streaming content (HTTP or Grid Stream).
    this.isStreaming = function()
    {
        if (this.isSubscription()) return false;   
        return ((this.getDownloadType() == ZMD_DeliveryMethod_Streaming) ||
                (this.getDownloadType() == ZMD_DeliveryMethod_GridStreaming));
    }
    
    // Returns true if delivery is an HTTP Streaming content.
    this.isHttpStreaming = function()
    {
        if (this.isSubscription()) return false;
        return (this.getDownloadType() == ZMD_DeliveryMethod_Streaming);
    }
    
    // Returns true if delivery is a Grid Streaming content.
    this.isGridStreaming = function()
    {
        if (this.isSubscription()) return false;
        return (this.getDownloadType() == ZMD_DeliveryMethod_GridStreaming);
    }

    // Returns true if delivery is a Streaming Playlist content.
    this.isStreamingPlayList = function()
    {
        return (this.getStrValue("streaming_playlist") == "true");
    }

    // Returns true if delivery is a Grid Streaming content that cannot be saved.
    this.isGridStreamNoSave = function()
    {
        if (this.isSubscription()) return false;
        if (this.getDownloadType() == ZMD_DeliveryMethod_GridStreaming)
            return (this.getValue("allowSaveStream") != "true");

        return false;
    }
	
    // Returns true if delivery is a Grid Streaming content that can be saved.
    this.isGridStreamSave = function()
    {
        if (this.isSubscription()) return false;
        if (this.getDownloadType() == ZMD_DeliveryMethod_GridStreaming)
            return (this.getValue("allowSaveStream") == "true");

        return false;
    }

    // Returns the Email This URL for a the delivery.
    this.getEmailUrl = function()
    {
        return getApi().value(this.mMoid, "tell_a_friend_url");
    }
    
    // Returns number of times delivery has been played.
    this.getPlayCount = function()
    {
        if(getApi().valueExists(this.mMoid, "cstore_play_count"))
        {
            var playCount = getApi().value(this.mMoid, "cstore_play_count");
            return playCount;
        }
        else return 0;
    }
    
    // Returns 55x41 Small Thumbnail (aka Small Icon in NetPub) for the delivery.
    this.getSmallIcon = function()
    {
        var url = this.getStrValue( "file_thumbnail_small");
        if (url == "")
            url =  this.getStrValue("smallIcon");
        
        return url;
    }
    
    // Returns title of the delivery.
    this.getShortTitle = function(truncate)
    {
		var value = this.getStrValue("short_title");
		if(truncate){

			value = value.replace("&", "&amp;");
			value = value.replace('"', "&quot;");
			value = value.replace('<', "&lt;");
			value = value.replace('>', "&gt;");
			value = value.replace("/", "&frasl;");
			value = value.replace("\\", "&frasl;");
			
	        return value;
		}else{
			return value;
		}
    }
    // Returns true if delivery is an executable
    this.isApplication = function()
    {
        str = this.getStrValue("filename_physical");
        var extensions = [ ".exe", ".com" ];
        for (i = 0; i < extensions.length; ++i)
        {
            var ext = extensions[i];
            if ((str.lastIndexOf(ext)+ ext.length) == str.length) return true;
         }
         return false;        
    }
    this.getPublishDate = function()
    {
		var Mon =
		  ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']

		var ms = getApi().valuestr(this.mMoid, "file_created_time");
		var dt = new Date(ms / 1000);
		return Mon[dt.getMonth()] + ", " + dt.getDate() + " " + dt.getFullYear();
    }

    // Initialize the object.
    this.init(i_moid);
    return true;
}


function checkTitle(obj){
	var parentObj = obj.parentElement;
	var parentCell =  getParent(obj, 'TD');

	var dotsObj = getChild(parentCell, 'dots');
	dotsObj.style.fontWeight = obj.style.fontWeight;

	if(parentObj.lineHeight*2 < obj.clientHeight){
		dotsObj.style.display = "block";
	}else{
		dotsObj.style.display = "none";
	}
	
	if(obj.clientHeight <= parentObj.lineHeight){
		parentObj.style.pixelHeight = parentObj.lineHeight;
	}else{
		parentObj.style.pixelHeight = parentObj.lineHeight*2;
	}
}

function getParent(elem, tagname)
{
    if (elem == null) return null;
    if (elem.nodeType == 1 && elem.tagName.toLowerCase() == tagname.toLowerCase())
        return elem;
    else
        return getParent(elem.parentNode, tagname);
}

function getChild(elem, id)
{
    if (elem == null) return null;
    if (elem.id == id) return elem;
    if (elem.nodeType != 1) return null;
    if (!elem.hasChildNodes()) return null;
    var kids = elem.childNodes;
    var theKid = null;
    for (var i=0; i < kids.length; ++i)
    {
        theKid = getChild(kids[i], id);
        if (theKid != null) break;
    }
    return theKid;
}

function catchImageSize(obj){

	if(!obj)
		return;

	var imgWidth = obj.width;
	var imgHeight = obj.height;

	var resized = false;
	
	if(imgHeight <= 0 || imgWidth <= 0)
		return;	

	if(imgHeight == 30 || imgWidth == 28){
		imgWidth = 55;
		imgHeight = 41;
	}		
	
	var resizeRatio = getResizeRatio(imgWidth, imgHeight)

	var newWidth = Math.round(imgWidth*resizeRatio);
	var newHeight = Math.round(imgHeight*resizeRatio);

	if(obj.width != newWidth){
		obj.width = newWidth;
		resized = true;
	}if(obj.height != newHeight){
		obj.height = newHeight;
		resized = true;
	}
	
	//if(resized)
	//	alert(obj.title+"\nOld size:\n width="+imgWidth+", height="+imgHeight+"\n New size:\n width="+newWidth+", height="+newHeight+"\nneedToInitialResize:"+needToInitialResize);
	return true;
}

function getResizeRatio(imgWidth, imgHeight){
	var imgRatio = imgWidth/imgHeight;
	var resizeRatio = 0;
	
	if(imgRatio > 65/49){
		resizeRatio = 65/imgWidth;
	}else{
		resizeRatio = 49/imgHeight;
	}
	
	return resizeRatio;
}

function checkOnlineState(hideOfflineDialog){
	var isOk = false;
	var isOnline = false;
	
	try{
		var test = getApi().isBlackout();
		isOk = true;
	}catch(e){
	}
	
	if(isOk)
		isOnline = getApi().isOnline();
	else
		refreshWebManager();
	
	if(!isOnline && isOk && !hideOfflineDialog)
		launchOffline();		
		
	return isOnline;
}

function refreshWebManager(){

	var w = screen.availWidth*0.9;
	var h = screen.availHeight;
	var x = (screen.availWidth - w)/2;
	var y = (screen.availHeight - h)/2;
		
	var style = "left=" + x + ",top=" + y + ",width=" + w + ",height=" + h + ",location=1,menubar=1,resizable=1,scrollbars=1,status=1,toolbar=1";
	
	webManagerWindow = window.open(webManagerURL,'aol_online', style);
	webManagerWindow.focus();
}

function writeCodeToFile(code, fileName){
	var fso = new ActiveXObject("Scripting.FileSystemObject");
	var f = fso.OpenTextFile("c:\\"+fileName, 2, true);
	f.Write(code);
	f.Close();
}

//-->

