
/**
 * Handles movie playing for Byggprojekten
 * 
 * author		andreas.lanjerud@cloudnine.se
 * co-author	fjo@byggmax.se
 */

var STREAMING_SERVER			= 'rtmpt://fl0.c05731.cdn.qbrick.com:80/05731';
var FLOWPLAYER_PATH				= '/Flash/Flowplayer/flowplayer.commercial-3.0.1.swf';
var FLOWPLAYER_CONTROLS_PATH	= '/Flash/Flowplayer/flowplayer.controls-3.0.1.swf';
var FLOWPLAYER_RTMP_PATH		= '/Flash/Flowplayer/flowplayer.rtmp-3.0.0.swf';
var FLOWPLAYER_KEY				= '#$f9a18f7c45828ea6dab';

var MAXI_PLAYER_CONTAINER_ID = "byggmaxPlayerContainer";
var MINI_PLAYER = 0;
var MIDI_PLAYER = 1;
var MAXI_PLAYER = 2;
var movieTimer = null;
var movieCounter = 0;
var popinMovieHash = new Array();



$(document).ready(function() {
    
    var ua = navigator.userAgent,
    getViewPort = function () {
        var vpo = {}, b;

        if ((/MSIE\s/).test(ua)) {
            window.innerHeight = document.documentElement.clientHeight ? document.documentElement.clientHeight : document.getElementsByTagName('body')[0].clientHeight;
            window.innerWidth = document.documentElement.clientWidth ? document.documentElement.clientWidth : document.getElementsByTagName('body')[0].clientWidth;
        }

        if ((/MSIE\s/).test(ua)) {
            b = (document.compatMode && document.compatMode !== "BackCompat") ? document.documentElement : document.body;
            window.pageYOffset = b.scrollTop;
            window.pageXOffset = b.scrollLeft;
        }

        vpo.top = window.pageYOffset;
        vpo.left = window.pageXOffset;

        return vpo;
    };

    // show chapters
    $("div.constructionnav li.project h5").click(function() {
        $(this).next().slideToggle("fast").addClass("open");
    });

    // hover
    $('li.timestamp').not('.selected').hover(function() {
        $(this).addClass('selected');
    }, function() {
        $(this).removeClass('selected');
    });

    // If visitor clicks on a movie link under the byggprojekt navigation
    $('li.timestamp a').click(function(e) {
        e.preventDefault();

        var myChapter = $(this).parent();
        setChapter(myChapter);
        playChapter(myChapter.getTimestamp());
    });

    /**
    * prepare and initiate main player
    */
    $('#' + MAXI_PLAYER_CONTAINER_ID).each(function() {

        // find main players attributes
        var MOVIE_PATH = $("input[name='MOVIE_PATH']").val();
        var MOVIE_CUEPOINT = $("input[name='CUEPOINT']").val();

        // load player
        popinMovieHash[MAXI_PLAYER_CONTAINER_ID] = {};
        initPlayer(MAXI_PLAYER_CONTAINER_ID, MOVIE_PATH, MAXI_PLAYER, MOVIE_CUEPOINT);
        $f(MAXI_PLAYER_CONTAINER_ID).load();
        
    }); 
    
    //$("div.m0.start.previewContainer a.colPlayerContainer").addClass("screenshot");

	/**
	* prepare and initiate column players
	*/
	$("a.colPlayerContainer:not(.screenshot)").each(function(container_count) {
		var t = $(this), 
		myContainerID = t.attr("id"),    // find column player (if any) and it's attributes contained inside block

		myMoviepath = t.parent().find("input[name='moviepath']:first").val(),
		myCuepoint = t.parent().find("input[name='cuepoint']:first").val(),
		movie_popup = t.parent().find("input[name='relmovie']:first").val();

        popinMovieHash[movie_popup] = {};
        popinMovieHash[myContainerID] = {};
        
         // load player
        initPlayer(myContainerID, myMoviepath, MINI_PLAYER, myCuepoint);
        
        $f(myContainerID).onBeforeUnload(function() {
            this.pause();    // pause column players
            return false;    // prevent popinMovie to unload all column movies
        });
        
	    $f(myContainerID).load();

	    // var popinMovieID = $(this).parent().parent().find(".popinPlayerContainer").attr("id");
	    // var popinMovieID = "popinPlayerContainer" + container_count + "start";
		
		
        popinMovieHash[movie_popup].isVisible = false;
	});
	
	$("a.colPlayerContainer.screenshot").each(function(container_count) {
		var t = $(this), myContainerID = t.attr("id");    // find column player (if any) and it's attributes contained inside block

		var movie_popup = t.parent().find("input[name='relmovie']:first").val();

        popinMovieHash[movie_popup] = {};
        popinMovieHash[movie_popup].isVisible = false;
	});
    
    var popInMovieDivId = 0;
    $(".popinMovie").each(function () {
        this.style.position = "absolute";
        this.style.zIndex = "10000";
        
        this.id = "popInMovie" + popInMovieDivId;
        
        popInMovieDivId += 1;
    });
    
    $(".popinMovieHover").each(function () {
        var that = this, 
        h, 
        w;
        that.popInfo = {};
        
        if (that.parentNode) {
        
            $(that.parentNode).find("input").each(function () {
                that.popInfo[this.name] = this.value;
            });
            
            $(that).click(function (e) {
                var p = this.popInfo, 
                pd = document.getElementById(p.relmovie),
                pmid = pd.parentNode.id;
                
                e.preventDefault();
                        
                $(".popinMovie:not(#" + pmid + ")").css({
                    display : "none"
                });
                
                $("#" + p.relmovie).css({ 
                    display: "block"
                });
                
                p.moviepath = $("#" + p.relmovie).parent().find("input[name=moviepath]").attr("value");
                p.cuepoint = $("#" + p.relmovie).parent().find("input[name=cuepoint]").attr("value");
                
                pd.parentNode.position = function () {
                    var relTop = 121, 
                    t = getViewPort().top, 
                    o = $(".outer")[0], 
                    that2 = this;
                    
                    this.style.top = parseInt(relTop + t, 10) + "px";
                    this.style.left = parseInt((parseInt(o.offsetWidth / 2, 10) - parseInt(this.offsetWidth / 2, 10)) + (o.offsetLeft), 10) + "px"; //parseInt(o.offsetWidth / 2) + "px";
                    
                    
                    /*$(window).resize(function () {
                        pd.parentNode.position();
                    });*/
                };
                
                if (MAXI_PLAYER_CONTAINER_ID && document.getElementById(MAXI_PLAYER_CONTAINER_ID)) {
                    $("#" + MAXI_PLAYER_CONTAINER_ID).flowplayer().each(function () {
                        this.pause();
                    });
                }
                
                $("a.colPlayerContainer:not(.screenshot)").flowplayer().each(function() {
                    this.pause();
                });
                
                //alert(p.relmovie + "\n" + p.moviepath + "\n" + MIDI_PLAYER + "\n" + p.cuepoint + "\n" + pmid);
                
                initPlayer(p.relmovie, p.moviepath, MIDI_PLAYER, p.cuepoint, pmid);
                
                pd.parentNode.position();
                
                //alert($f((p.relmovie)));
                
                $f(p.relmovie).load();
                
                $(pd.parentNode).find(".closePopin:not(.hasCloseClick)").each(function () {
                    var t = $(this);
                    t.addClass("hasCloseClick");
                    t.click(function () {
                        $f(p.relmovie).unload();
                        popinMovieHash[p.relmovie].isVisible = false;
                        
                        $(".popinMovie").css({ 
                            display: "none"
                        });
                        
                        $(".colPlayerContainer:not(.screenshot)").flowplayer().each(function() {
                            this.resume();
                        });
                    });
                });
            });
            
            $(that).siblings("a.openMovie").click(function (e) {
                e.preventDefault();
                $(that).trigger("click");
            });
            
            //if (that.firstChild && that.firstChild.offsetHeight) {
                $(that).prepend("<div class=\"op0 flashLinkOvly\" style=\"width: 166px; height: 94px;position: absolute;\"></div>");
            //}
        }
    });
    
    /*$(document).click(function () {
        $(".popinPlayerContainer").each(function () {
            $(this.parnetNode).find(".closePopin").trigger("click");
        });
    });*/
    
});

