﻿function BASE_URL()
{
    if(location.host.indexOf('localhost') != -1)
        return "/www_altnet_com/";
    else
        return "/";
}
var _ampbaseurl = BASE_URL();

function setCookie(name,value,days,domain)
{   
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
    document.cookie = name+"="+value+expires+"; path=/; domain="+domain+";";

}


function getCookie(name) {
    var start = document.cookie.indexOf(name+"=");
    var len = start+name.length+1;
    if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
    if (start == -1) return null;
    var end = document.cookie.indexOf(";",len);
    if (end == -1) end = document.cookie.length;
    return unescape(document.cookie.substring(len,end));
}

var amp = {
    FFPlugin        : "Altnet Music Plugin for Firefox",
    FFEmbed         : "<" + "embed type='application/x-AMPff' width=0 height=0 " + ">",
    IEProgID        : "AMPIEI.AmpAX.1",
    IEDRMOBJ        : "<OBJECT name=drmobj classid=clsid:A9FC132B-096D-460B-B7D5-1DB0FAE0C062 height=0 id=drmobj width=0></OBJECT>",
    isFF            : (navigator.userAgent.indexOf("Firefox") != -1),
    isIE            : (navigator.appVersion.indexOf("MSIE") != -1),
    isSP2           : (window.navigator.userAgent.indexOf("SV1") != -1),//check for SP2
    Ampobj          : null,
    Pcode           : location.host,
    StatsParams     : '&LN=Altnet Music Plugin&GR='+(navigator.language? navigator.language : navigator.userLanguage).substring(0,2),
    Queue           : new Array(),
    progress_title  : "Altnet Music Plugin",
    AMPInfoURL      : _ampbaseurl + "support",
    CODEBASEURL     : _ampbaseurl  + "install",
    eventAMPInstall : null,
    eventAMPInstalled : null,
    BrowserOK       : function()
    {
        if(amp.isFF || (amp.isIE && parseFloat(navigator.appVersion.substring(navigator.appVersion.indexOf("MSIE") + 4)) >= 5))
            return true;
        else
            return false;   
    },

    init : function()
    {
        if(amp.BrowserOK())
        {
            amp.Ampobj = null;
            if(amp.isFF && amp.detectplugin())
            {       
                document.write(amp.FFEmbed);
                amp.Ampobj = document.embeds[0];
                try
                {
                    if(amp.Ampobj.ampver == "")
                        amp.Ampobj = null;
                }
                catch(e)
                {
                    amp.Ampobj = null;
                }
      
            }
            else if(amp.isIE)
            {
                try
                {
                    document.write(amp.IEDRMOBJ);
                    amp.Ampobj = new ActiveXObject(amp.IEProgID);
                    //alert(amp.Ampobj.GetVer());
                    if(amp.Ampobj.GetVer() == "")
                        amp.Ampobj = null;
                }
                catch(e)
                {
                    //alert(e);
                    amp.Ampobj = null;
                }
                
            }
        }
        amp.CheckMachineGuid();
        //alert(amp.Ampobj);
    },
    
    detectplugin : function()
    {
        if (navigator.plugins && navigator.plugins.length > 0)
        {
            for(var i = 0; i < navigator.plugins.length; i++)
            {
                if(navigator.plugins[i].name.indexOf(amp.FFPlugin) != -1)
                    return true
            }
        }
        return false;
    },
    imagestack : Array,
    
    SendHTTPdownloadStat : function(CN, FN)
    {
		    var sDwnStat = 'http://backoffice.altnet.com/stats/add.aspx?ST=4&AN='+ amp.Pcode+'&CN='+CN+'&FN='+FN+'&LN=HTTP download&GR='+(navigator.language? navigator.language : navigator.userLanguage).substring(0,2);
		    if(amp.MachineGuid != "")
		       sDwnStat += '&MI=' + amp.MachineGuid;
		    
		    //add random number to the end to not allow caching
		    sDwnStat += '&random=' + Math.floor(Math.random()*10000);
		    
    
		    if(FN.indexOf(".wma") >= 0 || FN.indexOf(".wmv") >= 0)
            {
                
                try
                {
		            var statimg = new Image();
		            statimg.src = sDwnStat;
		            imagestack.push(statimg);
		        }
		        catch(e)
                {
                    //alert(e);
                }
                //alert(sDwnStat);
		    }
    },
    
    SendHTTPAlbumdownloadStat : function(AlbumObjID)
    {
		    var sDwnStat = 'http://backoffice.altnet.com/stats/add.aspx?ST=4&AN='+ amp.Pcode+'&AO='+AlbumObjID+'&LN=HTTP download&GR='+(navigator.language? navigator.language : navigator.userLanguage).substring(0,2);
		    if(amp.MachineGuid != "")
		       sDwnStat += '&MI=' + amp.MachineGuid;
		    
		    //add random number to the end to not allow caching
		    sDwnStat += '&random=' + Math.floor(Math.random()*10000);
		    
    

            try
            {
	            var statimg = new Image();
	            statimg.src = sDwnStat;
	            imagestack.push(statimg);
	        }
	        catch(e)
            {
                //alert(e);
            }
            //alert(sDwnStat);

    },


    SendHTTPStreamPlayStat : function(CN, FN)
    {
		    var sDwnStat = 'http://backoffice.altnet.com/stats/add.aspx?ST=28&AN='+ amp.Pcode+'&CN='+CN+'&FN='+FN+'&LN=HTTP download&GR='+(navigator.language? navigator.language : navigator.userLanguage).substring(0,2);
		    if(amp.MachineGuid != "")
		       sDwnStat += '&MI=' + amp.MachineGuid;
		    
		    //add random number to the end to not allow caching
		    sDwnStat += '&random=' + Math.floor(Math.random()*10000);
		                    
                try
                {
		            var statimg = new Image();
		            statimg.src = sDwnStat;
		            imagestack.push(statimg);
		        }
		        catch(e)
                {
                    //alert(e);
                }
                //alert(sDwnStat);
                
    },
    
    PlayStream: function(CN, FN)
    {
        try
        {
            amp.DeliverLicense(FN, CN);
            setTimeout("amp.SendHTTPStreamPlayStat('" + CN + "', '" + FN + "');", 1);
            //amp.SendHTTPStreamPlayStat(CN, FN);
        }
        catch(e)
        {
            //alert(e);
        }        
    },

    
    cleanup : function(title)
    {
	    title = title+''.replace(/ /g, '_').replace(/\W/g, '').replace(/_/g, ' ');
        if (String(title).length > 40)
		    title = String(title).substring(0,40);
	    return title;
    },
    
    DownloadAMP     : function()
    {
        if(!amp.IsMonitoring)
        {
            amp.monitorinstall();
            if(amp.eventAMPInstall != null)
                amp.eventAMPInstall();
            else
                amp.DoAmpDownload();
            
        }
    },
    
    DoAmpDownload : function()
    {
        location.href= amp.CODEBASEURL + "/altnet_music_plugin.exe";
    },
    
    DownloadAlbum : function(artname, artlocation, artist, album, campaign, albumobj)
    {
        amp.SendHTTPAlbumdownloadStat(albumobj);
        
        //download album art first
        if(artlocation != "")
            amp.DownloadFileOpt(artname,artist,album,artlocation,'0',campaign,"SFK",false);
            
        for(var i=0; i < document.links.length; i++)
        {
            if(document.links[i].id != "")
            {
                if(document.getElementById(document.links[i].id).getAttribute("href").indexOf("amp.DownloadFile") >= 0 && document.getElementById(document.links[i].id).getAttribute("href").indexOf(campaign) >= 0)
                {//change call to not stat because we are already stating the album download above.
                    var dwncode = document.getElementById(document.links[i].id).getAttribute("href").replace("amp.DownloadFile", "amp.DownloadFileNoStat");
                    setTimeout(dwncode, 1);
                }
            }
        }
    },
    
    DownloadFile: function (filename, artist, album, url_base, size, campaign)
    {
        amp.DownloadFileOpt(filename, artist, album, url_base, size, campaign, "", true);
    },
    
    DownloadFileNoStat: function (filename, artist, album, url_base, size, campaign)
    {
        amp.DownloadFileOpt(filename, artist, album, url_base, size, campaign, "", false);
    },
    
    DownloadFileOpt: function(filename, artist, album, url_base, size, campaign, ampoptions, dostat)
    {

        var params = "0,5001," + amp.cleanup(artist) + "," + amp.cleanup(album) + "," + size + "," + filename + ",http://" + url_base + ",3,0,1,"                        + campaign + "," + amp.StatsParams + ",0," + amp.CODEBASEURL + "," + amp.Pcode + ",1,"                       + amp.AMPInfoURL   + ",,,-1," + ampoptions;
	  //var params = "0,5001," + artist +               "," + album +             "," + size + "," + filename + ",http://" + url_base + "," + download_options + ",0,1," + campaign + "," + sStat           + ",0," + CODEBASEURL     + "," + pcode     + "," + install_options + "," + progress_infourl + "," + progress_bmpdir + "," + progress_bmp + "," + progress_logo + "," + ampoptions;  
        
        amp.AddToQueue([params, filename, campaign, dostat]);

        if(amp.Ampobj == null)
        {
            amp.DownloadAMP();
           
            return;
        }
        
        if(!amp.isProcessing)
            amp.ProcessQueue();
  
    },

    AddToQueue : function (param)
    {
        var bUnique = true;
        for(var i =0; i < amp.Queue.length; i++)
        {
            if(amp.Queue[i] == param)
                bUnique = false;
         }

        if(bUnique)
        {
            amp.Queue.push(param);  
        }     
    },
    
    isProcessing : false,
    ProcessQueue : function()
    {
        amp.isProcessing = true;
        while(amp.Queue.length > 0)
        {
            //try
            //{
                //alert(" queue.length " + amp.Queue.length);
	            amp.Ampobj.SetTitle(amp.progress_title);
	            amp.Ampobj.Download(amp.Queue[0][0]);
                
	            if(amp.Queue[0][3])//boolean do stat
	                setTimeout("amp.SendHTTPdownloadStat('" + amp.Queue[0][2] + "', '" + amp.Queue[0][1] + "');", 1);
	            
	            if (!amp.isFF)
	                setTimeout("amp.DeliverLicense('" + amp.Queue[0][1] + "','" + amp.Queue[0][2] + "');",1);
	            
	            amp.Queue.pop(amp.Queue[0]);
	            
            /*}
            catch(e)
            {
                alert(e);
            }*/
        }
        amp.isProcessing = false;
        
        
    },
    
    isMonitoring : false,
    monitorinstall : function()
    {
        amp.isMonitoring = true;
        if (amp.isFF)
        {
            return;
            //alert("Please download and install then restart browser.");
        }
        else
        {
            try
            {
                amp.Ampobj = new ActiveXObject(amp.IEProgID);
                if(amp.Ampobj.GetVer() == "")
                    amp.Ampobj = null;
                    
                amp.CheckMachineGuid();
            }
            catch(e)
            {
                amp.Ampobj = null;
            }
            if(amp.Ampobj == null)
            {
                setTimeout("amp.monitorinstall();", 1000);//try again in 1 sec
            }
            else
            {
                amp.isMonitoring = false;
                
                if(amp.eventAMPInstalled != null)
                    amp.eventAMPInstalled();
                
                //setmachinecookie
                amp.ProcessQueue();
            }
   
        }
    },
    
    MachineGuid : "",
    CheckMachineGuid : function()
    {
        try
        {
            amp.MachineGuid = getCookie("machineguid");
            if(amp.Ampobj != null)
            {
			    if (amp.isFF)
	                setCookie("AMPVer", amp.Ampobj.ampver, 365*70,".altnet.com");//set apm present cookie
	            else
		            setCookie("AMPVer", amp.Ampobj.GetVer(), 365*70,".altnet.com");//set apm present cookie
                
                
                //alert("machineguid:" + machineguid);
                if(amp.MachineGuid != "" && amp.MachineGuid != null)
                {
				    if (amp.isFF)
	                    amp.Ampobj.custid = amp.MachineGuid;
	                else
	                    amp.Ampobj.SetCustID(amp.MachineGuid);

                }
                else
                {
				    var BDEInstaCustID = "";
				    if (amp.isFF)
					    BDEInstaCustID = amp.Ampobj.custid;
				    else
					    BDEInstaCustID = amp.Ampobj.GetCustID();
                
                    //alert("BDEInstaCustID:" + BDEInstaCustID);
                    if(BDEInstaCustID != "" && BDEInstaCustID != null)
                    {
                       setCookie("machineguid", BDEInstaCustID, 365*70,".altnet.com");//set apm present cookie 
                       amp.MachineGuid = BDEInstaCustID;
                       location.href=location.href;
                    }
                }
                
            }
            else
            {
                setCookie("AMP", "0", -1,".altnet.com");//remove amp version 
            }
        }
        catch(e)
        {
           //alert(e);
           return false;
        }
        
        return true;
    },
    
    LicensedCampaigns : "",
    Secversion  : null,
    LicenseURL  : "http://ts2.altnet.com/drm/licenseacquisition.aspx",
    DeliverLicense : function(filename, campaign)
    {
        //alert(amp.Ampobj);
        if(amp.Ampobj == null)
        {
            amp.DownloadAMP();
            return false;
        }
            
        if(amp.LicensedCampaigns.indexOf(campaign) != -1)
            return true;

        if(filename.indexOf(".wma") < 0 && filename.indexOf(".wmv") < 0)
            return true;
	    try
        {
            
            var netobj = document.getElementById("drmobj");
            if(netobj)
            {
                //alert(typeof(netobj.GetLicenseFromURL));
	            //if(typeof(netobj.GetLicenseFromURL) != "undefined")
	            //{
		           if(amp.checkIndividualisation())
		            {
		                //alert(amp.LicenseURL + "?silent=1&action=LICGEN&liccode=" + campaign + "&sessionid=&origfile=" + filename + "&licenseid=" + Date.parse(new Date()) + "&security=1&predel=1&sitecode=" + sitecode + "&machineguid=" + amp.MachineGuid + "&ampver=" + amp.Ampobj.GetVer());
		                var sitecode = getCookie("sitecode");
			            netobj.GetLicenseFromURL('<a></a>', amp.LicenseURL + "?silent=1&action=LICGEN&liccode=" + campaign + "&sessionid=&origfile=" + filename + "&licenseid=" + Date.parse(new Date()) + "&security=1&predel=1&sitecode=" + sitecode + "&machineguid=" + amp.MachineGuid + "&ampver=" + amp.Ampobj.GetVer());
			            amp.LicensedCampaigns += "|" + campaign;
		            }
	            //}	
            }
        }
        catch(e)
        {
            //alert(e);
            
        }
        return true;//always
    },
    
    checkIndividualisation: function()
    {   
        try
        {
            
	        var sXMLCommand, objClientInformation, objXMLDOM, xmlNode;
	        var sFoundSec;
	        var nRequiredSec = '2400', nFoundSec = 0.0;
	        sFoundSec = new String('0.0')
        	  
	        if(amp.Secversion == null)
	        {
	            var netobj = document.getElementById("drmobj");
	            objClientInformation = netobj.GetSystemInfo();
	            //alert(objClientInformation);
	            sXMLCommand = '<?xml version="1.0"?><MEDIATEST><WMP>10</WMP>' + 
					            netobj.GetSystemInfo() + '</MEDIATEST>';
	            try {
		            objXMLDOM = new ActiveXObject("Msxml2.DOMDocument");
	            }
	            catch (xmlException) {
		            objXMLDOM = new ActiveXObject("Msxml.DOMDocument");
	            }
	            objXMLDOM.loadXML (sXMLCommand);
            	  
	            xmlNode = objXMLDOM.selectSingleNode("MEDIATEST/CLIENTINFO/SECURITYVERSION");
	            if (xmlNode)
	            {
		            var sRegEx
		            sRegEx = /\./g;
		            sFoundSec = String(xmlNode.text);
		            sFoundSec = sFoundSec.replace(sRegEx, '');
		            amp.Secversion = sFoundSec;
	            }
	        }
	        //alert(sFoundSec);
	        if (Number(sFoundSec) < nRequiredSec)
		        return false;// individualisation doesn't meet the minimum required level
	        else
		        return true;// Finally, we're done, and everything looks ok.
		}
		catch(e)
		{
		    //alert(e);
		    return false;
		}
    }
}
amp.init();

