var _mm_obj = null
var _mm_isappinstalled = false;
var _mm_appid;
var _mm_DQID; //Added 1/22/08 Dean Singh
var _mm_skuid; //Added 1/30/08 Dean Singh
var _mm_appver;
var _mm_lasterror;
var _mm_location = escape('placeholder pc');
var mmctrl;
var isFirefox = false;
var basePath = 'https://<%= CinemaNowBasePath %>/'

function _mm_init(ctrltype) {
	if (!_mm_obj) {
	
	    set_mm_cookie();
	    
		if (_mm_Loadobj(ctrltype)) {
		    _mm_obj = true;
		    _mm_appid = _mm_Exec( 'GetAppID', null, null );
		    _mm_appver = _mm_Exec( 'GetAppVersion', null, null );
		    _mm_location = _mm_Exec('GetMachineName',null,null);
		    _mm_obj = true;
			set_mm_cookie();
			
			//alert("_mm_appid: " + _mm_appid + "\n_mm_appver: " + _mm_appver + "\n_mm_location: " + _mm_location);
			if (_mm_appver <= "")
			{
			    //alert("no appver");
    			_mm_obj = false;
    			return false;
			}			

            if (_mm_appver && _mm_appid) 		return true;
			else return false;
		
		}
		else {
			mm_obj = false;
			//alert("mm_obj FAILED...");
			return false;
		}
	}
	return true;
}

function set_mm_cookie() {
    document.cookie = "MM_APPID = " + _mm_appid + ";";
}


function _mm_Exec(f,i,p) {
	if (_mm_obj) {
		var exec;
		try {
			if (!i && !p)	{
				exec = "mmctrl."+ f +"()";
			}
			else if (!i)
			{
				exec = p +"(mmctrl."+ f +"())";
				//return eval(p +"(mmctrl."+ f +"())");
			}
			else
			{
				var input = i;
				if (i.length > 1 && (typeof(i) == 'object')) {
					input = i.join();
				}
				if (!p)
				{
					exec = "mmctrl."+ f +"("+ input +")";
				}
				else
					exec = p +"(mmctrl."+ f +"("+ input +"), "+ input +")";
			}
			
			return eval(exec);
		}
		catch (e) {
			//handle error
			//if (String(exec).indexOf("null")!=-1) {return}
			//alert("_mm_Exec() Error \n\n Call : \n\nDescription : " + e.description);
			//alert("_mm_Exec() Error \n\n Call : "+ exec +"\n\nDescription : " + e.description);
		    //alert("_mm_Exec() Error \n\nDescription : " + e.description);
			 document.write(exec);
		}
	}
	else { //alert('failed to exec'); 
	}
}

function _mm_Prop(p,i) {
	if (_mm_obj)	{
		var exec;
		try	{
			if (!i)	
				exec = "mmctrl."+ p;
			else
				exec = "mmctrl."+ p +" = "+ i;
			
			return eval(exec);
		}
		catch (e) {
			//handle error
			//alert("_mm_Prop() Error \n\n Call : "+ exec +"\n\nDescription : " + e.description);
		}
	}
}



function _mm_Loadobj(ctrltype) {
		

		try
		{
			//alert("Support ActiveXObject...");
			if (ctrltype.toLowerCase() == 'settings')
			{
				mmctrl = new ActiveXObject("CinemaNowControl.CinemaNowSettingsCtrl");
			}
			else
			{
				mmctrl = new ActiveXObject("CinemaNowControl.CinemaNowCtrl");
			}
			return true;
		}
		catch (e)
		{
	        //alert("catch - _mm_Loadobj failed by ActiveX method");
            try
            {
	            mmctrl = document.getElementById('mmctrl');
				if (mmctrl)
				{	
					//alert("Support Object tag...");
		            mmctrl.classid = "clsid:AF86B78A-983F-4591-9E19-3AC9BAE0F7F5"
		            if (document.all.mmctrl.GetAppVersion())
					{
						_mm_obj=true;
						return true
					}
				}
				return false;				
            }
            catch (e)
            {
	            //alert("catch - _mm_Loadobj failed by Object method");
	            if (navigator.userAgent.indexOf("Firefox") > -1) 
	            {
	                //alert("isFirefox");
	                isFirefox = true;
	                try 
	                {
	                    if (FFPluginDetected('CinemaNow'))
	                    {
	                        //alert("ff plugin detected");
	                        mmctrl = document.embeds[0];
				            if (mmctrl)
				            {	
		                        if (mmctrl.GetAppVersion())
					            {
						            _mm_obj=true;
						            return true
					            }
				            }
	                    }
//	                    else
//	                    {
//	                        //alert("ff plugin not detected");
//	                    }
	                }
	                catch (e)
	                {
	                    //alert("catch - _mm_Loadobj failed by FF plugin method")
	                    return false;
	                }	 
	            }
//	            else
//	            {
//	                //alert("not firefox");
//	            }
	            return false;
            }		
        }		
}