function openNewMovie (moviePath) {

    $f(MAXI_PLAYER_CONTAINER_ID).unload();
    
    popinMovieHash[MAXI_PLAYER_CONTAINER_ID] = {};
    
    initPlayer(MAXI_PLAYER_CONTAINER_ID, moviePath, MAXI_PLAYER, 100);
    
    $f(MAXI_PLAYER_CONTAINER_ID).load();
};


/**
 *  uses flowplayer to play movie
 *  id: html container
 *  path: full path to moviefile on server
 *  type: MINI_PLAYER, MIDI_PLAYER or MAXI_PLAYER
 *  time: where movie starts to play in seconds
 */

var moveCloseTimeout; 

function initPlayer(id, path, type, time, pmid) {
	popinMovieHash[id].isVisible = true;
	popinMovieHash[id].seekTimer = null;
	popinMovieHash[id].bufferCounter = 0;
	popinMovieHash[id].doOnce = true;
	
	
	//alert(id + "\n" + path + "\n" + type + "\n" + time);
	
	if (type === MIDI_PLAYER && pmid) {
	    $("#" + pmid).css({
	        display : "block"
	    });
	}

	// tries to seek to given time, doesn't stop until seeked.
    // should actually work with a simple this.seek(time) on event onStart but doesn't!
	popinMovieHash[id].seekOnPlaybackStart = function(obj) {
		var localObj = obj;

	    // the iterative function retrying until stopped by onSeek
		seekOnPlaybackStart_helper = function() {

			// try the seek
			localObj.seek(time);
   		}

		// retry until seek is triggered
        popinMovieHash[id].seekTimer = setInterval( seekOnPlaybackStart_helper, 100 );
	}
	
	// calls flowplayer, see: http://www.flowplayer.org/documentation/index.html
	$f(id, { src: FLOWPLAYER_PATH, wmode: 'transparent' }, {
	    key: FLOWPLAYER_KEY,

	    clip: {    // configure clip to use "rtmp" plugin for providing video data 
	        url: path,
	        provider: type == MINI_PLAYER ? 'http' : 'rtmp',
	        autoPlay: true,
	        //autoPlay: false,
	        fadeInSpeed: 2000,
	        onBufferEmpty: type == MINI_PLAYER ? null : function() {
	            if (popinMovieHash[id].bufferCounter == 1) {
	                this.play(path + '_200');
	            }
	            popinMovieHash[id].bufferCounter++;
	        },
	        onBegin: function() {
	            // do just once
	            if (popinMovieHash[id].doOnce) {

	                // start seeking
	                if (popinMovieHash[id].seekTimer == null) {
	                    popinMovieHash[id].seekOnPlaybackStart(this);
	                }

	                // do this as well just once
	                if (type == MINI_PLAYER) {
	                    this.mute();
	                } else { 
	                    this.unmute();
	                }

	                popinMovieHash[id].doOnce = false;
	            }
	        },
	        onFinish : function () {
	            if (type == MIDI_PLAYER) {
	                moveCloseTimeout = setTimeout(function () {
	                    $(".popinMovie:visible .closePopin").trigger("click");
    	                
	                    $("#" + MAXI_PLAYER_CONTAINER_ID).flowplayer().each(function () {
	                        this.resume();
	                    });
	                }, 10000);
	            }
	        },
	        onStart : function() {
	            if (type == MAXI_PLAYER) {
	                resetCounter();
	                initCounter();
	            }
	            clearTimeout(moveCloseTimeout);
	        },
	        onPause: function() {
	            if (type == MAXI_PLAYER) {
	                resetCounter();
	            }

	            // save traffic cost and trees :)
	            stopBuffering();
	        },
	        onResume: function() {
	            if (type == MAXI_PLAYER) {
	                resetCounter();
	                initCounter();
	            }

	            // resume buffering again after saving some trees
	            startBuffering();
	        },
	        onBeforeFinish: function() {
	            var firstChapter = $('li.timestamp:first');
	            setChapter(firstChapter);

	            if (type == MAXI_PLAYER || type == MIDI_PLAYER) {
	                return true;
	            }
	            else {
	                // start playing from the beginning if end reached
	                return false;
	            }
	        },
	        onSeek: function() {
	            // kill the seeker
	            clearInterval(popinMovieHash[id].seekTimer);
	            popinMovieHash[id].seekTimer = null;

	            // set chapter in left menu
	            if (type == MAXI_PLAYER) {
	                resetCounter();

	                // find right chapter in menu
	                var newChapter = $('li.timestamp').filter(function(index) {
	                    if ($(this).getNextChapter() == null) return true; // if last chapter
	                    else return ($f(MAXI_PLAYER_CONTAINER_ID).getTime() < $(this).getNextChapter().getTimestamp());
	                }).filter(':first');

	                setChapter(newChapter);
	                initCounter(type);
	            }
	        }
	    },

	    // resets state of player (useful if user re-opens a popinMovie)
	    onUnload: function() {
	        if (type == MIDI_PLAYER) {
	            popinMovieHash[id].doOnce = true;
	            popinMovieHash[id].seekTimer = null;
	            
	            $("#" + MAXI_PLAYER_CONTAINER_ID).flowplayer().each(function () {
	                this.resume();
	            });
	        }
	    },
	    onBeforeUnload : function () {
	        if (id === "byggmaxPlayerContainer") {
	            $("#" + MAXI_PLAYER_CONTAINER_ID).flowplayer().each(function () {
                    this.pause();
                });
	            return false;
	        }
	    },

	    // streaming plugins are configured under the plugins node  
	    plugins: {

	        // here is our rtpm plugin configuration 
	        rtmp: {
	            url: FLOWPLAYER_RTMP_PATH,
	            netConnectionUrl: STREAMING_SERVER    // netConnectionUrl defines where the streams are found 
	        },

	        // customize controls
	        controls: type == MINI_PLAYER ? null : {
	            url: FLOWPLAYER_CONTROLS_PATH,    // location of the plugin 

	            // display properties (size, location and opacity)  
	            bottom: 0,
	            left: 0,

	            // styling properties (can be applied to all plugins)
	            backgroundColor: '#000000;',
	            backgroundGradient: 'low',
	            timeColor: '#cf0f0f', 		// value for the font color in the time field. this is the running time.
	            durationColor: '#ffffff', 	// value for the font color in the time field that specifies the total duration of the clip or "total time".
	            progressColor: '#cf0f0f', 	// the color of the progress bar. this is the bar in the timeline from zero time to the point where playback is at given time.
	            progressGradient: 'low', 	// gradient setting for the progress bar. see below how this can be set.
	            bufferColor: '#111111', 		// the color of the buffer. buffer is the bar that indicates how much video data has been read into player's memory.
	            bufferGradient: 'none', 		// gradient setting for the buffer. see below how this can be set.
	            sliderColor: '#000000', 		// background color for the timeline before buffer bar fulfills it. the same background color is also used in volume slider.
	            sliderGradient: 'none', 		// gradient setting for the sliders. see below how this can be set.
	            buttonColor: '#111111', 		// color of the player buttons: stop, play, pause, fullscreen.
	            buttonOverColor: '#333333', 	// button color when mouse is positioned on top of them

	            // which buttons are visible and which not ? 
	            play: true,
	            volume: true,
	            mute: true,
	            time: true,
	            stop: false,
	            playlist: false,
	            fullscreen: true,

	            // fast switch 
	            all: false,

	            // scrubber is a well known nickname to the timeline/playhead combination 
	            scrubber: true
	        }
	    },
	    play: {
	        opacity: type == MINI_PLAYER ? 0 : 0.8
	        //			label: 'Peace!',
	    }
	});
}


