/*
Plugin Name: playerOs
Plugin URI: http://www.streamsolution.it
Description: Cambia player in base al sistema operativo e al plugin installato
Version: 2.0.0
Author: Fabio Ricali and Dario Spadaro
*/

// initialize global variables
var detectableWithVB = false;
var pluginFound = false;


function goURL(daURL) {
    // if the browser can do it, use replace to preserve back button
    if(javascriptVersion1_1) {
        window.location.replace(daURL);
    } else {
        window.location = daURL;
    }
    return;
}

function redirectCheck(pluginFound, redirectURL, redirectIfFound) {
    // check for redirection
    if( redirectURL && ((pluginFound && redirectIfFound) ||
        (!pluginFound && !redirectIfFound)) ) {
        // go away
        goURL(redirectURL);
        return pluginFound;
    } else {
        // stay here and return result of plugin detection
        return pluginFound;
    }
}

function canDetectPlugins() {
    if(detectableWithVB || (navigator.plugins && navigator.plugins.length > 0) ) {
       return true;
    } else {
       return false;
    }
}

function detectFlash(redirectURL, redirectIfFound) {
    pluginFound = detectPlugin('Shockwave','Flash');
    // if not found, try to detect with VisualBasic
    if(!pluginFound && detectableWithVB) {
        pluginFound = detectActiveXControl('ShockwaveFlash.ShockwaveFlash.1');
    }
    // check for redirection
    return redirectCheck(pluginFound, redirectURL, redirectIfFound);
}

function detectDirector(redirectURL, redirectIfFound) {
    pluginFound = detectPlugin('Shockwave','Director');
    // if not found, try to detect with VisualBasic
    if(!pluginFound && detectableWithVB) {
        pluginFound = detectActiveXControl('SWCtl.SWCtl.1');
    }
    // check for redirection
    return redirectCheck(pluginFound, redirectURL, redirectIfFound);
}

function detectQuickTime(redirectURL, redirectIfFound) {
    pluginFound = detectPlugin('QuickTime');
    // if not found, try to detect with VisualBasic
    if(!pluginFound && detectableWithVB) {
        pluginFound = detectQuickTimeActiveXControl();
    }
    return redirectCheck(pluginFound, redirectURL, redirectIfFound);
}

function detectReal(redirectURL, redirectIfFound) {
    pluginFound = detectPlugin('RealPlayer');
    // if not found, try to detect with VisualBasic
    if(!pluginFound && detectableWithVB) {
        pluginFound = (detectActiveXControl('rmocx.RealPlayer G2 Control') ||
        detectActiveXControl('RealPlayer.RealPlayer(tm) ActiveX Control (32-bit)') ||
        detectActiveXControl('RealVideo.RealVideo(tm) ActiveX Control (32-bit)'));
    }
    return redirectCheck(pluginFound, redirectURL, redirectIfFound);
}

function detectWindowsMedia(redirectURL, redirectIfFound) {
    pluginFound = detectPlugin('Windows Media');
    // if not found, try to detect with VisualBasic
    if(!pluginFound && detectableWithVB) {
        pluginFound = detectActiveXControl('MediaPlayer.MediaPlayer.1');
    }
    return redirectCheck(pluginFound, redirectURL, redirectIfFound);
}