function InitMediaManager(){
	_mm_init('normal');
}

function SetAction(url){
//    alert(url);
	AJAXRequest("GET", url, null, ProcessCNOW);
};

function ProcessCNOW(myAJAX){
var xml;
 if (myAJAX.readyState == 4) { 
	if (myAJAX.status == 200) {	    
		xml =  "'" + myAJAX.responseText + "'"
		alert('1234545');
		alert(xml);
		
		if (xml == '\'invalid request\'') {
		//there was an error recieved from url handler.
		//message user to restart browser.
		    alert("I'm sorry I am not able to fullfill your request.\nPlease restart your internet browser and try again.");
		} else {		    
		_mm_Exec("ProcessCNOW", xml, null)
		}
		
	} else {
		alert("There was a problem retrieving the XML data:\n" + xml);	
	}
 }
}

function GetNewDownloads(){
	_mm_Exec("GetNewDownloads", null, null);
}



function mmDoAction(action,pid,skuid){

	if (_mm_obj){
		switch (action) {
			case 'watch':
			  _mm_Exec( 'Watch', pid, null );
			  break;
			case 'download':
				SetAction(basePath + "mmgr/accquire.ashx?passID=" + pid + "&appid=" + _mm_appid + "&ver=" + _mm_appver + "&location=" + _mm_location + "&string=1")
				break;
            case 'downloadLegacy':
				SetAction(basePath + "mmgr/accquire.ashx?passID=" + pid + "&skuid=" + _mm_skuid + "&DQID=" + _mm_DQID + "&appid=" + _mm_appid + "&ver=" + _mm_appver + "&location=" + _mm_location + "&string=1&bSwitch=True&bLegacy=True")
				break;								
			case 'subscriptiondownload':
				SetAction(basePath + "mmgr/accquire.ashx?passID=0&skuid=" + pid + "&appid=" + _mm_appid + "&ver=" + _mm_appver + "&location=" + _mm_location + "&string=1")
				break;
			case 'downloadandburn':
				SetAction(basePath + "mmgr/accquire.ashx?passID=" + pid + "&appid=" + _mm_appid + "&ver=" + _mm_appver + "&location=" + _mm_location + "&string=1&burn=1")
				break;
			case 'downloadnoburn':
				SetAction(basePath + "mmgr/accquire.ashx?passID=" + pid + "&appid=" + _mm_appid + "&ver=" + _mm_appver + "&location=" + _mm_location + "&string=1")
				break;
			case 'burn':
				_mm_Exec('Burn', pid, null);
				break;
			default :
				//alert('Action: ' + action + ' not yet implemented')
				SetAction(basePath + "mmgr/accquire.ashx?passID=" + pid + "&appid=" + _mm_appid + "&ver=" + _mm_appver + "&location=" + _mm_location + "&string=1")
		}		  
	} else {
	    try {
	    //what if firefox plugin is turned off?
	    if (isFirefox)
	    {
	        //alert("isfirefox");
	        //detect firefox plugin
	        //if plugin is installed, send to MMInstall page	        
	        //else plugin not installed, show message box
	            //if cant find message box, go to FFPluginInstall page
	        if (FFPluginDetected('CinemaNow'))	        
	        {   //alert("ff plugin detected");
	            goToUrl(basePath + 'MediaManagerInstall.aspx?ReturnURL=' + escape(location.href));  
	        }
	        else
	        {
	            //alert("ff plugin not detected");
       		    goToUrl(basePath + 'FirefoxInstall.aspx?ReturnURL=' + escape(location.href))

//	            var ffMsgBox = document.getElementById("ffMsgBox");
//	            if (ffMsgBox)
//	            {      //alert("ffMsgBox found");
//	                ffMsgBox.style.display = 'block';   }
//	            else 
//	            {  //alert("ffMsgBox not found");
//	                goToUrl(basePath + 'FirefoxPluginInstall.aspx?ReturnURL=' + escape(location.href)) }
	        }
	    } 
	    else
	    {
	        //alert("not firefox");
		    goToUrl(basePath + 'MediaManagerInstall.aspx?ReturnURL=' + escape(location.href))
		}
		}
		catch (e)
		{   //alert("error!!!!! ahh");
		    //alert(e.message); 
		}
	}
}


//function FFPluginDetected()
//{
//    var L = navigator.plugins.length;
//    for(var i=0; i<L; i++) {
//        if (navigator.plugins[i].name.indexOf("CinemaNow Plugin for Mozilla") > -1) 
//        {
//            return true;
//        }
//    }
//    return false;
//}

