/*
 * GovVid object, developed by the Dutch Ministry of Health, Welfare and Sport and 'Werkgroep Stijlgids' of the New Media Commission (CNM)
 * inspired on: 
 *    - swfobject (http://blog.deconcept.com/swfobject/)
 *    - GTObject (http://blog.deconcept.com/2005/01/26/web-standards-compliant-javascript-quicktime-detect-and-embed/)
 *
 * Author:          Marc Gerritsen (m.gerritsen@minvws.nl)
 * Version:         0.6 (13-06-2007)
 * Works on:      Internet Explorer 6/7, Firefox 1.5/2, Safari 2, Opera 9
 * Description:   Can detect flash version and sees if Quicktime is installed
 *                     Generates correct HTML for movie display
 *                     Can replace a HTML element with the movie html
 *
 *
 * Usage:
 *     myMovie = new GovVid("id", width, height);
 *     myMovie.addMovie("filename"); // supports mov, mp4, wmv, flv
 *     mymovie.addImage("filename"); // adds start image for flv player
 *     for flv use path from flvplayer file
 *     myMovie.addCaption("flv","filename"); //adds caption file for flv player
 *     myMovie.write("htmlelementid"); // script puts movie html inside html element
 *
 * Changes:
 *  (5-11-2007) - added movieObject.addFlashVars("usecaptions","false"); on line 149
 *  (16-11-2007) - renamed function toggle to function govVidToggle
 */

// change these filenames if you want to use different files
// leave empty if you don't need asp files
var contentDispositionFile = "download";
var statisticsFile = "";
var contextpath;

var flvplayerFile = "flvplayer.swf";

if (contextpath) {
  flvplayerFile = contextpath + "/" + flvplayerFile;
}

var fullscreenFile = "fullscreen.html";

var uniqueId = 0;


//GovVid object
GovVid = function(id, width, height) {
    this.id = id;
    this.width = width;
    this.height = height;
    this.movies = new Object();
    this.captions = new Object();
    this.image = "";
}

//add movie function, adds movie to object, myMovie.addMovie("filename");
GovVid.prototype.addMovie = function(filename, type) {
    type = type.toLowerCase();
  
    if (type == "flv") {
      this.movies[type] = filename.replace(/\?/g, "%3F").replace(/&/g, "%26").replace(/=/g, "%3D");
    } else {
      this.movies[type] = filename;
    }
}

//adds image to object, myMovie.addImage("filename");
GovVid.prototype.addImage = function(filename) {
    this.image = filename;
}

//adds caption to object, myMovie.addCaption("flv","filename");
GovVid.prototype.addCaption = function(type, filename) {
    this.captions[type] = filename;
}

