/**
 * RIM Video Player JS API
 * @author ituuri, jbilsten
 */

var VideoPlayer = new Class({
	initialize: function(options) {
		//this.uri = new URI(window.location.protocol + "//" + window.location.host + "/" + window.location.pathname);
		//console.log("uri: " + document.location.href);
		//options = this.getHeightAndWidth(options);
		
		options.isOffsite  = getQueryVariable('l'); //If it doesn't exist it will return 1/true meaning we're on blackberry.com or sharing domains
		options.videoId = getQueryVariable('i', Number(window.local));
		
		this.minWidth = 418;
		this.maxWidth = 900;
		this.ratio = options.width/options.height;
		//console.log("width: " + options.width);
		//console.log("height: " + options.height);

		//Assign height/width to video player
		this.width = (options.width != null && options.width > this.minWidth) ? options.width : this.minWidth;
		this.height = (options.height != null && this.width > this.minWidth) ? options.height : (this.width * options.height/options.width);

		this.container = $$('div.rimVideoPlayer')[0];

		//If the player is offSite, share links need to pull from querystring url variable
		this.isOffSite = (options.isOffSite != null) ? options.isOffSite : 0;

		this.videoId = (options.videoId != null) ? options.videoId : 1;
		this.galleryXmlPath = (options.galleryXmlPath != null) ? options.galleryXmlPath : 'videoGallery.xml';
		this.videoFile = (options.videoFile != null) ? options.videoFile : '/assets/flash/video.swf';

		this.url = options.url;
		this.embedUrl = 'http://'+document.location.host + document.location.pathname;
		this.shareUrl = null;

		this.menu = new Menu({
			videoPlayer: this
		});
		this.controlbar = new ControlBar({
			menu: this.menu,
			videoPlayer: this
		});
		this.video = new Video({
			height: (this.height - this.controlbar.height),
			width: this.width
		});

		this.updateShareUrl();

		//Resize VideoPlayer
		this.container.style.width = this.width;
		this.container.style.height = this.height;

		this.writeFlash('BB_Movie');
		//this.controlbar.reset();
	},
	getHeightAndWidth: function(p_options) {
		//p_options.height = 	this.uri.getData("height");
		//p_options.width =	this.uri.getData("width");
		
		return p_options;
	},
	updateShareUrl: function() {
		if (this.url == 1) { //'url' querystring variable doesn't exist -> on a blackberry site and we have permissions to grab the parent frame location
			this.shareUrl = 'http://'+window.parent.document.location.host+window.parent.document.location.pathname+'?i='+this.videoId;
		} else if(this.url != null) { //'url' exists so we use it
			this.shareUrl = this.url;
		} else { //No information, break gracefully
			this.shareUrl = this.embedUrl;
		}
		if(this.menu != null)
			this.menu.updateEmbed();
	},
	setVideoId: function(id) {
		this.videoId = id;
	},
	playVideo: function(id) {
		//console.log('VideoPlayer.playVideo: ' + id);
		this.video.isLoading = true;
		this.videoId = id;
		this.updateShareUrl();
		this.controlbar.reset();
		sendCmdToFlash('vp_newvideo',id);
		this.controlbar.play(true);
		//this.controlbar.togglePlayPause();
	},
	writeFlash: function(flashId) {
		if(typeof(SWFObject) == 'function' && typeof(SWFObject.prototype) == 'object') {	//SWFObject v1.4
			var so = new SWFObject(this.videoFile, flashId, this.video.width, this.video.height, "9", "#000");

			so.addParam("scale", "noscale");
			so.addParam("allowfullscreen", "true");
			so.addParam("menu", "false");
			
			so.addVariable("autoplay", "false");
			so.addVariable("vidwidth", this.video.width);
			so.addVariable("vidheight", this.video.height);
			so.addVariable("defaultid", this.videoId);
			so.addVariable("xmlPath", this.galleryXmlPath);
			
			so.addParam("wmode", "transparent");
			so.write("videoContainer");
		} else { // if(swfobject) { //SWFObject v2.1+
			//Hide the controlbar chrome if flash is not installed
			if(!swfobject.hasFlashPlayerVersion("7.0.0")) {
				this.controlbar.container.style.display = "none";
				this.controlbar.menu.container.style.display = "none";
			}
			var flashvars = {
				autoplay:"false",
				vidwidth:this.video.width,
				vidheight:this.video.height,
				xmlPath:this.galleryXmlPath,
				defaultid:this.videoId
			};
			var params = {
				scale:"noscale",
				quality:"best",
				wmode:"transparent",
				menu:"false",
				allowfullscreen:"true"
			};
			var attributes = {id:flashId,name:flashId};
			//Create replacement div for the flash to overwrite
			var divReplace = new Element('div', {
				'id':'replace'
			});
			divReplace.innerHTML = this.video.container.innerHTML;
			this.video.container.innerHTML = '';
			divReplace.inject(this.video.container, 'top');
			//end replacement
			swfobject.embedSWF(this.videoFile,"replace",parseInt(this.video.width),parseInt(this.video.height),"9","expressInstall.swf", flashvars, params, attributes);
		}
	}
});