function detectPlugin() {
    // allow for multiple checks in a single pass
    var daPlugins = detectPlugin.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



if ((navigator.userAgent.indexOf('MSIE') != -1) && (navigator.userAgent.indexOf('Win') != -1)) {
document.writeln('<script language="VBscript">');

    document.writeln('\'do a one-time test for a version of VBScript that can handle this code');
    document.writeln('detectableWithVB = False');
    document.writeln('If ScriptEngineMajorVersion >= 2 then');
    document.writeln('  detectableWithVB = True');
    document.writeln('End If');

    document.writeln('\'this next function will detect most plugins');
    document.writeln('Function detectActiveXControl(activeXControlName)');
    document.writeln('  on error resume next');
    document.writeln('  detectActiveXControl = False');
    document.writeln('  If detectableWithVB Then');
    document.writeln('     detectActiveXControl = IsObject(CreateObject(activeXControlName))');
    document.writeln('  End If');
    document.writeln('End Function');

    document.writeln('\'and the following function handles QuickTime');
    document.writeln('Function detectQuickTimeActiveXControl()');
    document.writeln('  on error resume next');
    document.writeln('  detectQuickTimeActiveXControl = False');
    document.writeln('  If detectableWithVB Then');
    document.writeln('    detectQuickTimeActiveXControl = False');
    document.writeln('    hasQuickTimeChecker = false');
    document.writeln('    Set hasQuickTimeChecker = CreateObject("QuickTimeCheckObject.QuickTimeCheck.1")');
    document.writeln('    If IsObject(hasQuickTimeChecker) Then');
    document.writeln('      If hasQuickTimeChecker.IsQuickTimeAvailable(0) Then ');
    document.writeln('        detectQuickTimeActiveXControl = True');
    document.writeln('      End If');
    document.writeln('    End If');
    document.writeln('  End If');
    document.writeln('End Function');

    document.writeln('</scr' + 'ipt>');
}

//main class
function playerOs(url_sc, url_wma, url_pls, url_proxy, w, h, wr, swf_path){
    
    //shoutcast url
    this.urlSC          =   url_sc;
    
    //pls url
    this.urlPls         =   url_pls; 
    
    //windows media audio url
    this.urlWMA         =   url_wma;
    
    //sc_proxy url
    this.urlProxy       =   url_proxy;
    
    //width
    this.width          =   w;
    
    //height
    this.height         =   h;
    
    //wrapper element
    this.wrapper        =   wr;
    
    //path swf player
    this.swfPath        =   swf_path;
    
    if(!this.swfPath) this.swfPath = "player.swf";
    
    this.osName;
    this.playerType;
    this.output;
    
    this.getPlayer      =   getPlayer;
    this.getOS          =   getOS;
    
    this.wmaPlayer      =   wmaPlayer;
    this.qtPlayer       =   qtPlayer;
    this.html5Player    =   html5Player;
    this.flashPlayer    =   flashPlayer;
    this.noPlayer       =   noPlayer;
    
    //choose Player condition
    function getOS(){
        //alert(navigator.appVersion);
        if (navigator.appVersion.indexOf("Win")!=-1 && navigator.userAgent.indexOf('MSIE') !=-1/*&& detectWindowsMedia()*/) this.playerType="WMA";
        if (navigator.appVersion.indexOf("Win")!=-1 && (navigator.userAgent.indexOf('Firefox') !=-1 || navigator.userAgent.indexOf('Chrome') !=-1 || navigator.userAgent.indexOf('Safari') !=-1) && detectQuickTime() && !detectWindowsMedia()) this.playerType="QT";
        if (navigator.appVersion.indexOf("Win")!=-1 && (navigator.userAgent.indexOf('Firefox') !=-1 || navigator.userAgent.indexOf('Chrome') !=-1 || navigator.userAgent.indexOf('Safari') !=-1) && detectWindowsMedia()) this.playerType="WMA";
        if (navigator.appVersion.indexOf("Win")!=-1 && !detectWindowsMedia() && detectFlash() &&!detectWindowsMedia() && !detectQuickTime()) this.playerType="Flash";
        if (navigator.appVersion.indexOf("Win")!=-1 && !detectWindowsMedia() && !detectFlash() && !detectQuickTime()) this.playerType="NoPlayer";
        if (navigator.appVersion.indexOf("Macintosh")!=-1 && detectWindowsMedia()  && !detectFlash() && !detectQuickTime()) this.playerType="WMA";
        if (navigator.appVersion.indexOf("Macintosh")!=-1 && detectQuickTime()) this.playerType="QT";
        if (navigator.appVersion.indexOf("Macintosh")!=-1 && (navigator.userAgent.indexOf('Firefox') !=-1 || navigator.userAgent.indexOf('Chrome') !=-1) && detectFlash()) { this.playerType="Flash"; }
        if (navigator.appVersion.indexOf("Macintosh")!=-1 && !detectFlash() && !detectQuickTime() && !detectWindowsMedia()) this.playerType="NoPlayer";
        if (navigator.appVersion.indexOf("iPhone")!=-1) this.playerType="iPhone";
        if (navigator.appVersion.indexOf("iPad")!=-1)  this.playerType="iPad";
        if (navigator.appVersion.indexOf("Linux")!=-1) this.playerType="Flash";
    }
    
    //Make windows media player
    function wmaPlayer(){
        var output;
        output  = "<object id=\"player\" width=\""+this.width+"\" height=\""+this.height+"\" classid=\"CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6\">";
        output += "<param name=\"url\" value=\""+this.urlWMA+"\"/>";
        output += "<param name=\"AutoStart\" value=\"1\"/>";
        output += "<param name=\"UiMode\" value=\"mini\"/>";
        output += "<param name=\"captioningID\" value=\"captions\"/>";
        output += "<param name=\"ShowTracker\" value=\"0\"/>";
        output += "<embed type=\"application/x-mplayer2\" pluginspage=\"http://www.microsoft.com/Windows/Downloads/Contents/Products/MediaPlayer/\" src=\""+this.urlWMA+"\" width=\""+this.width+"\" height=\""+this.height+"\" showcontrols=\"1\" showpositioncontrols=\"0\" showaudiocontrols=\"1\" showtracker=\"0\" showdisplay=\"0\" autoplay=\"true\" showstatusbar=\"1\" showgotobar=\"0\" showcaptioning=\"0\" autostart=\"1\" autorewind=\"0\" animationatstart=\"1\" transparentatstart=\"0\" allowchangedisplaysize=\"0\" allowscan=\"0\" enablecontextmenu=\"0\" clicktoplay=\"0\" align=\"middle\">  </embed>";
        output += "</object>";
        output += "<div id=\"captions\" style=\"font-family:Trebuchet MS,Arial,sans-serif; width:"+this.width+"\"></div>";
        return output;
    }
    
    //Make html5 player
    function html5Player(){
        var output;
        if (p.urlProxy =='') p.urlProxy = p.urlPls;
        output = "<audio id=\"audio\" controls=\"controls\" width=\""+this.width+"\" height=\""+this.height+"\" src=\""+this.urlProxy+"\" autoplay=\"autoplay\"></audio>";
        return output;
    }
    
    //Make flash player
    function flashPlayer(){
        var output;
        output  = "<object id=\"playlist\" classid=\"clsid:d27cdb6e-ae6d-11cf-96b8-444553540000\" width=\""+this.width+"\" height=\""+this.height+"\" codebase=\"http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0\">";
        output += "<param name=\"align\" value=\"middle\" />";
        output += "<param name=\"allowScriptAccess\" value=\"sameDomain\" />";
        output += "<param name=\"allowFullScreen\" value=\"false\" />";
        output += "<param name=\"FlashVars\" value=\"file="+this.urlSC+";stream.nsv&type=mp3&volume=50&autostart=true\" />";
        output += "<param name=\"quality\" value=\"high\" />";
        output += "<param name=\"src\" value=\""+this.swfPath+"\" />";
        output += "<param name=\"name\" value=\"playlist\" /><param name=\"allowfullscreen\" value=\"false\" />";
        output += "<embed id=\"playlist\" type=\"application/x-shockwave-flash\" width=\""+this.width+"\" height=\""+this.height+"\" FlashVars=\"file="+this.urlSC+";stream.nsv&type=mp3&volume=50&autostart=true\" src=\""+this.swfPath+"\" name=\"playlist\" quality=\"high\" allowfullscreen=\"false\" allowscriptaccess=\"sameDomain\" align=\"middle\"></embed></object>";
        return output;
    }

    //Make quicktime player
    function qtPlayer(){
        var output;
        output  = '<object classid="CLSID:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="http://www.apple.com/qtactivex/qtplugin.cab" width="'+this.width+'" height="'+this.height+'" align="middle">';
        output += '<param name="src" value="'+this.urlPls+'">';
        output += '<param name="autoplay" value="true">';
        output += '<param name="controller" value="true">';
        output += '<embed src="'+this.urlPls+'" width="'+this.width+'" height="'+this.height+'" autoplay="true" controller="true" type="video/quicktime" autostart="true" pluginspage="http://www.apple.com/quicktime/download/" align="middle">';
        output += '</object>';
        return output;
    }
    
    //no player
    function noPlayer(){
        var output;
        output   = '<font face="Arial" size="1">Se non visualizzi correttamente il player: <br />';
        output  += '<b>Utenti Windows</b>: <a href="http://www.microsoft.com/windows/windowsmedia/download/AllDownloads.aspx?displang=en" target="_blank">Internet Explorer</a> - <a href="https://addons.mozilla.org/it/firefox/browse/type:7" target="_blank">Firefox</a> - <a href="http://www.apple.com/safari/download/plugins.html" target="_blank">Safari</a><br /><b><a href="http://www.microsoft.com/windows/windowsmedia/player/wmcomponents.mspx" target="_blank">Utenti Mac</a></b>'; 
        output  += '</font>';
        return output;
    }
    
    //switch player
    function getPlayer(){
        this.getOS();
        switch(this.playerType){
            case "WMA":
                this.output = this.wmaPlayer();
                break;
            
            case "QT":
                this.output = this.qtPlayer();
                break;
            
            case "Flash":
                this.output = this.flashPlayer();
                break;
            
            case "iPhone":
                this.output = this.html5Player();
                break;
            
            case "iPad":
                this.output = this.html5Player();
                break;
                
            case "noPlayer":
                this.output = this.noPlayer();
                break;
            
            default :
                this.output = this.flashPlayer();
                break;
        }
        document.getElementById(this.wrapper).innerHTML = this.output;
    }
    
}