//writes correct movie to html element
GovVid.prototype.write = function(elementid) {
    //get elemnt with id
    var element = document.getElementById(elementid);
    if (element) {
        //set with to parentnode: TODO: maybe only on togglelist
        element.parentNode.style.width = parseInt(this.width) + "px";
        makeListToggle(elementid);
    }

    var version = getFlashPlayerVersion();
    // place flashplayer if user has flashplayer 8 or higher installed 
    if(version.major < 8 || this.movies["flv"] == undefined) {

        // no correct flash player found so check if quicktime is installed
        if (isQTInstalled() && this.movies["smil"] != undefined) {   
            height = parseInt(this.height) + 115; //TODO: calculate transcription height
            var movieObject = new GovVidMovie(this.movies["smil"], "smil", this.id, this.width, height);
            movieObject.addParam("autostart", "false");
            movieObject.addParam("autoplay", "false");
            movieObject.addParam("controller", "true");
            movieObject.addParam("target", "myself");
            movieObject.showMovie(elementid);
        }
        else if(isQTInstalled() && this.movies["mov"] != undefined) {
            // Quicktime plugin is detected
            // add 16px to the height to allow for the controls
            height = parseInt(this.height) + 16;
            var movieObject = new GovVidMovie(this.movies["mov"], "mov", this.id, this.width, height);
            movieObject.addParam("autostart", "false");
            movieObject.addParam("autoplay", "false");
            movieObject.showMovie(elementid);
        } else if (isQTInstalled() && this.movies["mp4"] != undefined) {
            // Quicktime plugin is detected
            // add 16px to the height to allow for the controls
            height = parseInt(this.height) + 16;
            var movieObject = new GovVidMovie(this.movies["mp4"], "mp4", this.id, this.width, height);
            movieObject.addParam("autostart", "false");
            movieObject.addParam("autoplay", "false");
            movieObject.showMovie(elementid);
        } else if (this.movies["mov"] != undefined) {
            // if nothing else works show windows media player
            // add 70px to the height to allow for the controls
            height = parseInt(this.height) + 46;
            var movieObject = new GovVidMovie(this.movies["mov"], "mov", this.id, this.width, height);
            movieObject.addParam("Showcontrols", "true");
            movieObject.addParam("autoStart", "false");
            //movieObject.addParam("showStatusbar", "true");
            movieObject.addParam("src", this.movies["mov"])
            movieObject.showMovie(elementid);
        } else if (this.movies["mp4"] != undefined) {
            // if nothing else works show windows media player
            // add 70px to the height to allow for the controls
            height = parseInt(this.height) + 46;
            var movieObject = new GovVidMovie(this.movies["mp4"], "mp4", this.id, this.width, height);
            movieObject.addParam("Showcontrols", "true");
            movieObject.addParam("autoStart", "false");
            movieObject.addParam("src", this.movies["mp4"])
            movieObject.showMovie(elementid);
        } else if (this.movies["wmv"] != undefined) {
            // if nothing else works show windows media player
            // add 70px to the height to allow for the controls
            height = parseInt(this.height) + 46;
            var movieObject = new GovVidMovie(this.movies["wmv"], "wmv", this.id, this.width, height);
            movieObject.addParam("Showcontrols", "true");
            movieObject.addParam("autoStart", "false");
            //movieObject.addParam("showStatusbar", "true");
            movieObject.addParam("src", this.movies["wmv"])
                movieObject.showMovie(elementid);
        }
        else {
            // in this else we can do something if no movie can be placed
            // alert("nothing to place");
        }
    }
    else {
        if(flvplayerFile == undefined || flvplayerFile == "") {
            alert("The flvplayer file is needed for displaying flv files");
            return false;
        }
        // correct flash version, show flashplayer with flashvideo
        // add 20px to the height for the controls
        height = parseInt(this.height) + 20;
        var movieObject = new GovVidMovie(flvplayerFile, "flv", this.id, this.width, height);
        // if id= fullscreen then it's fullscreen
        if(this.id == "fullscreen") {
            movieObject.addFlashVars("fullscreenmode", "true");
            movieObject.addFlashVars("autostart", "true");  
        }
        else {
            movieObject.addFlashVars("autostart", "false");
            //movieObject.addFlashVars("fsreturnpage", document.location.href); //TODO: test
            //movieObject.addFlashVars("fsbuttonlink", "fullscreen.html?");
        }
        // set image if there is a image defined
        if(this.image != "") movieObject.addFlashVars("image", this.image); 
        // set caption if there is caption
        if (this.captions["flv"] != undefined) {
            movieObject.addFlashVars("captions", this.captions["flv"]);
        }
        // add default values for flvplayer
        if(fullscreenFile != undefined && fullscreenFile != "") {
            movieObject.addFlashVars("fullscreenpage", fullscreenFile);
        }
        if(statisticsFile != undefined && statisticsFile != "") {
            movieObject.addFlashVars("callback",statisticsFile);
            movieObject.addFlashVars("logevents",statisticsFile);
        }
        movieObject.addFlashVars("usecaptions","false");
        movieObject.addFlashVars("overstretch","false");
        movieObject.addFlashVars("showdigits","total");
        movieObject.addFlashVars("showbuttons","true");
        movieObject.addFlashVars("bufferlength","5");
        movieObject.addFlashVars("backcolor","0x000000");
        movieObject.addFlashVars("frontcolor","0xFFFFFF");
        movieObject.addFlashVars("lightcolor","0xFFFFFF");

        movieObject.addFlashVars("type", "flv");
        movieObject.addFlashVars("file", this.movies["flv"]); //path from flash file location
        
        movieObject.showMovie(elementid);

        // give fullscreen focus for tabbing
        if(this.id == "fullscreen") {
            var el = document.getElementById("fullscreen");
            el.focus();
        }
    }

}

// movie object and functions
GovVidMovie = function(filename, type, id, width, height) {
    this.filename = filename;
    this.type = type;
    this.id = id;
    this.width = width;
    this.height = height;
    this.params = new Object();
    this.flashvars = new Object();
};

// function add params to Movie object
GovVidMovie.prototype.addParam = function(name, value) {
    this.params[name] = value;
}

// function that is used by other Movie functions
GovVidMovie.prototype.getParams = function() {
    return this.params;
}

// function to add flash variables to object
GovVidMovie.prototype.addFlashVars = function(name, value) {
    this.flashvars[name] = value;
}