var Video = new Class({
	initialize: function(options) {
		this.isLoading = false;
		this.height = options.height;
		this.width = options.width;
		this.container = $('videoContainer');
		this.container.style.width = this.width;
		this.container.style.height = this.height;
		this.isPaused = true;
		this.currentTime = "0:00";
		this.totalTime = "0:00";
	},
	play: function(force) {
		sendFlashEvent('play');
		this.isPaused = false;
	},
	pause: function(force) {
		sendFlashEvent('pause');
		this.isPaused = true;
	},
	load: function(id) {
		this.id = id;
		this.isLoading = true;
	}
});

var ControlBar = new Class({
	initialize: function(options) {
		this.btnMenu = $$('a.menu')[0];
		this.btnPlayPause = $$('.button_pause_play')[0];
		this.container = $$('div.controls')[0];
		this.progressContainer = $$('div.progress')[0];
		this.progressMeter = $('progressMeter');
		this.progressGrabber = this.progressMeter.getElement('.grabber');
		this.audioLevel = $('audioLevel');
		this.currentAudioLevel = $$('.audio .currentLevel')[0];
		this.timeDisplay = $$('.timeDisplay')[0];

		this.height = parseInt(this.container.getStyle('height'));
		this.menu = options.menu;
		this.videoPlayer = options.videoPlayer;
		dontSendEvent = true; //For progressBar & volume

		//Resize ControlBar
		this.container.style.width = this.videoPlayer.width;
		this.progressContainer.style.width = this.videoPlayer.width - 200; //200 = play + volume + menu?
		this.progressMeter.style.width = this.videoPlayer.width - 308; //extra 108 for time/time

		//Build sliders: progress & volume
		this.loadingMeter = new LoadMeter({
			width: this.videoPlayer.width - 314
		}).set(0);

		this.progressSlider = new Slider(this.progressMeter, this.progressGrabber, {
			steps: 100,
			range: [1],
			onComplete: function() {
				//console.log("onComplete");
			},
			onStart: function() {
				//console.log("onStart");
			},
			onChange: function(value) {
				if (!dontSendEvent) {
					var bits = videoPlayer.video.totalTime.split(":");
					var totalSeconds = (bits[0]/1 * 60) + bits[1]/1;
					bits = videoPlayer.video.currentTime.split(":");
					var currentSeconds = (bits[0]/1 * 60) + bits[1]/1;
					if (value > this.loadingMeter.percent) {
						var destinationSeconds = Math.round(totalSeconds * (this.loadingMeter.percent / 100));
					} else {
						var destinationSeconds = Math.round(totalSeconds * (value / 100));
					}
					var secondsToMove = destinationSeconds - currentSeconds;
					
					if (value == 1 && currentSeconds > 0) {
						secondsToMove = 0 - currentSeconds;
					}
					//this.send('vp_play_scrub', secondsToMove);
					sendFlashEvent('timeline', secondsToMove);
				}
			}.bind(this)
		}).set(0);

		this.progressSlider.drag.addEvents({
				'start': function() {
					dontReceiveEvent = true;
					this.pause();
				}.bind(this),
				'complete': function() {
					this.play();
					dontReceiveEvent = false;
				}.bind(this)
		});

		this.audioSlider = new Slider(this.audioLevel, this.audioLevel.getElement('.grabber'), {
			steps: 100,
			range: [1],
			onChange: function(value) {
				if (!dontSendEvent) {
					try {
						/*
						if (value == 1) {
							this.send('vp_mute', '');
						} else {
							this.send('vp_audio_scrub', value);
						}
						*/
						this.currentAudioLevel.setStyle('width',(parseInt(this.audioLevel.getStyle('width')) * value/100) + 'px');
						sendFlashEvent('audioLevel', value);
					} catch (e) {
						//do nothing
					}
				}
			}.bind(this)
		}).set(50);
		this.currentAudioLevel.setStyle('width',(parseInt(this.audioLevel.getStyle('width')) * .5) + 'px');
		dontSendEvent = false;

		/*
		* Events
		*/

		this.btnMenu.addEvents({
			'click': function(e) {
				e.stop();
				this.pause();
				this.menu.toggle();
			}.bind(this),
			'mouseleave': function() {
				if( this.menu.isVisible ) {
					this.menu.hide.delay(1000,this.menu);
				}
			}.bind(this)
		});

		this.btnPlayPause.addEvent('click', function(e) {
			e.stop();
			this.togglePlayPause();
		}.bind(this));
	},
	setTime: function(time) {
		if(this.timeDisplay.innerHTML != time) {
			//console.log('time: '+time);
			this.timeDisplay.innerHTML = time;
		}
	},
	play: function(forcePlay) {
		//console.log('controlpanel.play()');
		if( this.videoPlayer.video.isPaused || forcePlay ) {
			this.btnPlayPause.addClass('button_pause');
			this.btnPlayPause.removeClass('button_play');
			this.videoPlayer.video.play();
		}	
	},
	pause: function() {
		//console.log('controlpanel.pause()');
		if( !this.videoPlayer.video.isPaused ) {
			this.btnPlayPause.removeClass('button_pause');
			this.btnPlayPause.addClass('button_play');
			this.videoPlayer.video.pause();
		}
	},
	togglePlayPause: function() {
		//console.log("togglePlayPause: in");
		//console.log("isPaused: " + this.videoPlayer.video.isPaused);
		//console.log("dontSendEvent: " + dontSendEvent);
		if(!dontSendEvent) {
			try {
				if( this.videoPlayer.video.isPaused ) {
					this.play();
				} else {
					this.pause();
				}
			} catch (e) {
				//Flash not ready, do nothing
			}
		}
	},
	reset: function() {
		//console.log('reset()');
		this.btnPlayPause.className = "button_pause_play";
		this.btnPlayPause.addClass("button_play");
		this.videoPlayer.video.pause();
		this.progressSlider.set(1);
	}
});

