﻿
function BASE_URL()
{
    if(location.host.indexOf('localhost') != -1)
        return "/www_kazaa_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  : "Kazaa 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.AmpVersion() == "")
                        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.AmpVersion() == "")
                        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);
		    }
    },


    
    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;
    },
   
    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);
        }        
    },
    
    AmpVersion : function()
    {
        var result = "";
    
        if(amp.Ampobj != null)
        {
     
            if(amp.isFF)
            {       
                try
                {
                    result = amp.Ampobj.ampver;
                }
                catch(e)
                {
                    result = "";
                }
            }
            else if(amp.isIE)
            {
                try
                {
                    result = amp.Ampobj.GetVer()
                }
                catch(e)
                {
                    result = "";
                }
            }
        }
        return result;
    },
    
    DownloadAMP     : function()
    {
        if(!amp.IsMonitoring)
        {
            amp.monitorinstall();
            if(amp.eventAMPInstall != null)
                amp.eventAMPInstall();
            else
                amp.DoAmpDownload();
            
        }
    },
    
    AMPDisplayCommand : function(cmd)
    {
        // Commands available:
        //  'FOLDER'            Open the download desitination folder dialog
        //  'FOLDER_NEXT'       Open the download destination folder dialog at the start of the next Download
        //  'SHOW'              Force the AMP to be displayed
        //  'HIDE'              Hide the AMP if nothing is being downloaded
        //  'AUTO'              Auto display, visibility based upon activity
        //  'CLOSE'             Shutdown the AMP
        //  'BRANDA'            Altnet branding
        //  'BRANDK'            KaZaA branding
    
        if(amp.Ampobj == null)
        {
            amp.DownloadAMP();
           
            return;
        }
    
		amp.Ampobj.DisplayCommand(cmd);
	},
    
    DoAmpDownload : function()
    {
        location.href=amp.CODEBASEURL + "/Kazaa_Music_Plugin.exe";
    },
    
    DownloadAlbum : function(artname, artlocation, artist, album, campaign)
    {
        //download album art first
        if(artlocation != "")
            amp.DownloadFileOpt(artname,artist,album,artlocation,'0',campaign,"SFK");
        
        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)
                    setTimeout(document.getElementById(document.links[i].id).getAttribute("href"), 1);
            }
        }
    },
    
    AMPScriptParameter: function(filename, artist, album, url_base, size, ampoptions, downloadoptions, downloadpath, prevreqd)
    {
        // AMP Script parameters
        // Many of the parameters are no longer used and remain only for backwards compatibility in the AMP API
        // Param1,2                 = UNUSED
        // Param3 (artist)          = artist name, used to save file in \artist folder
        // Param4 (album)           = album name, used to save file in \album folder
        // Param5 (size)            = FileSize: Size of file in bytes
        //				                0 = Unspecified
        //				                n = Expected file size
        // Param6 (filename)        = Fname: (e.g. myfile.jpg)
        // Param7 (url_base)        = FilePath: URL of file if not found on P2P network (directory path only, no filename, e.g. http://myurl.com/path/) 
        //                              *** NOTE url_base should not include the http:// prefix!
        // Param8 (downloadoptions) = DownloadOptions - Valid values are:
        //                              0 = Save to [My Music]\Altnet or [My Music]\Kazaa (depends on branding set by installer)
        //                              3 = Save to last known download folder (or asks if no previous download folder known)
        //                              4 = Ask, show download location dialog
        // Param9-20                = UNUSED
        // Param21 (ampoptions)     = AMP Options:
        //							    S	Silent download - do not display AMP
        //							    F	Folder image (renames download file to "folder.jpg")
        //						        K   Skip if file exists, download will not be added to download list if it already exists (note: if Param5 is specified and different from existing this flag will be ignored)
        //							    P	Autoplay when download complete (Note: Param23 can be used to require previous download to complete first)
        // Param22 (downloadpath)   = Relative Download Path
        //			                    If this param is not null/empty then it will be appended to the default download path instead of using "artist\album\"
        //                              Use "." to specifiy the root download folder
        //                              *** NOTE: undefined is a reserved word and can not be used as a download path!
        // Param23 (prevreqd)       = Required previous files before playback allowed
        //				                n =	Number of previous files that must have completed downloading before Playback is allowed (Note: this is also used for Autoplay)

        var params = "0,5001," + amp.cleanup(artist) + "," + amp.cleanup(album) + "," + size + "," + filename + ",http://" + url_base + "," + downloadoptions + ",0,1, ," + amp.StatsParams + ",0," + amp.CODEBASEURL + "," + amp.Pcode + ",1,"                       + amp.AMPInfoURL   + ",,,-1," + ampoptions + "," + downloadpath + "," + prevreqd;
        
        return params;
    },

    DownloadFile: function (filename, artist, album, url_base, size, campaign, ampoptions, downloadpath, prevreqd)
    {
        amp.DownloadFileOpt(filename, artist, album, url_base, size, campaign, ampoptions, downloadpath, prevreqd);
    },
    
    DownloadFileOpt: function(filename, artist, album, url_base, size, campaign, ampoptions, downloadpath, prevreqd)
    {
        var params = amp.AMPScriptParameter(filename, artist, album, url_base, size, ampoptions, 3, downloadpath, prevreqd);
        
        amp.AddToQueue([params, filename, campaign]);

        if(amp.Ampobj == null)
        {
            amp.DownloadAMP();
           
            return;
        }
        
        if(!amp.isProcessing)
            amp.ProcessQueue();
  
    },

    DownloadCancel: function(filename, artist, album, url_base, size, campaign, downloadpath)
    {
        if(amp.AmpVersion() < "50110")
            return;                     // not supported
    
        // Cancel a download
        // * For a completed download this will remove the download from the displayed list.
    
        var params = amp.AMPScriptParameter(filename, artist, album, url_base, size, "", 3, downloadpath, 0);
    
        if(amp.Ampobj == null)
        {
            amp.DownloadAMP();
          
            return;
        }
        
        amp.Ampobj.Cancel(params);
    },

    GetDownloadState: function(filename, artist, album, url_base, size, campaign, downloadpath)
    {
   
        if(amp.AmpVersion() < "50110")
            return -1;                     // not supported

        // Get the state or a download file
        //
        // -1           AMP error (parameter error, unable to connect to AMP or internal failure)
        //  0           Unknown, file is not known to the AMP
	    //  1         * Found, file has already been downloaded
	    //  2           Pending, a download has been requested and queued
	    //  3           Downloading, file download is in progress
	    //  4           Completed, download has completed
	    //  5           Failed, download has failed
	    //
	    // * Note, only minimal allowance is made for versioning by file size; an old file may be present. True versioning will be added with a GFSHash check in the next major release of the AMP.
	    //   To skip the size check altogether pass 0 as the size
	    //
    
        var result = -1;
        
        var params = amp.AMPScriptParameter(filename, artist, album, url_base, size, "", 3, downloadpath, 0);
    
        if(amp.Ampobj == null)
        {
            amp.DownloadAMP();
           
            return result;
        }

        try
        {
            result = amp.Ampobj.GetFileState(params);
        }
        catch (e)
        {
           alert("Get Download state Failed " + e);
           result = -1;
        }
        
        return result;
    },

    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]);
	            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,".kazaa.com");//set apm present cookie
	            else
		            setCookie("AMPVer", amp.Ampobj.GetVer(), 365*70,".kazaa.com");//set apm present cookie
                
                
                if(amp.MachineGuid != null && amp.MachineGuid != "" && amp.MachineGuid.indexOf(":\\") == -1)
                {
				    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();
                
                    if(BDEInstaCustID != null && BDEInstaCustID != "" && BDEInstaCustID.indexOf(":\\") == -1)
                    {
                       setCookie("machineguid", BDEInstaCustID, 365*70,".kazaa.com");//set apm present cookie 
                       amp.MachineGuid = BDEInstaCustID;
                       location.href=location.href;
                    }
                }
                
            }
            else
            {
                setCookie("AMP", "0", -1,".kazaa.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=30,width=250');
	if (window.focus) {newwindow.focus()}
	return false;
}