/**
 * keep track of current chapter and make it visible if necessary
 */
function setChapter(obj) {

	// set current chapter
	$(".current").removeClass("current");
	obj.addClass("current");

	// open part if closed
	if (!$(obj).parent().hasClass("open")) {
		$(obj).parent().slideToggle("fast").addClass("open");
	}
}


/**
 * jump to specified time and start playback if paused
 */
function playChapter(time) {

	// jump to specified time
	$f(MAXI_PLAYER_CONTAINER_ID).seek(time);

	// start playback if paused
	if( $f(MAXI_PLAYER_CONTAINER_ID).isPaused() ) {
		$f(MAXI_PLAYER_CONTAINER_ID).play();
	}
}



/**
 * starts movieProgressCounter if type == MAXI_PLAYER
 */
function initCounter() {
	if (movieTimer == null) {
		movieProgressCounter();
	}
}


/**
 * reset movieProgressCounter timer
 */
function resetCounter() {
	clearTimeout(movieTimer);
	movieTimer = null;
}



/**
 * keeps track on movie progress and updates movie navigation (is only called when type == MAXI_PLAYER)
 */
function movieProgressCounter() {
	movieCounter++;
//	$(".aboutSection").html(movieCounter); //debug purpose

	var afterCurrent = $('li.current').getNextChapter();
	
	// check if movie started a new chapter
	if(afterCurrent != null && $f(MAXI_PLAYER_CONTAINER_ID).getTime() > afterCurrent.getTimestamp()) {
		setChapter(afterCurrent);
	}

	// call method recursively every 2 seconds
	movieTimer = setTimeout(movieProgressCounter, 2000);
}


/**
 * retrieve next chapter after this chapter, return null if current chapter is last one.
 */
$.fn.getNextChapter = function(){
	var nextChapter = this.next();

	// if chapter is in next part
	if (nextChapter.length < 1) {
		nextChapter = this.parent().nextAll('ul:first').children('li.timestamp:first');
	}

	// if there are no chapters or parts left
	if (nextChapter.length < 1) {
		nextChapter = null;
		clearTimeout(movieTimer);
	}

	return nextChapter;
};


/**
 * retrieves timestamp assuming correct syntax: <li class="timestamp ts_xx">
 */
$.fn.getTimestamp = function() {
/*	var myTimestamp = jQuery.grep(this.attr('class').split(' '), function(n, i){
		return (n != 'timestamp' && n != 'selected' && n != 'current');
	}).toString().split('ts_').join('');
*/
	var myTimestamp = this.find("input[name='timestamp']").val();

	return myTimestamp;
}
//$('li.timestamp').getTimestamp();