var Menu = new Class({
	initialize: function(options) {
		this.videoPlayer = options.videoPlayer;

		this.isVisible = false;
		this.isFocused = false;
		this.container = $('menuContainer');
		this.error = $$('div.errorMessages')[0];
		this.btnEmbed = $$('a.menuitem_embed')[0];
		this.btnShare = $$('a.menuitem_share')[0];
		this.btnClose = $$('a.closeExtendedButton')[0];
		this.btnShareEmail = $('share_email');
		this.txtShare = $('embed_url');
		this.txtEmbed = $('embed_embed');
		this.arrLinks = $$('.map a');
		//this.btnShareReddit = $('share_reddit');
		this.btnShareFacebook = $('share_facebook');
		this.btnShareStumbleUpon = $('share_stumbleupon');
		this.btnShareMySpace = $('share_myspace');
		this.btnShareDelicious = $('share_delicious');
		this.btnShareDigg = $('share_digg');

		this.ShowFx = new Fx.Morph(this.container, {
			duration: 1000,
			transition: Fx.Transitions.Sine.easeOut,
			link: 'cancel'
		});

		/*
		* Events
		*/
		this.container.addEvent('mouseleave', function() {
			this.isFocused = false;
			this.hide.delay(1000,this);
		}.bind(this));

		this.container.addEvent('mouseenter', function() {
			this.isFocused = true;
		}.bind(this));

		this.btnClose.addEvent('click', function(e) {
			e.stop();
			this.isFocused = false;
			this.hide();
		}.bind(this));

		this.btnEmbed.addEvent('click', function(e) {
			e.stop();
			this.select('embed');
		}.bind(this));

		this.btnShare.addEvent('click', function(e) {
			e.stop();
			this.select('share');
		}.bind(this));

		this.btnShareEmail.addEvent('click', function(e) {
			e.stop();
			this.select('share_email');
		}.bind(this));

		/*
		this.btnShareReddit.addEvent('click', function(e) {
			e.stop();
			window.open('http://www.reddit.com/login?dest=/submit?url='+this.videoPlayer.shareUrl);
		}.bind(this));
		*/

		this.btnShareDigg.addEvent('click', function(e) {
			e.stop();
			window.open('http://digg.com/submit?phase=2&url='+this.videoPlayer.shareUrl);
		}.bind(this));

		this.btnShareStumbleUpon.addEvent('click', function(e) {
			e.stop();
			window.open('http://www.stumbleupon.com/submit?url='+this.videoPlayer.shareUrl);
		}.bind(this));

		this.btnShareDelicious.addEvent('click', function(e) {
			e.stop();
			window.open('http://del.icio.us/post?v=4&noui&jump=close&url='+this.videoPlayer.shareUrl);
		}.bind(this));

		this.btnShareFacebook.addEvent('click', function(e) {
			e.stop();
			window.open('http://www.facebook.com/share.php?u='+this.videoPlayer.shareUrl);
		}.bind(this));

		this.btnShareMySpace.addEvent('click', function(e) {
			e.stop();
			window.open('http://www.myspace.com/Modules/PostTo/Pages/?u='+this.videoPlayer.shareUrl);
		}.bind(this));

	},
	updateEmbed: function() {
		this.txtEmbed.value = '<iframe src="' + this.videoPlayer.embedUrl +'?i='+this.videoPlayer.videoId+'&l=0&url='+this.videoPlayer.shareUrl+ 
								'" width="'+ this.videoPlayer.width +'" height="'+ this.videoPlayer.height +'" ' +
								'marginheight="0" marginwidth="0" frameborder="0" scrolling="no"></iframe>' 
		this.txtShare.value = this.videoPlayer.shareUrl;
	},
	hideError: function() {
		this.error.setStyle('display','none');
	},
	setError: function(msg) {
		this.error.innerHTML = msg;
	},
	select: function(item) {
		this.reset();
		this.container.addClass('menu_' + item);
		if(item == 'share_email') {
			$('share_to').focus();
		}
	},
	toggle: function() {
		if(this.isVisible) {
			this.hide();
		} else {
			this.show();	
		}
	},
	hide: function() {
		if( !this.isFocused ) {
			this.isVisible = false;
			this.ShowFx.start({
				'bottom':'-57px'
			});
		}
	},
	show: function() {
		this.isVisible = true;
		this.reset();
		this.ShowFx.start({
			'bottom':'26px'
		});
	},
	reset: function() {
		this.hideError();
		this.container.className = "menu_background";
	}
});

