﻿var _global_flash = {};
var JSON_Programme = {};

function delegate( target, method ) {
	if(!method || !target) return;
	var parameters = [];
	for(var i = 2; i <arguments.length; i++) {
		parameters.push(arguments[i]);
	}
	var proxy = function() {
		var actualParameters = [];
		for(var i = 0; i <arguments.length; i++) {
			actualParameters.push(arguments[i]);
		}
		return method.apply(target, actualParameters.concat(parameters));
	};
	return proxy;
}

function trace(message) { $("#testoutput").append("<a>"+message+"</a><br/>");}
function clearTraces() {$("#testoutput").html("");}
function S4(){return (((1+Math.random())*0x10000)|0).toString(16).substring(1);}
function guid(){return String((this.S4()+this.S4()+"_"+this.S4()+"_"+this.S4()+"_"+this.S4()+"_"+this.S4()+this.S4()+this.S4())).toUpperCase();}
function swfReady(id) {}

VideoEvent = {};
VideoEvent.AUTO_REWOUND = "autoRewound";
VideoEvent.BUFFERING_STATE_ENTERED = "bufferingStateEntered";
VideoEvent.CLOSE = "close";
VideoEvent.COMPLETE = "complete";
VideoEvent.FAST_FORWARD = "fastForward";
VideoEvent.PAUSED_STATE_ENTERED = "pausedStateEntered";
VideoEvent.PLAYHEAD_UPDATE = "playheadUpdate";
VideoEvent.PLAYING_STATE_ENTERED = "playingStateEntered";
VideoEvent.READY = "ready";
VideoEvent.REWIND = "rewind";
VideoEvent.SCRUB_FINISH = "scrubFinish";
VideoEvent.SCRUB_START = "scrubStart";
VideoEvent.SEEKED = "seeked";
VideoEvent.SKIN_LOADED = "skinLoaded";
VideoEvent.STATE_CHANGE = "stateChange";
VideoEvent.STOPPED_STATE_ENTERED = "stoppedStateEntered";

function CustomEvent() {}
CustomEvent.prototype.type = "";
CustomEvent.prototype.id = "";
CustomEvent.prototype.value = "";

function ListenerProxy(type_in, callback_in, id_in) {
	this.type = type_in;
	this.callback = callback_in;
	if (id_in == undefined) {
		this.id = "listenerProxy_" + type_in + "_" + guid();
	} else {
		this.id = id_in;
	}
};

ListenerProxy.prototype.dispatchProxy = function(e) {
	this.callback(e, this);
}

function buildOpenChannel(ocParams) {
	if (!swfobject.hasFlashPlayerVersion("9")) return;
	_global_flash.width = ocParams.width;
	_global_flash.height = ocParams.height;
	_global_flash.controls = ocParams.showControls;
	_global_flash.isIV = ocParams.isIntelligentVideo;
	_global_flash.IVSwf = {};
	_global_flash.userID = ocParams.userID;
	_global_flash.trackerURI = ocParams.trackerURI;
	_global_flash.trackerSource = ocParams.trackerSource;
	_global_flash.programmeID = ocParams.programmeID;
	_global_flash.seekBarColor = ocParams.seekBarColor;
	_global_flash.timerColor = ocParams.timerColor;
	_global_flash.showMCLogo = ocParams.showMCLogo;
	if (ocParams.forceWidth) {
		_global_flash.forceWidth =  "true";
		_global_flash.forceWidthW = ocParams.width;
		_global_flash.forceWidthH = ocParams.height;
	} else {
		_global_flash.forceWidth = "false";
		_global_flash.forceWidthW = "x";
		_global_flash.forceWidthH = "x";
	}

	if (_global_flash.controls) _global_flash.height = _global_flash.height + 48;
	
	$.ajax({
		url:'http://admin.multichanneltv.com/phptojson.php',
		data:'pid='+ocParams.programmeID,
		async:false,
		dataType:"jsonp"
	});
}

function customTracker(str) {
		jsAPI.callCoreMethod("doTracking","custom_tracking", str);
}

function onReceiveJSON(json) {
	JSON_Programme = json;
	JSON_Programme.user_id = _global_flash.userID;
	JSON_Programme.tracker_source = _global_flash.trackerSource;
	JSON_Programme.tracker_uri = _global_flash.trackerURI;
	onReadyDelegate = delegate(this, onCoreReady);
	jsAPI = new JavascriptAPI("openchannelcore", "http://openchannel.multichanneltv.com/core/modules/vid_controls_default.swf", onReadyDelegate, null, _global_flash.width, _global_flash.height, null);
}

// Usage objects (Chapters, Slides, Intelligent Video)
Chapters = function() {
	this.chapters = {};
	this.currentChapter = null;
	for (i in JSON_Programme.chapters) {
		this.chapters[i] = JSON_Programme.chapters[i];
	}
}

