var afns_video_data = {};
var afns_video_category = "video_undefined"; // this needs to be set by the calling environment
var afns_video_autoplay = false;
var afns_video_group = "onn_player";
var player = null;

function add_overlay(clickthrough_url, overlay_image, clicktrack_list) {
    if(!clickthrough_url) {
        clickthrough_url = "#";
    }
    if(!overlay_image) {
	    // if overlay image is not specified, we're doing a video advertisement
        overlay_image = "http://media.theonion.com/img/icons/blank.gif";
        var target = "_blank";
	    var control_height = 26;
    }
    else {
	    var target = "";
	    var control_height = 0;
    }
    var width = $("#player_container").width();
    var height = ($("#player_container").height()-control_height);
    var clicktrack_html = '';
    if(clicktrack_list) { // expand list into literals so that when out of this scope function works
    	clicktrack_html = 'onclick="afns_video_track([';
    	for(var i = 0; i < clicktrack_list.length; i ++) {
    	    if(i > 0) { clicktrack_html = clicktrack_html + ","; }
    	    clicktrack_html = clicktrack_html + "'" + clicktrack_list[i] + "'";
    	}
    	clicktrack_html = clicktrack_html + '])"';
    }
    var overlay = '<a class="video_overlay" style="text-decoration: none; top: 0px; left: 0px; position: absolute; display: block; width: '+width+'px; height: '+height+'px;" '+clicktrack_html+' href="'+clickthrough_url+'" target="'+target+'"><img class="video_overlay_image" src="'+overlay_image+'" width="'+width+'" height="'+height+'" style="position: absolute; top: 0px; left: 0px; border: none;" /></a>';
    $("#player_wrapper").append(overlay);
    if(!target) {
        var imgoverlay = '<img class="video_overlay_image" src="http://media.theonion.com/img/buttons/video_button_480.png" style="position: absolute; top: 0px; left: 0px;" width="'+width+'" height="'+height+'" />';
	    $(".video_overlay").append(imgoverlay);
    }
}

function remove_overlay() {
    $(".video_overlay").remove();
    $(".video_overlay_skip").remove();
    $(".video_overlay_image").remove();
}

function display_poster() {
    add_overlay("javascript:initialize_ads(preroll, afns_video_group);", afns_video_data.thumbnail);
}

function ad_countdown_update(clip, cue_time, resume_time) {
    clip.onCuepoint(cue_time, function() { $(".video_overlay_countdown").html("Content resumes in " + resume_time); } );
}

function ad_countdown() {
    var overlay = '<p class="video_overlay_countdown" style="filter:alpha(opacity=50); opacity: 0.5; background-color: #333; color: #ccc; text-decoration: none; top: 0px; right: 0px; position: absolute; display: block; padding: 3px;"></p>';
    $("#player_wrapper").append(overlay);
    // set cuepoints for updating the overlay content with
    var clip = player.getClip(0);
    clip.onCuepoint(1000, function() {
	    var clip = player.getClip(0);
	    var duration = parseInt(clip.fullDuration);
	    // only count down to a maximum of 15 seconds out because skip this ad appears at 16000
	    for(var i = 0; i < duration - 1 && i < 16; i ++) {
		ad_countdown_update(clip, i*1000, duration-i);
	    }
	    clip.onCuepoint(i*1000, function() { $(".video_overlay_countdown").remove(); });
	});
}

function skip_this_ad_overlay() {
    if (typeof(afns_trackevent) == "undefined") {
	_gaq.push(['_trackEvent', 'event_migration_error', 'onion/flowplayer_videocontroller', 'skip_this_ad_overlay', null, false])
    }
    else {
	afns_trackevent({'category': afns_video_category,'action': 'ad_skip_overlay_shown'});
    }
    var overlay = '<a class="video_overlay_skip" style="background-color: #333; color: white; text-decoration: none; top: 0px; right: 0px; position: absolute; display: block; padding: 3px;" href="javascript:skip_ad();">Skip this ad</a>';
    $("#player_wrapper").append(overlay);
}

