/**
* MTVN
* @module MTVN
*/
// Define the namepsace
if (typeof(MTVN) == 'undefined') MTVN = {};

Function.prototype.extend = function(SuperFunc) {
   var Self = this;
   var Func = function() {
      SuperFunc.apply(this, arguments);
      Self.apply(this, arguments);
   };
   var thisSuper = new SuperFunc();
   thisSuper.SuperFunc = SuperFunc;
   Func.prototype = thisSuper;
   return Func;
}

MTVN.extend = function (subclass, superclass) {
	function Dummy() {}
	Dummy.prototype = superclass.prototype;
	subclass.prototype = new Dummy();
	subclass.prototype.constructor = subclass;
	subclass.superclass = superclass;
	subclass.superproto = superclass.prototype;
}

MTVN.Config = {
	_params : { 
		debug : false
	},
	
	_getConfigParam : function (propName) {
		return this._params[propName] == undefined ? null : this._params[propName];
	},

	_setConfigParam : function (propName, propValue) {
		this._params[propName] = propValue;
	},
	
	configure : function (propName, propValue) {
		this._setConfigParam(propName, propValue);
	}
}

/* MTVN.debug */
MTVN.debug = function (txt, context) {
	if (!MTVN.Config._params.debug && !document.location.search.match(/debug=true/i)) return;
	
	var itemContainer = document.getElementById('MTVN-debug-items');
	var firstRun = false;
	
	// On the first run set up the container
	if (itemContainer == null) {
		firstRun = true;
		
		var displayState = document.cookie.indexOf('MTVN-debug-state=block') != -1 ? 'block' : 'none';
		
		var debugContainer = document.createElement('DIV');
		debugContainer.id = 'MTVN-debug';
		document.body.insertBefore(debugContainer, document.body.firstChild);
		
		debugContainer.innerHTML = '<div id="MTVN-debug-header"><b>DEBUG LOG<b/> '+
			'<a href="" onclick="MTVN.debugChangeState(); return false;">Show/Hide</a></div>';
		
		itemContainer = document.createElement('DIV');
		itemContainer.setAttribute('id', 'MTVN-debug-items');
		itemContainer.style.display = displayState;
		
		//itemContainer.style.height = document.body.clientHeight -50 + 'px';
		debugContainer.appendChild(itemContainer);
		debugContainer.innerHTML += '<div id="MTVN-debug-filter" style="display:'+displayState+'"><b>Filter events:</b> '+
			'<input type="text" onKeyUp="MTVN.debug._filter(this.value);" style="font:10px verdana; width:200px;" /></div>'
	}
	
	var initialHeight = itemContainer.scrollHeight;
	var wasScrolled = itemContainer.scrollTop + itemContainer.offsetHeight == initialHeight;
	
	var el = document.createElement('DIV');
	if (context == undefined) context = 'NoContext';
	el.className = 'MTVN-debug-item ' + MTVN.Util.sanitize(context);
	itemContainer.appendChild(el);
	var logDate = new Date();
	var dateStr = logDate.getHours() + ':' + logDate.getMinutes() + ':' + logDate.getSeconds() + ' - ' + logDate.getMilliseconds();
	el.innerHTML = '<div class="MTVN-debug-eventType">&nbsp;'+context+'&nbsp;</div>' +
		'<div class="MTVN-debug-timestamp">Time: ' + dateStr + ' ms</div>'+
		'<div class="MTVN-debug-msg">' + txt + '</div>';
	
	if (initialHeight <= itemContainer.offsetHeight && itemContainer.scrollHeight > itemContainer.offsetHeight) {
		itemContainer.scrollTop = itemContainer.scrollHeight * 2;
	} else {
		if (wasScrolled) {
			itemContainer.scrollTop = itemContainer.scrollHeight * 2;
		}
	}
}

MTVN.debugChangeState = function () {
	var itemContainer = document.getElementById('MTVN-debug-items');
	
	var isHidden = itemContainer.style.display == 'none';
	
	itemContainer.style.display = isHidden ? 'block' : 'none';
	var filterContainer = document.getElementById('MTVN-debug-filter');
	filterContainer.style.display = isHidden ? 'block' : 'none';
	
	document.cookie = 'MTVN-debug-state='+itemContainer.style.display+'; path=/; domain='+location.hostname+';';
}