function onChapterChange(eventObject) {
	if(eventObject == null) {/*	trace("event handled with no event object"); */	return;	}
	for (i in jsChapters.chapters) {
		i = parseInt(i);
		if (Math.floor(eventObject.playheadTime) >= Math.floor(jsChapters.chapters[i].start_point)) {
			if (jsChapters.chapters[i+1]) {
				if (Math.floor(eventObject.playheadTime) < Math.floor(jsChapters.chapters[i+1].start_point)) {
					if (jsChapters.currentChapter != i) {
						jsChapters.currentChapter = i;
						jsAPI.callCoreMethod("doTracking","chapter_loaded", jsChapters.chapters[i].chapter_title);
					}
					break;
				}
			} else {
					if (jsChapters.currentChapter != i) {
						jsChapters.currentChapter = i;
						jsAPI.callCoreMethod("doTracking","chapter_loaded", jsChapters.chapters[i].chapter_title);
					}
			}
		}
	}
}

Slides = function() {
	this.slides = [];
	this.currentSlide = false;
	for (i in JSON_Programme.slides) {
		this.slides[i] = JSON_Programme.slides[i];
	}
}

function onSlideChange(eventObject) {
	if(eventObject == null) { /*trace("event handled with no event object"); */return; }
	if (jsSlides.currentSlide) {
		if (Math.floor(eventObject.playheadTime) >= Math.floor(jsSlides.slides[jsSlides.currentSlide].end_point) || 
			  Math.floor(eventObject.playheadTime) < Math.floor(jsSlides.slides[jsSlides.currentSlide].start_point)) {
			$("#openchannel-slides").html("");
			jsSlides.currentSlide = false;
		}
	}
	for (i in jsSlides.slides) {
		if (Math.floor(eventObject.playheadTime) >= Math.floor(jsSlides.slides[i].start_point) && 
				Math.floor(eventObject.playheadTime) < Math.floor(jsSlides.slides[i].end_point)) {
				if (jsSlides.currentSlide === i) continue;
				$("#openchannel-slides").html('<img src="' + jsSlides.slides[i].slide_file + '" />');
				jsSlides.currentSlide = i;
			  //var myObj = {"type":"customTest","id":i,"value":{"TimeDate"	: "2009-09-11 16:56:10","ViewerID"	: "187"}}	jsAPI.callMethod("eventDispatchProxy",myObj);
		}
	}
}

IntelligentVideos = function() {
	this.iv = [];
	this.currentVideo = false;
	for (i in JSON_Programme.intelligent_video) {
		this.iv[i] = JSON_Programme.intelligent_video[i];
	}
}

function loadIVSwf() {
	var t = new Date();
	var flashvars = {child_height: _global_flash.height, child_width:_global_flash.width, source_folder:JSON_Programme.swf_location, programme_id: _global_flash.programmeID, user_id:_global_flash.userID};
	var params = {menu: "false",scale: "noScale",allowFullscreen: "true",allowScriptAccess: "always",bgcolor: "#dddddd",wmode:"transparent", align:"TL", salign:"TL"}; 
	var attributes = {};
	var ui_width = _global_flash.width;
	var ui_height = _global_flash.controls ? _global_flash.height-48 : _global_flash.height;
	swfobject.embedSWF("http://openchannel.multichanneltv.com/core/modules/ui_loader.swf?__c="+t.getTime(), "iv", ui_width, ui_height, "9.0.0", "expressInstall.swf", flashvars, params, attributes, ivLoaded);
}

function ivLoaded(e) {
	_global_flash.IVSwf = e.ref;
}

function IVSwfLoaded() {
	var movie = _global_flash.IVSwf;
	movie.loadIVObject(jsIV.iv);
}

function onIntelligentVideoChange(eventObject) {
	if(eventObject == null) { return; }
	if (jsIV.currentVideo) {
		if (Math.floor(eventObject.playheadTime) >= Math.floor(jsIV.iv[jsIV.currentVideo].end_point) || 
			  Math.floor(eventObject.playheadTime) < Math.floor(jsIV.iv[jsIV.currentVideo].start_point)) {
			_global_flash.IVSwf.removeIV();
			jsIV.currentVideo = false;
		}
	}
	for (i in jsIV.iv) {
		if (Math.floor(eventObject.playheadTime) >= Math.floor(jsIV.iv[i].start_point) && 
				Math.floor(eventObject.playheadTime) < Math.floor(jsIV.iv[i].end_point)) {
				if (jsIV.currentVideo === i) continue;
				if (jsIV.iv[i].action == "pause") {
					jsAPI.callMethod("pause");
				} else if (jsIV.iv[i].action == "stop") {
					jsAPI.callMethod("pause");
					jsAPI.callCoreMethod("hideControls");
				}
				_global_flash.IVSwf.loadSwf(jsIV.iv[i].iv_id);
				jsIV.currentVideo = i;
			}
	}
}

function onCoreReady() {
	jsChapters = new Chapters();
	jsSlides = new Slides();
	if (_global_flash.isIV) jsIV = new IntelligentVideos();
	if (_global_flash.isIV) loadIVSwf();
	jsAPI.setProperty("source", JSON_Programme["smil"]);
	jsAPI.callMethod("addData", JSON.stringify(JSON_Programme));
	
	
	jsAPI.addEventListener(VideoEvent.PLAYHEAD_UPDATE,  delegate(this, onChapterChange));
	jsAPI.addEventListener(VideoEvent.PLAYHEAD_UPDATE, delegate(this, onSlideChange));
	if (_global_flash.isIV) jsAPI.addEventListener(VideoEvent.PLAYHEAD_UPDATE, delegate(this, onIntelligentVideoChange));
}

function JSRestartVideo() {
	jsAPI.callCoreMethod("restartVideo");
}