function afns_video_track(url_list) {
    if(typeof(url_list) == "string") { // backwards compat
        $(".video_overlay").append('<img width="1" height="1" src="'+url_list+'" />');
    }
    else {
        for(var i = 0; i < url_list.length; i ++) {
            $(".video_overlay").append('<img width="1" height="1" src="'+url_list[i]+'" />');
        }
    }
}

function preroll() {
    remove_overlay();
    player.pause();
    if(afns_video_ad.vast) {
    	player.play(afns_video_ad.vast.mediafile);
    	add_overlay(afns_video_ad.vast.clickthrough, "", afns_video_ad.vast.tracking.click);

    	// set up tracking events for vast
    	var duration = afns_video_ad.vast.duration * 1000;
    	afns_video_track(afns_video_ad.vast.tracking.start);
    	afns_video_track(afns_video_ad.vast.tracking.impression);
    	player.getClip(0).onCuepoint(duration / 4, function() { afns_video_track(afns_video_ad.vast.tracking.firstQuartile); });
    	player.getClip(0).onCuepoint(duration / 2, function() { afns_video_track(afns_video_ad.vast.tracking.midpoint); });
    	player.getClip(0).onCuepoint(3 * duration / 4, function() { afns_video_track(afns_video_ad.vast.tracking.thirdQuartile); });
    	player.getClip(0).onCuepoint(duration - 600, function() { afns_video_track(afns_video_ad.vast.tracking.complete); });
    	player.onMute(function() { afns_video_track(afns_video_ad.vast.tracking.mute); });
    	player.onUnmute(function() { afns_video_track(afns_video_ad.vast.tracking.unmute); });
    	player.getClip(0).onPause(function() { afns_video_track(afns_video_ad.vast.tracking.pause); });
    	player.getClip(0).onResume(function() { afns_video_track(afns_video_ad.vast.tracking.resume); });
    	player.onFullscreen(function() { afns_video_track(afns_video_ad.vast.tracking.fullscreen); });
    	player.onFullscreenExit(function() { afns_video_track(afns_video_ad.vast.tracking.close); });

    	if (typeof(afns_trackevent) == "undefined") {
    	    _gaq.push(['_trackEvent', 'event_migration_error', 'onion/flowplayer_videocontroller', 'preroll_vast', null, false])
    	}
    	else {
    	    afns_trackevent({'category': afns_video_category,
    			     'action': 'vast_ad_play',
    			     'label': afns_video_id+"-"+afns_video_data.slug});
    	}

    	player.onBeforeSeek(function() { return false; });
    }
    else if(afns_video_ad.preroll) {
        player.play(afns_video_ad.preroll);
	    ad_countdown();
	    player.getClip(0).onCuepoint(16000, skip_this_ad_overlay);
        add_overlay(afns_video_ad.preroll_client_url);
	    player.onBeforeSeek(function() { return false; });
    	if(afns_video_ad.preroll_client_pixel) {
    	    $(".video_overlay").append('<img src="'+afns_video_ad.preroll_client_pixel+'" />');
    	}
    	if (typeof(afns_trackevent) == "undefined") {
    	    _gaq.push(['_trackEvent', 'event_migration_error', 'onion/flowplayer_videocontroller', 'preroll', null, false])
    	}
    	else {
    	    afns_trackevent({'category': afns_video_category,
    			     'action': 'preroll_play',
    			     'label': afns_video_id+"-"+afns_video_data.slug});
    	}	
    }
    else {
        next_state();
    }
}

function main_video() {
    remove_overlay();
    try {
        hide_wallpaper();
    } catch(err) {}
    player.pause();
    player.onBeforeSeek(function() { });
    player.play(afns_video_data.video_url);
    if(afns_video_ad.postroll) {
	    player.getClip(0).onCuepoint(afns_video_data.postroll_cuepoint, postroll);
    }
    if (typeof(afns_trackevent) == "undefined") {
	    _gaq.push(['_trackEvent', 'event_migration_error', 'onion/flowplayer_videocontroller', 'main_video', null, false])
    }
    else {
	    afns_trackevent({'category': afns_video_category,
			 'action': 'video_play',
			 'label': afns_video_id+"-"+afns_video_data.slug});
    }
}