var LoadMeter = new Class({
	initialize: function(options) {
		this.width = options.width;
		this.progress = $$('div.currentProgress')[0];
		this.percent = 0;
	},
	set: function(percent) {
		this.percent = percent;
		this.progress.style.width = this.width * (percent/100);
		return this;
	}
});

/* Resets the email error message area */
function resetEmailError() {
	var messageDiv = $$('div.errorMessages')[0];
	
	messageDiv.innerHTML = "";
	messageDiv.style.display = "none";	
}

/* Displays an email error message */
function showEmailError(p_text) {
	var messageDiv = $$('div.errorMessages')[0];
	
	messageDiv.innerHTML = p_text;
	messageDiv.style.display = "block";	
}

/* Sends the email share form on enter key down */
function sendOnEnter(p_event) {
	if (!p_event) {
		p_event = window.event;
	}
	
	if (p_event.keyCode == 13) {
		sendShareEmail();
	}
}

/* Sends the share email */
function sendShareEmail() {
	var toAddress = 	$('share_to').value;
	var fromAddress = 	$('share_from').value;
	var shareURL = 		document.location.href;
	if (!checkEmail(toAddress)) {
		showEmailError('Please enter a valid TO address.');
	} else if (!checkEmail(fromAddress)) {
		showEmailError('Please enter a valid FROM address.');
	} else {
		showEmailError('Sending email...');
		var request = new Request({url:"rimvideoplayer_sendemail.jsp?to=" + toAddress + "&from=" + fromAddress + "&url=" + shareURL, async:false});
		request.addEvent("failure", function(xhr) {
			showEmailError('Failed to send email.');
		});
		request.addEvent("success", function(p_text, p_xml) {
			showEmailError(p_text);
		});
		request.addEvent("complete", function() {
			showEmailError('Sending email, awaiting server response...');
		});
		request.send();
	}
}

/* used to stop event sends onchange of the sliders when changing per event from the flash movie */
var dontSendEvent = false;
var dontReceiveEvent = false;
var lastAttempt = 0;
/* Slider Controls Initialization */

/* 
* Parameters:
* 	variable - the querystring variable you want the value of
* 	bParent - boolean that's true if you want the parent frame or false if you want the iframe
*/

function getQueryVariable(p_var,p_loc) {
	p_loc = (p_loc != null && p_loc) ? window.parent.location : window.location;
	var query = p_loc.search.substring(1);
	//console.log("variable: " + p_var + " query: " + query);
	//Check if it has frames and parent is true then search parent url.  Otherwise search the iframe url.
	//var query = (window.parent.frames.length<1) ? window.parent.location.search.substring(1) : window.location.search.substring(1);
	//console.log("window.location.search: " + window.location.search.substring(1));
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == p_var) {
			return pair[1];
		}
	}
	return 1;
}