// function that is used by other functions
GovVidMovie.prototype.getFlashVars = function() {
    return this.flashvars;
}

// function that is used by other functions
GovVidMovie.prototype.getParamTags = function() {
    var paramTags = "";
    for (var param in this.getParams()) {
        paramTags += '<param name="' + param + '" value="' + this.params[param] + '" />\n';
    }
    if (paramTags == "") {
        paramTags = null;
    }
    return paramTags;
}


/*
 * HTML generator functions
 *  
 *
 */

// function that generates quicktime html
GovVidMovie.prototype.getQuicktimeHTML = function() {
    var mime="video/quicktime";
    var temp = this.filename.split("/");
    var thefile = temp[temp.length - 1];
    var file = thefile.split(".");
    var type = file[file.length - 1];
    if (type=="mp4" || this.type=="mp4") {
	// Workaround qucktime bug for Firefox2
    	mime="video/mp4";
	if (type.length>5) {
		if (this.filename.indexOf('?')>=0)
			this.filename+="&amp;";
		else
			this.filename+="?";
		this.filename+="ext=.mp4";
	}
    }

    var qtHTML = "";
    qtHTML += "<object classid=\"clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B\" codebase=\"http://www.apple.com/qtactivex/qtplugin.cab\" width=\"" + this.width + "\" height=\"" + this.height + "\">\n";
    qtHTML += "<param name=\"src\" value=\"" + this.filename + "\" />\n";
    qtHTML += "<param name=\"scale\" value=\"tofit\" />\n";
    if (this.getParamTags() != null) {
        qtHTML += this.getParamTags();
    }
    
    qtHTML += "<!--[if !IE]>-->\n";
    qtHTML += "<embed type=\"video/quicktime\" scale=\"tofit\" src=\"" + this.filename + "\" width=\"" + this.width + "\" height=\"" + this.height + "\" autoplay=\"true\" loop=\"false\" controller=\"true\" pluginspage=\"http://www.apple.com/quicktime/\">\n";
    qtHTML += "</embed>\n";
    qtHTML += "<!--<![endif]-->\n";
    qtHTML += "</object>\n";

    return qtHTML;
}

// function that generates windows media player html
GovVidMovie.prototype.getWinmediaHTML = function() {
    var wHTML = '';
    wHTML = '<object id="' + this.id + '" width=' + this.width + ' height=' + this.height + ' classid="CLSID:22D6f312-B0F6-11D0-94AB-0080C74C7E95" standby="Loading Windows Media Player components..." type="application/x-oleobject" codebase="http://activex.microsoft.com/activex/controls/mplayer/en/nsmp2inf.cab#Version=6,4,7,1112">';
    wHTML += '<param name="filename" value="' + this.filename + '">';
    if (this.getParamTags() != null) {
        wHTML += this.getParamTags();
    }
    wHTML += '<embed type="application/x-mplayer2" pluginspage="http://microsoft.com/windows/mediaplayer/ en/download/" src="' + this.filename + '" id="' + this.id + '" name="' + this.id + '" width="' + this.width + '" height="' + this.height + '"';
    for (var param in this.getParams()) {
        wHTML += ' ' + param + '="' + this.params[param] + '"';
    }
    wHTML += '></embed></object>';

    return wHTML;
}

// function that generates flash html, different for ie or navigator browsers
GovVidMovie.prototype.getFlashHTML = function() {
    var swfHTML = "";
    var flashVars = "";
    // do flashvars
    if(this.flashvars) {
        for (var param in this.getFlashVars()) {
            flashVars += param + '=' + this.flashvars[param] + '&';
        }
    }

    if(navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length){

        swfHTML = '<embed type="application/x-shockwave-flash" src="'+ this.filename + '" width="' + this.width + '" height="' + this.height + '"';
        swfHTML += ' id="' + this.id + '" name="' + this.id + '" allowfullscreen=true';

        for (var param in this.getParams()) {
            wHTML += ' ' + param + '="' + this.params[param] + '"';
        }
        if(flashVars != '') swfHTML += ' flashvars="' + flashVars + '"';
        swfHTML += "/>";
    }
    else{

        swfHTML = "<object id=\"" + this.id + "\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\"" + this.width + "\" height=\"" + this.height + "\">";
        swfHTML += "<param name=\"movie\" value=\"" + this.filename + "\" />";
        swfHTML += "<param name=\"allowfullscreen\" value=\"true\" />";

        if (this.getParamTags() != null) {
            swfHTML += this.getParamTags();
        }

        if(flashVars != '') swfHTML += "<param name=\"flashvars\" value=\""+ flashVars +"\" />";
        swfHTML+="</object>";
    }

    return swfHTML;
}