function postroll() {
    current_state = postroll; // set current state to postroll because if we enter from cuepoint player still thinks it's main video
    remove_overlay();
    player.pause();
    if(afns_video_ad.postroll) {
        player.play(afns_video_ad.postroll);
        add_overlay(afns_video_ad.postroll_client_url);
    	player.onBeforeSeek(function() { return false; });
    	if(afns_video_ad.postroll_client_pixel) {
    	    $(".video_overlay").append('<img src="'+afns_video_ad.postroll_client_pixel+'" />');
    	}
    	if (typeof(afns_trackevent) == "undefined") {
    	    _gaq.push(['_trackEvent', 'event_migration_error', 'onion/flowplayer_videocontroller', 'main_video', null, false])
    	}
    	else {
    	    afns_trackevent({'category': afns_video_category,
    			     'action': 'postrol_play',
    			     'label': afns_video_id+"-"+afns_video_data.slug});
    	}
    }
    else {
	    video_complete(); // not next_state because we encode bookend for delivery with main video
    }
}

function bookend() {
    remove_overlay();
    player.pause();
    player.onBeforeSeek(function() { });
    if(afns_video_data.bookend_url) {
	    player.play(afns_video_data.bookend_url);
	    if (typeof(afns_trackevent) == "undefined") {
    	    _gaq.push(['_trackEvent', 'event_migration_error', 'onion/flowplayer_videocontroller', 'bookend', null, false])
    	}
    	else {
    	    afns_trackevent({'category': afns_video_category,
    			     'action': 'bookend_play',
    			     'label': afns_video_id+"-"+afns_video_data.slug});
    	}
    }
    else {
	next_state();
    }
}

function video_complete() {
    // post video play logic should start countdown to next video or initialize first vid
    // for now just cause play to go back to initial vid
    player.pause();
    //any local recirc?
    current_state = preroll;
    try {
        video_recirc();
    } catch(err) {
        display_poster();
    }
}

var state_list = [preroll, main_video, postroll, bookend, video_complete];
var current_state = preroll;

function skip_ad() {
    if (typeof(afns_trackevent) == "undefined") {
	_gaq.push(['_trackEvent', 'event_migration_error', 'onion/flowplayer_videocontroller', 'skip_ad', null, false])
    }
    else {
	afns_trackevent({'category': afns_video_category,
			 'action': 'ad_skip_overlay_clicked',
			 'label': afns_video_id+"-"+afns_video_data.slug});
    }	
    next_state();
}


function next_state() {
    for(var i = 0; i < state_list.length - 1; i ++) {
    	if(state_list[i] == current_state) {
    	    current_state = state_list[i+1];
    	    current_state();
    	    break;
    	}
    }
}

function html5_video(video_url) {
    var width = $("#player_container").width();
    var height = $("#player_container").height();
    //hmm ipad height hack here for time being
    if(height < width/2) height = width * 0.65;
    var html5tag;
    var nextVideo;
    

    html5tag = '<video id="videoPlayer" controls height="'+height+'" width="'+width+'" src="'+video_url+'" />';
    $("#player_container").html(html5tag);
    $("#videoPlayer").bind("play", 
        function(e){
            afns_trackevent({'category': afns_video_category,
    			     'action': 'html5_player_play',
    			     'label': afns_video_id+"-"+afns_video_data.slug});
        }
    );
    
}