// Logs the contents of an object
MTVN.debugObj = function (obj, context, txt) {
	if (!MTVN.Config._params.debug) return;
	
	var str = 'Obj contents:<br />';
	for (var prop in obj) {
		str += prop + '=' + obj[prop] + '<br />';
	}
	if (txt != undefined) str = txt + '<br />' + str;
	MTVN.debug(str, context);
}

MTVN.debug._filter = function (regexStr) {
	var itemContainer = document.getElementById('MTVN-debug-items');
	
	regexStr = regexStr.toLowerCase();
	var re = new RegExp(regexStr);
	
	var divs = itemContainer.getElementsByTagName('DIV');
	
	for (var i=0; i < divs.length; i++) {
		if (regexStr == '') {
			divs[i].style.display = 'block';
			continue;
		}
		
		if (divs[i].className.indexOf('MTVN-debug-item') != -1) {
			if (MTVN.util.sanitize(divs[i].className).match(re) != null) {
				divs[i].style.display = 'block';
			} else {
				divs[i].style.display = 'none';
			}
		}
	}
	
	itemContainer.scrollTop = itemContainer.scrollHeight;
	return true;
}
/* ---------- */

MTVN.SWFObject = {
	expressInstallSwfUrl: MTVN_clientBase + '/swfobject_2_1/expressInstall.swf'
}

MTVN.SHR = {
	isLoaded : false,
	requestQueue : [],
	
	init : function(){
		MTVN.debug('Initialzing', 'MTVN.SHR.init');
		
		var src = MTVN_clientBase+"/swf/swfhttprequest.swf";
		var flashObjectId = "MTVN_shr-container";
		var flashVersion = "9.0.115.0";
		
		// add container to DOM
		var body = document.getElementsByTagName("body")[0];
		var shrContainer = document.createElement("div");
		shrContainer.id = flashObjectId;
		body.appendChild(shrContainer);
		
		// swfobject params
		var flashvars = {};
		var params = {
			allowScriptAccess: "always",
			bgcolor: "#b2b2b2"
		};
		var attributes = {
			id: flashObjectId,
			name: flashObjectId
		};
		
		swfobject.embedSWF(src, flashObjectId, "1", "1", flashVersion, MTVN.SWFObject.expressInstallSwfUrl, flashvars, params, attributes);

		this.checkIsLoaded();
	},

	checkIsLoaded : function(){
		//console.log("checkIsLoaded: " + this.isLoaded);
		if (typeof SWFHttpRequest == "function"){
			this.isLoaded = true;
			MTVN.SHR.processRequestQueue();
		}
		else{
			setTimeout('MTVN.SHR.checkIsLoaded()',500);
		}
	},
	
	processRequestQueue : function(){
		for (var i=0; i < this.requestQueue.length; i++) {
			var deferred = this.requestQueue.shift();
			var fnCall = deferred.fn + '(' + JSON.stringify(deferred.args, null, 1) + ')';
			eval(fnCall);
		}
	},
	
	addToRequestQueue : function(fnObj){
		this.requestQueue.push(fnObj);
	}
}

/* ---------- */

MTVN.Util = {
	sanitize : function(id) {
		id = id + '';
		id = id.toLowerCase();
		id = id.replace(/^([0-9])/, '_$1');
		id = id.replace(/[^A-Za-z0-9\-]/g, '_');
		return id;
	},

	addCSSClass : function (element, className) {
		if (element != null) {
			element.className += ' ' + className;
		}
	},
	
	removeCSSClass : function (element, className, allOccurances) {
		if (allOccurances != true) allOccurances = false;
		if (element != null) {
			var classes = element.className.split(' ');
			for (var i=0; i<classes.length; i++) {
				if (classes[i] == className){
					classes.splice(i, 1);
					if (!allOccurances) break;
				}
			}
			element.className = classes.join(' ');
		}
	}
};

MTVN.Util.Cookies = new function(){
	this.create = function(name,value,days){
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}
	
	this.read = function(name){
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}
	
	this.erase = function(name){
		MTVN.Util.Cookies.create(name,"",-1);
	}
}
/* ---------- */