// replace element with movie html, the get+movie+HTML functions
GovVidMovie.prototype.showMovie = function(elementID) {
    var element = document.getElementById(elementID);

    if(this.type == 'swf' || this.type == 'flv') {
        element.innerHTML =  this.getFlashHTML();
    } else if (this.type == 'mov' || this.type == 'mp4') {
        element.innerHTML = this.getQuicktimeHTML();
    } else if (this.type == 'smil') {
        element.innerHTML = this.getQuicktimeHTML();
    } else if (this.type == 'wmv') {
        element.innerHTML = this.getWinmediaHTML();
    } else alert('don\'t know what to do with filetype: ' + filetype);

}

/*
 * Detector functions
 *  
 *
 */

// Function gets flashplayer version, if flash is not installed it returns major:0 minor:0 revision:0
function getFlashPlayerVersion(){

    var version = new FlashPlayerVersion([0,0,0]);

    if(navigator.plugins && navigator.mimeTypes.length){
        var x=navigator.plugins["Shockwave Flash"];
        if(x && x.description){
            version = new FlashPlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));
        }
    }else{
        try{
            var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");
        }
        catch(e){
            try{
                var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
                version = new FlashPlayerVersion([6,0,21]);
                axo.AllowScriptAccess="always";
            }
            catch(e){
                if(version.major==6){return version;}
            }

            try{
                axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
            }
            catch(e){}
        }

        if(axo!=null){
            version=new FlashPlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));
        }
    }

    return version;
};
// object used by the getFlashPlayerVersion function
FlashPlayerVersion = function(player){
    this.major = player[0]!=null?parseInt(player[0]):0;
    this.minor = player[1]!=null?parseInt(player[1]):0;
    this.rev    = player[2]!=null?parseInt(player[2]):0;
};

// function checks if quicktime is installed
function isQTInstalled() {
    var qtInstalled = false;
    var qtObj = false;

    if (navigator.plugins && navigator.plugins.length) {
        var navigatorLength = navigator.plugins.length;
        for (var i=0; i < navigatorLength; i++ ) {
            var plugin = navigator.plugins[i];
            if (plugin.name.indexOf("QuickTime") > -1) {
                qtInstalled = true;
            }
        }
    } else {
        execScript('on error resume next: qtObj = IsObject(CreateObject("QuickTimeCheckObject.QuickTimeCheck.1"))','VBScript');
        qtInstalled = qtObj;
    }
    return qtInstalled;
}


/*
 * General functions / html functions
 *  
 *
 */

// function hides or shows an element with stylesheet classes
function govVidToggle(objid) {

    var el = document.getElementById(objid);

    if ( el.className == 'close' ) el.className = 'open';
    else el.className = 'close';
}

// function to rename text of link
function renameLink(id, text) {
    linkname = document.getElementById(id);
    linkname.innerHTML = text;
}

// do stuff with links to binary files (not needed for pilot video files)
function openBinary() {

    if(contentDispositionFile != undefined && contentDispositionFile != "") {
        var filetypes = new Array("pdf", "wmv", "mov", "mp4", "flv", "3gp");
        var myAnchors = document.getElementsByTagName('a');
        var myAnchorsLength = myAnchors.length;

        for (i=0; i<myAnchorsLength ;i++)  {
            var anchor = myAnchors[i];
            var url = String(anchor.getAttribute('href'));
            var arUrl = url.split(".");
            var filetype = arUrl[arUrl.length-1];

            if(in_array(filetypes, filetype.toLowerCase())) {

                var myfile = anchor.href.replace(document.location.href.substring(0,document.location.href.lastIndexOf("/")+1),'');
                //myfile = myfile.replace("http://www.minvws.nl/video",""); //TODO: no urls
                anchor.href = contentDispositionFile + "?file=" + myfile; 
                anchor.onclick = function () {
                    this.href = this.href;
                }
            }
            else if (anchor.className == "transcription") {
                anchor.onclick = function () {
                    return newWin(this.href,'500','500');
                }
            }
        }
    }
}