//preview code
var preview =
{
    curritem : null,
    player : null,
    isloading : false,
    alreadyinit : false,
    
    init : function()
    {
        if(preview.alreadyinit == false)
        {
		    preview.player = document.createElement('DIV');
		    preview.player.innerHTML = "";
		    preview.player.style.display = 'none'
		    document.documentElement.childNodes[0].appendChild(preview.player);
		    window.onbeforeunload = preview.stopplayer;
			
		    preview.alreadyinit = true;
		}
					
					
    
    },
    
    mousedown : function(inst)
    {
        preview.init();
        if(preview.curritem != null && inst.attributes["clipid"].value == preview.curritem.attributes["clipid"].value)
        {
            preview.isloading = false;
            preview.stopplayer();
        }
        else
        {
            if(preview.curritem != null)
                preview.stopplayer();
            
            inst.setAttribute("_origclass",inst.className);
            inst.className = "btnPreviewloading";
            preview.curritem = inst;
            if(preview.player != null)
                setTimeout("preview.playplayer('" + preview.curritem.attributes["href"].value + "');",1);
        }
        return false;
    
    },
     
    playerevent : function(state)
    {
        //alert(state);
        switch(state)
        {
            case 1://content stopped
                preview.stopplayer();
                break;
                
            case 3://finished loading now playing
                //
                if(preview.curritem != null)
                {
                    preview.isloading = false;
                    //alert(preview.curritem.className = "btnPreviewstop");
                    preview.curritem.className = "btnPreviewstop";
                }
                break;
                
            case 10://content stopped
                preview.stopplayer();
                break;
         }
    },

  
    stopplayer : function()
    {
        
        if(preview.curritem != null && preview.isloading == false)
        {
            preview.curritem.className = preview.curritem.attributes["_origclass"].value;
            preview.curritem = null;
            
            if(document.getElementById("ClipPlayer") != null)
                document.getElementById("ClipPlayer").controls.stop();
            preview.player.innerHTML = "";
        }
        
        
    
    },
    
    playplayer : function(url)
    {
        if(preview.player != null)
        {
            try
		    {
                preview.isloading = true;
                preview.player.innerHTML = '<object' + ' id="ClipPlayer" classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" width="1" height="1" TYPE="application/x-oleobject" ' + '>'+
		        '<param name="autoStart" value="true">' + 
		        '<param name="URL" value="' + url + '">' + 
		        '<param name="uimode" value="invisible">' + 
		        '<param name="enableContextMenu" value="false">' + 
		        '<' + 'embed type="application/x-mplayer2" URL="' + url + '" width="1" height="1" ' + '><' + '/embed>' + 
		        '</' + 'object' + '>' + 
		        '<' + 'script for="ClipPlayer" event="PlayStateChange(NewState)" language="javascript">preview.playerevent(NewState);<' + '/script>' + 
		        '<' + 'script for="ClipPlayer" event="error()" language="javascript">preview.stopplayer();<' + '/script>';
		        
		        
		    }
		    catch(err)
		    {
		        preview.isloading = false;
		        preview.stopplayer();
		    }
        }
    
    },
    
    event: function(e)
    {
        return (e == null) ? window.event : e;
    }
}

function ffpopit(url) {
	newwindow=window.open(url,'ffpreview','height=300,width=400');
	if (window.focus) {newwindow.focus()}
	return false;
}