MTVN.Dictionary = {
	phrases : {},
	
	getPhrase : function(key){
		var val = (this.phrases[key] != undefined) ? unescape(this.phrases[key]) : key;
		val = this.replaceTokens(val);
		return val;
	},
	
	addPhrase : function(key, value){
		this.phrases[key] = value;
	},
	
	replaceTokens : function(s){
		if(s.indexOf("{") < 0) return s; // no tokens
		else{
			var start = s.substring(0, s.indexOf("{"));
			var end = s.substring(s.indexOf("}")+1, s.length);
			var remainder = s.substring(s.indexOf("{")+1, s.length);

			var token = remainder.substring(0, remainder.indexOf("}"));			
			var tokenValue = (this[token]!=undefined) ? this[token] : "{"+token+"}";
			return start + tokenValue + this.replaceTokens(end);
		}
	}
}

/*
 * DialogManager manages the rendering and destruction of all dialogs
 */
MTVN.DialogManager =  {
	_activeDialog : null,
	_container : null,
	dialogCount : 0
}

MTVN.DialogManager.init = function () {
	this.contextName = 'DialogManager';
	//this.container;
	
	// Set up the yui class on the body so we can do a modal effect

	// DA - really don't think we need this - 08/18/2009 
	/*
	if (!document.body.className.match('yui-skin-sam'))
	document.body.className += ' yui-skin-sam';
	*/
	
	MTVN.DialogManager.createContainer();
	
	window.onresize = function () {
		var _activeDialog = MTVN.DialogManager._activeDialog
		if (_activeDialog != null) {
			MTVN.DialogManager.sizeMask(_activeDialog.widget, null);
		}
	}
	
	window.onscroll = function () {
		var _activeDialog = MTVN.DialogManager._activeDialog;
		if (_activeDialog != null) {
			MTVN.DialogManager.sizeMask(_activeDialog.widget, null);
		}
	}
}

MTVN.DialogManager.createMask = function () {
	var mask = document.createElement('DIV');
	mask.id = this._container.id + '_mask';
	mask.className = 'mask';
	mask.style.zIndex = 1;
	document.body.insertBefore(mask, document.body.firstChild);
	this.mask = mask;
}

MTVN.DialogManager.sizeMask = function(widget, scrollTop) {
	
	if (scrollTop != null)
		document.documentElement.scrollTop = scrollTop;
	
	this.mask.style.zIndex = widget.element.style.zIndex -1;
	
	this.mask.style.width = document.documentElement.scrollWidth + 'px';
	this.mask.style.height = (document.documentElement.scrollHeight > document.documentElement.clientHeight ?
							document.documentElement.scrollHeight : document.documentElement.clientHeight)  + 'px';
	
	if (window.innerWidth) {
		widget.element.style.position = 'fixed'; 
		widget.element.style.top = (document.documentElement.clientHeight / 2) -
			(widget.element.offsetHeight / 2) + 'px';
	} else {
		widget.element.style.position = 'absolute';
		widget.element.style.top = (document.documentElement.clientHeight > widget.element.offsetHeight ? 
					document.documentElement.scrollTop + (document.documentElement.clientHeight / 2) - (widget.element.offsetHeight / 2) : 
					document.documentElement.scrollTop) + 'px';
	}
	
	widget.element.style.marginLeft = '50%';
	widget.element.style.left = (-(widget.element.offsetWidth / 2)) + 'px';
}

MTVN.DialogManager.showMask = function (widget, scrollTop) {
	if (this.mask == null) {
		this.createMask();
	}
	
	MTVN.DialogManager.sizeMask(widget, scrollTop);
	MTVN.DialogManager.mask.style.display = 'block';
}

MTVN.DialogManager.hideMask = function () {
	this.mask.style.display = 'none';
}

MTVN.DialogManager.createContainer = function () {
	this._container = document.createElement('DIV');
	this._container.id = 'MTVN-dialog-container_' + this.dialogCount++;
	document.body.insertBefore(this._container, document.body.firstChild);
}

MTVN.DialogManager.resetContainer = function () {
	if (this._container != null) this._container.parentNode.removeChild(this._container);
	this.createContainer();
}