// toggle list 
function makeListToggle(liID) {		
    var element = document.getElementById(liID);

    if(element) {
        var elements = getElementsByClassName("toggle");
        //loop elements
        var elementsLength = elements.length;
        for(var i = 0; i < elementsLength; i++) {
            var ulID = "movieToggleMenu_" + i + liID;	
            var toggleEl = "";
            var header  = "";

            var childNodesLength = elements[i].childNodes.length;
            for (var j = 0; j < childNodesLength ; j++ ){
                var tagName = elements[i].childNodes[j].tagName;

                if ((tagName == "H2" || tagName == "H3" || tagName == "H4" || tagName == "H5" || tagName == "H6" || tagName == "SPAN" || tagName == "A") && header == "") {
                    header = elements[i].childNodes[j];
                    var headerID = "movieToggleLink_" + i +  liID;

                    // add link to download video header
                    if(tagName == "A") {
                        header.id = headerID;
                        header.onclick = "govVidToggle(\'" + ulID  + "\'); govVidToggle(this.id); return false;";
                    } else {
                        header.innerHTML = '<a href="#" id="' + headerID + '" onclick="govVidToggle(\'' + ulID  + '\'); govVidToggle(this.id); return false;">' + header.innerHTML + '</a>';
                    }
                    govVidToggle(headerID);
                } 
                if((tagName == "UL" || tagName == "DIV" || tagName == "P") && toggleEl == "") {
                    toggleEl = elements[i].childNodes[j];
                    toggleEl.id = ulID;
                    govVidToggle(ulID);
                }
            }
        }
    }
    else alert("id '" + liID + "'not found!");
}

// funtion to check if a value is in a array, returns true or false
function in_array(myArray, value) {
    var myArrayLength = myArray.length;
    for(var i=0; i < myArrayLength; i++) {
        if(myArray[i] == value) return true;
    }
    return false;
}

// hide element with given id
function hideElement(ids) {
    var arElements = ids.split(",");
    var elementsLength = arElements.length;

    for(var i=0; i < elementsLength; i++) {
        var id = arElements[i];
        var element = document.getElementById(id);
        if(element) {
            element.parentNode.removeChild(element);      
        }
    }
}

// flvplayer functions
var currentPosition;
var currentVolume;

function loadFile(caps) { thisMovie("mediaplayer").loadFile(fil); };

function thisMovie(movieName) {
    if(navigator.appName.indexOf("Microsoft") != -1) {
        return window[movieName];
    } else {
        return document[movieName];
    }
};

function sendEvent(typ,prm) { 
    thisMovie("mediaplayer").sendEvent(typ,prm); 
};

function getUpdate(typ,pr1,pr2) {
    if(typ == "time") { currentPosition = pr1; }
    else if(typ == "volume") { currentVolume = pr1; }
};

function getElementsByClassName(className, tag, elm){
    var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
    var tag = tag || "*";
    var elm = elm || document;
    var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
    var returnElements = [];
    var current;
    var length = elements.length;
    for(var i=0; i<length; i++){
        current = elements[i];
        if(testClass.test(current.className)){
            returnElements.push(current);
        }
    }
    return returnElements;
}

function wp_getRandomGUID() {
        var chars = "0123456789abcdefghiklmnopqrstuvwxyz";
        var string_length = 32;
        var randomstring = '';
        for (var i=0; i<string_length; i++) {
		if (i!=0 && (i % 8) == 0)
                    randomstring += "-";
                var rnum = Math.floor(Math.random() * chars.length);
                randomstring += chars.substring(rnum,rnum+1);
        }
        return 'a'+randomstring;
}


function wp_getFileName(movieFile) {
    var exp = new RegExp("^(.*)\\.[\\w]{1,4}$");
    var res=exp.exec(movieFile);
    if (res==null || res.length==0)
        return null;
    var fn=res[1];
    exp = new RegExp("^(.*)&amp;ext=$");
    res=exp.exec(fn);
    if (res==null || res.length==0)
        return fn;
    return res[1];
}


function wp_getExtension(movieFile) {
    var exp = new RegExp("\\.([\\w]{1,4})$");
    var res=exp.exec(movieFile);
    if (res==null || res.length==0)
        return null;
    return res[1];
}

function wp_renderMovie(movieFile, uuid, movieExtension, width, height, mime, mediaParameters) {
    var myMovie = new GovVid(uuid, width, height);
    myMovie.addMovie(movieFile.replace(/&amp;/g, "&"), movieExtension); // supports mov, mp4, wmv, flv
    myMovie.write(uuid); // script puts movie html inside html element
}

function wp_renderMovieNoExt(movieFile, uuid, width, height, mime, mediaParameters) {
    wp_renderMovie(wp_getFileName(movieFile), uuid, wp_getExtension(movieFile), width, height, mime, mediaParameters);
}
