/**
 * Various static utility methods to help with creating and using the html5 player.
 *
 * @author Joey Line <joey.line@skiclubz.com>
 */
(function($) {
	// Constructor
	zPlayer.utils = function() {
	};
	
	// wrapper for console.log, to prevent errors if console isn't around and to make 
	// Chrome/Safari give prettier log statements with multiple arguments. Modified from
	// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
	// TODO: This should check zPlayer.config.debug [which should be more or less "static" as far
	//	as we're concerned] before calling console.log.
	zPlayer.utils.log = function() {
		if(!window.log) window.log = {};
		window.log.history = window.log.history || [];   // store logs to an array for reference
		window.log.history.push(arguments);
		
		if(typeof(window.console)=='object') {
			// hack in a reference to the calling function
			Array.prototype.unshift.call(arguments, arguments.callee.caller);
			// add a timestamp [in milliseconds]
			Array.prototype.unshift.call(arguments, new Date().getTime());
			
			window.console.log('zPlayer', Array.prototype.slice.call(arguments));
		}
	};
	
	zPlayer.utils.serverLog = function() {
		zPlayer.utils.log(Array.prototype.slice.call(arguments));
		$.post('/video/log', {data: Array.prototype.slice.call(arguments)});
	};
	
	/**
	 * Checks whether the current browser is compatible. Operates on a black list and currently
	 * only blocks IE8-. Other older browsers should be blocked by the fact that they either
	 * don't have HTML5 Video or can't play our video formats.
	 */
	zPlayer.utils.checkCompatibleBrowser = function() {
		// IE8-
		if ($.client.browser == 'MSIE' && $.client.version < 9)
			return false;
		
		return true;
	}
	
	// is the browser on an iPhone?
	zPlayer.utils.isiPhone = function() {
		var agent = navigator.userAgent.toLowerCase();
		return agent.match(/iPhone/i);
	};
	
	// is the browser on an iPad? 
	zPlayer.utils.isiPad = function() {
		var agent = navigator.userAgent.toLowerCase();
		return agent.match(/iPad/i);
	};

	// if obj is null or undefined, return true.
	zPlayer.utils.isNull = function(obj) {
		return ((obj === null) || (obj === undefined) || (obj === ""));
	};
	
	// return the extension of filename
	zPlayer.utils.extension = function(filename) {
		return filename.substr(filename.lastIndexOf('.') + 1);
	};
	
	// This is a workaround to the fact that IE8 [and possibly older versions of other browsers]
	// don't see elements under a <video> element as children due to their lack of understanding of
	// HTML5. Use it just like jQuery.children() or jQuery.siblings() - it will return the jQuery
	// object containing children or siblings matching the optional selector, or an empty jQuery
	// object if none were found.
	$.fn.childrenOrSiblings = function(selector) {
		var result = null;
		this.each(function() {
			result = $(this).children(selector);
			if(zPlayer.utils.isNull(result[0])) {
				result = $(this).siblings(selector);
			}
		});
		
		return result;
	};
	
	// format a seconds timestamp in the format ##:##.##
	// TODO: add hours? format would then be [##:]##:##.##
	zPlayer.utils.formatTime = function(seconds, precision) {
		if(zPlayer.utils.isNull(precision)) precision = 0;
		var time = '0:00.00';
		if (seconds > 0) {
			// calculate the minutes
			time = Math.floor(seconds / 60);
			
			// calculate the seconds
			var fixedSeconds = (seconds - (time * 60)).toFixed(precision);
			
			// put it all together now!
			time += ':' + (fixedSeconds < 10
					? '0' + fixedSeconds
					: fixedSeconds);
		}
		
		return time;
	};
	
	// trims whitespace around a string
	// http://blog.stevenlevithan.com/archives/faster-trim-javascript
	zPlayer.utils.trim = function(str) {
		str = str.replace(/^\s+/, '');
		for (var i = str.length - 1; i >= 0; i--) {
			if (/\S/.test(str.charAt(i))) {
				str = str.substring(0, i + 1);
				break;
			}
		}
		return str;
	};
	
	// filetypes supported by Flash
	zPlayer.utils.flashFileTypes = {
		'aac': true,
		'f4v': true,
		'flv': true,
		'm4a': true,
		'm4v': true,
		'mov': true,
		'mp3': true,
		'mp4': true
	};
	
	zPlayer.utils.flashCanPlay = function(extension) {
		if(zPlayer.utils.flashFileTypes[extension]) {
			return true;
		}
		return false;
	};
	
	// Check if the browser supports Flash player 9.0.115+ (FLV/H264).
	zPlayer.utils.supportsFlash = function(){
		var version = '0,0,0,0';
		try {
			// ie
			try {
				// avoid fp6 minor version lookup issues
				// see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
				var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
				try {
					axo.AllowScriptAccess = 'always';
				} catch(e) {
					version =  '6,0,0';
				}
			} catch(e) {}
			
			version = new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
		} catch(e) {
			// other browsers
			try {
				if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) {
					version = (navigator.plugins['Shockwave Flash 2.0'] ||
						navigator.plugins['Shockwave Flash']).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
				}
			} catch (e) {}
		}
		
		zPlayer.utils.log('Flash version', version);
		
		var major = parseInt(version.split(',')[0], 10);
		var minor = parseInt(version.split(',')[2], 10);
		if (major > 9 || (major == 9 && minor > 97)) {
			return true;
		} else {
			return false;
		}
	};
})(jQuery);