function FFPluginDetected() {
    // allow for multiple checks in a single pass
    var daPlugins = FFPluginDetected.arguments;

    // consider pluginFound to be false until proven true
    var pluginFound = false;

    // if plugins array is there and not fake
    if (navigator.plugins && navigator.plugins.length > 0) {
		var pluginsArrayLength = navigator.plugins.length;
		// for each plugin...
		for (pluginsArrayCounter=0; pluginsArrayCounter < pluginsArrayLength; pluginsArrayCounter++ ) {
	    	// loop through all desired names and check each against the current plugin name
	    	var numFound = 0;
	    	for(namesCounter=0; namesCounter < daPlugins.length; namesCounter++) {
				// if desired plugin name is found in either plugin name or description
				if( (navigator.plugins[pluginsArrayCounter].name.indexOf(daPlugins[namesCounter]) >= 0) ||
		    		(navigator.plugins[pluginsArrayCounter].description.indexOf(daPlugins[namesCounter]) >= 0) ) {
		    		// this name was found
		    		numFound++;
				}

	    	}

	    	// now that we have checked all the required names against this one plugin,
	    	// if the number we found matches the total number provided then we were successful
	    	if(numFound == daPlugins.length) {
				pluginFound = true;
				// if we've found the plugin, we can stop looking through at the rest of the plugins
				break;
	    	}
		}
    }
    return pluginFound;
} // detectPlugin

function escapeXML(myxml){
    var quote="'";

    myxml = myxml.replace(/\'/g,"&#39;");
    myxml = myxml.replace(/\\/g,"\\\\");
    myxml = quote + myxml + quote;

    return myxml;
}



function WSmmDoAction(action, pid, xml){

    if (_mm_obj){
		    switch (action) {
			    case 'download':
                 _mm_Exec('ProcessCNOW', xml, null);
			      break;
			    case 'watch':
                 _mm_Exec( 'Watch', pid, null );
			      break;
			    case 'burn':
                 _mm_Exec('Burn', pid, null);
			      break;
			    default :
				  alert('Action: ' + action + ' not yet implemented');
		    }
    }			  
}


function locblock(o,action,loc) {
   
    if(  o.innerHTML.toLowerCase().indexOf('<br><br>') == -1 ) {
        var s = '<br><br><font color=black>Download was initiated from the following location:<br><b>'+ loc +'</b><br><br>';
     
        switch (action) {
            case 'downloadandburn':
            case 'downloadnoburn':
            case 'download':
                s += '<font color=red>You may only start this download at 1 location.<br></font></font>';
                break;
            case 'burn':
                s += '<font color=red>Please go to that PC location to burn this file.</font>';
                break;
            case 'watch':
                s+= '<font color=red>Please go to that PC location to watch this file.</font>';
                break;
                
        }
        o.innerHTML += s;
    }
    //alert('Download has already been initiated from : '+ loc +'\n\nYou may only download a purchase to 1 location.  To download 
}

function relocate() {
    //alert(qsReturnUrl);
    if (qsReturnUrl > "") {
        location.href = qsReturnUrl + '?mm_appid=' + _mm_appid + '&mm_appver=' + _mm_appver + '&mm_location=' + _mm_location;
    }
}


function doComponentCheck(mode)
{
	if( !_mm_init('normal') )
	{
		//alert('not installed');
        location.href = '/media_manager_install.asp';
		//window.setTimeout("doComponentCheck(1)", 5000);
	}
	else { 
	    //alert('relocating');
	    window.setTimeout("relocate()", 2000); 	    
	}
}

function doComponentCheckInstall(mode)
{
	if( !_mm_init('normal') )
	{
		//alert('not installed');
		window.setTimeout("doComponentCheck(1)", 5000);
	}
	else { 
	    //alert('relocating');
	    window.setTimeout("relocate()", 5000); 	    
	}
}


function fixMMforWMP()
{
    _mm_Exec("EnableStartupTrayicon", "false", null);
}

function checkMMVer(verNum) 
{
    if (_mm_appver)
    {
        var verCompare = new Array();
        verCompare = verNum.split('.');
        
        var appver = new Array();
        appver = _mm_appver.split('.');
        
        var maxCompare = 4;
        if (verCompare.length > appver.length) 
	    { maxCompare = appver.length; }
        else  { maxCompare = verCompare.length;  }

        for (var i = 0; i < maxCompare; i++)
        {
            var v = parseInt(verCompare[i]);
            var a = parseInt(appver[i]);
            if ( v < a)
            { 
                return true; 
            }
            else if (v > a)
            { 
                return false; 
            }
            //else v = a, continue comparing
        }
	    if (verCompare.length > maxCompare)
	    {
		    return false;
	    }
	    else 
	    {
		    return true;
	    }
	}
	else return false;

}