/* Sends an event from the DOM controls to the flash movie */
function sendFlashEvent(p_event, p_param) {
	if (p_event == "play") {
		sendCmdToFlash('vp_play','');
	} else if (p_event == "pause") {
		sendCmdToFlash('vp_pause','');
	} else if (p_event == "audioLevel") {
		if (p_param == 1) {
			sendCmdToFlash('vp_mute','');
		} else {
			//console.log("sending: vp_audio_scrub with value:" + (p_param / 100));
			sendCmdToFlash('vp_audio_scrub', p_param / 100);
		}
	} else if (p_event == "timeline") {
		//console.log("sending: vp_play_scrub with value:" + p_param);
		sendCmdToFlash('vp_play_scrub', p_param);
	}
}

/* Receives events from the flash movie */
function receiveFlashEvent(p_event, p_param) {
	if (p_event.toLowerCase() == "settime") {
		if (p_param != videoPlayer.controlbar.timeDisplay.innerHTML) {
			//console.log("receiveFlashEvent('settime','"+p_param+"')");
			videoPlayer.controlbar.setTime(p_param);
		}
		//$$('.rimVideoPlayer .timeDisplay')[0].innerHTML = p_param;
	} else if (p_event.toLowerCase() == "pause") {
		//console.log("flash 2 html: Pause");
		videoPlayer.video.pause();
	} else if (p_event.toLowerCase() == "play") {
		//console.log("flash 2 html: Play");
		videoPlayer.video.play();
	} else if (p_event.toLowerCase() == "setload") {
		dontSendEvent = true;
		if (Math.round(p_param) != videoPlayer.controlbar.loadingMeter.percent) {
			//console.log("setting load meter in response to flash event with value: " + Math.round(p_param));
			videoPlayer.controlbar.loadingMeter.set(Math.round(p_param));
		}
		dontSendEvent = false;
	} else if (p_event.toLowerCase() == "setprogress") {
		if (dontReceiveEvent || (videoPlayer.video.isLoading && Math.round(p_param) > 1) ) {
			return;
		} else {
			dontSendEvent = true;
			if( videoPlayer.video.isLoading && Math.round(p_param) == 1) {
				videoPlayer.video.isLoading = false;
			}
			if(Math.round(p_param) > 0 && Math.round(p_param) != videoPlayer.controlbar.progressSlider.step) {
				//console.log("setting progress meter in response to flash event with value: " + Math.round(p_param));
				videoPlayer.controlbar.progressSlider.set(Math.round(p_param));
			}
			dontSendEvent = false;
		}
	} else if (p_event.toLowerCase() == "setaudiolevel") {
		dontSendEvent = true;
		videoPlayer.controlbar.audioSlider.set(p_param);
		dontSendEvent = false;
	}
}

/* Flash API From Erin G. */
function playCompleted() {
	//console.log('playCompleted');
	dontSendEvent = true;
	videoPlayer.controlbar.reset();
	videoPlayer.controlbar.progressSlider.set(0);
	dontSendEvent = false;
}

function updateTitles() {
	//fires when XML is loaded and passes in an array of titles
}

function sendToAS(cmd,values) {    
	thisMovie("BB_Movie").callAS(cmd,values);
}

function sendCmdToFlash(cmd,values) {		
	sendToAS(cmd,values);
}

function thisMovie(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	} else {
		return document[movieName];
	}
}

function showTotalTime(val){
	//console.log("total time: " + val);
	if (val != null) {
		videoPlayer.video.totalTime = val;
	}
	receiveFlashEvent("settime", videoPlayer.video.currentTime + " / " + videoPlayer.video.totalTime);
}

function showCurrentTime(val){
	//console.log("current time: " + val);
	if (val != null) {
		videoPlayer.video.currentTime = val;
	}
	receiveFlashEvent("settime", videoPlayer.video.currentTime + " / " + videoPlayer.video.totalTime);
}

function showCurrentPercentage(val){
	//console.log("current percentage received from flash: " + val);
	if (val != null) {
		receiveFlashEvent("setprogress", val);
	}
}

function showLoadedPercentage(val){
	//console.log("loadedpercentage: " + val)
	if (val != null) {
		receiveFlashEvent("setload", val);
	}
}

/* Email related functions, copied from web */
function checkEmail(p_val) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(p_val)){
		return true;
	}
	return false;
}