MTVN.DialogManager.destroyActiveDialog = function () {
	this.resetContainer();
	if (this._activeDialog != null) {
		this._activeDialog.destroy();
		this._activeDialog = null;
	}
}

MTVN.DialogManager.showSingleButtonDialog = function (dialogTitle, message, buttonTxt, cssClass, buttonCallback, buttonEvtObj, buttonScope) {
	
	// If no button action is specified, assume close
	if (buttonCallback == undefined) {
		buttonCallback = function() { 
			MTVN.DialogManager.destroyActiveDialog(); 
			};
	}
	
	var buttons = [{
		text : buttonTxt,
		isDefault : true,
		handler : function () {
			buttonCallback.call(buttonScope, buttonEvtObj);
		}
	}]
	
	this._activeDialog = new MTVN.SimpleButtonDialog(dialogTitle, message, buttons, cssClass);
}

MTVN.DialogManager.showConfirmDialog = function (dialogTitle, message, buttonTxt, cancelTxt, cssClass, buttonCallback, buttonEvtObj, buttonScope) {
	// Default button text
	buttonTxt = MTVN.util.getValue(buttonTxt, 'Yes');
	cancelTxt = MTVN.util.getValue(cancelTxt, 'No');
	
	// If no button action is specified, assume close
	if (buttonCallback == undefined) {
		bbuttonCallback = function() { 
				MTVN.DialogManager.destroyActiveDialog(); 
			};
	}
	
	var buttons = [];
	var buttons = [{
			text : buttonTxt,
			isDefault : false,
			handler : function () {
				buttonCallback.call(buttonScope, buttonEvtObj);
			}
		}, 
		{
			text : cancelTxt,
			handler : {
				fn : function() { this.hide() }
			}
		}
	];
	
	this._activeDialog = new MTVN.SimpleButtonDialog(dialogTitle, message, buttons, cssClass);
}

// Base class all dialogs should extend
MTVN.BaseDialog = function() {
	MTVN.DialogManager.destroyActiveDialog();
}

MTVN.BaseDialog.prototype.init = function () {}

MTVN.BaseDialog.prototype.destroy = function() {
	try {
		this.widget.hide();
		this.widget.destroy();
	} catch (e) {
		alert (e);
	}
}

MTVN.BaseDialog.prototype.successAction = function (evtObj) {
	//MTVN.debug('Not implemented for this dialog.', 'BaseDialog.successAction');
};

/*
 * A Dialog that shows a single button and a message.
 * cssClass, buttonCallback and buttonEvtObj are optional.
 * Default behavior is to close after clicking button.
 */
MTVN.SimpleButtonDialog = function (dialogTitle, message, buttons, cssClass) {
	
	MTVN.SimpleButtonDialog.superclass.apply(this, arguments);
		
	this.dialogTitle = dialogTitle;
	this.message = message;
	this.buttons = buttons;
	this.cssClass = cssClass;

	this.widgetID = 0;//MTVN.Controller.newWidgetID();
	
	this.init();
	this.widget = this.widgetInit();
	
	this.widget.beforeHideEvent.subscribe(function() {MTVN.DialogManager.hideMask()});
}

// Extend the base class
MTVN.extend(MTVN.SimpleButtonDialog, MTVN.BaseDialog);

MTVN.SimpleButtonDialog.prototype.init = function () {
	MTVN.DialogManager._container.className += ' MTVN-single-button-dialog';
	if (this.cssClass != undefined) MTVN.DialogManager._container.className += ' ' + this.cssClass;
	MTVN.DialogManager._container.innerHTML = 
	'<div class="hd">'+this.dialogTitle+'</div> '+
	'<div class="bd"> '+this.message+'</div> ';
}

MTVN.SimpleButtonDialog.prototype.widgetInit = function () {
/*	
	var widget = new YAHOO.widget.Dialog(MTVN.DialogManager._container, 
		{ width : "400px",
		  //fixedcenter : true,
	      draggable : true,
	      //modal : true,
		  visible : true, 
		  monitorresize : false,
		  constraintoviewport : true,
		  buttons : this.buttons
		 } );
		 
	var scrollTop = document.documentElement.scrollTop;
		 
	widget.render();
	
	MTVN.DialogManager.showMask(widget, scrollTop);
	
	widget.show();
	
	return widget;
*/
	return null;
}