function initialize_player(callback) {
    if (/iPad|android|iphone|ipod/i.test(navigator.userAgent)) {
        //ipad, android, iphone, ipod only case right now
        $.getJSON("/ajax/onn/embed/"+afns_video_id+".json", function(data) {
	      html5_video(data.video_url);
	      afns_video_data = data;
	      afns_trackevent({'category': afns_video_category,
  			     'action': 'html5_player_init',
  			     'label': afns_video_id+"-"+afns_video_data.slug});
        });
        return true;
    }
    $f("player_container",
       {src: "http://media.theonion.com/flash/video/flowplayer/flowplayer.swf",
        wmode: "opaque",
        cachebusting: false},
        {
            play: {opacity: 0},
	    clip: {scaling: 'fit',
		    onBeforeFinish: function() { next_state(); }},
            canvas: {
                    backgroundGradient: 'none',
                    backgroundColor: '#000000'
                    },
            plugins: {
                controls: {
                    autoHide: true,
                    hideDelay: 2000,
                    backgroundGradient: 'none',
                    backgroundColor: '#1e1f1e',
                    volumeSliderGradient: 'none',
                    progressColor: '#6b0004',
                    bufferGradient: 'none',
                    sliderBorder: '1px solid rgba(128, 128, 128, 0.7)',
                    bufferColor: '#000000',
                    volumeSliderColor: '#000000',
                    progressGradient: 'none',
                    volumeColor: '#640206',
                    durationColor: '#525252',
                    buttonColor: '#9b9d9b',
                    tooltipColor: '#000000',
                    volumeBorder: '1px solid rgba(128, 128, 128, 0.7)',
                    timeColor: '#9e9e9e',
                    borderRadius: '0px',
                    timeBorder: '0px solid rgba(0, 0, 0, 0.3)',
                    timeSeparator: ' ',
                    sliderColor: '#200909',
                    timeBgColor: '#1c1c1c',
                    sliderGradient: 'none',
                    buttonOverColor: '#ffffff',
                    tooltipTextColor: '#ffffff',
                    height: 30,
                    opacity: 1.0,
                    timeFontSize: 10
                }
            }
        });
        
    $f().load(function() {
        player = $f();
        $.getJSON("/ajax/onn/embed/"+afns_video_id+".json", function(data) {
            afns_video_data = data;
            //measured in 10th's of seconds
            if (typeof afns_pageview_timestamp != "undefined") {
                var duration = parseInt((new Date().getTime() - afns_pageview_timestamp) / 100);
                //track the time it took to get here from PageView
                if (duration > 40) {
                    afns_trackevent({'category': afns_video_category,
				     'action': 'video_load_time_gt30s',
				     'label': afns_video_id+"-"+afns_video_data.slug, 'value': duration});
                }
                else {
                    afns_trackevent({'category': afns_video_category,
				     'action': 'video_load_time',
				     'label': afns_video_id+"-"+afns_video_data.slug, 'value': duration});
		}
            }
            if(typeof(afns_video_autoplay) === "undefined") {
                afns_video_autoplay = false;
            }
            if(!afns_video_autoplay) {
                display_poster();
            }
            else {
                if(afns_video_ad) {
                    preroll();
                }
                else {
                    initialize_ads(preroll, afns_video_group);
                }
            }
            if(callback) {
		callback();
	    }
	    });
	});
    return $f;
}

function sponsoredplayer(dom_id, url, poster, autoplay, ga_event) {
    if(!poster || poster == "") {
        poster = "http://o.onionstatic.com/img/icons/blank.gif";
    }
    flowplayer(
        dom_id,
        "http://media.theonion.com/flash/video/flowplayer/flowplayer.swf",
        {
        wmode: 'opaque',
        cachebusting: false,
        clip: {
            autoBuffering: true,
            onCuepoint: [[500], function(clip, point) {
                if(ga_event) {
                    ev = ga_event.split(",");
                    _gaq.push(['_trackEvent', ev[0], ev[1], ev[2]]);
                }
            }],
            onStart: function() {
                this.mute();
            }
        },
        playlist: [
            {url: poster},
            {url: url, autoPlay: autoplay}
        ],
        canvas: {
            backgroundGradient: 'none',
            backgroundColor: '#000000'
        },
        plugins: {
            controls: {
                hideDelay: 2000
            }
        }
    });
}

