
// Create namespace if not existing
if(typeof mt === 'undefined') {
	mt = {	'controllers' : {}, 
			'models' : {}, 
			'extra' : {}
		}
}


// Create a logger wrapper
if(mt.constants && !mt.constants.JSDEBUG){
    if(!window.console) window.console = {};
    var methods = ["log", "debug", "warn", "info"];
    for(var i=0;i<methods.length;i++){
        console[methods[i]] = function(){};
    }
}







// Set some global extra functionality needed
mt.extra = {
	
	// The global listener/event triggerer can span multiple models and controlers that reside on the same page.
		globalListener : {
			functionsToBeCalled : [],

		 	addListener : function(functionToAdd, context){
 			this.functionsToBeCalled.push({"myFunction" : functionToAdd, "myContext" : context});
			},
			triggerEvent : function(eventObj){
	 		
				for (var i = this.functionsToBeCalled.length - 1; i >= 0; i--){
					//console.info(this.functionsToBeCalled[i]);
					this.functionsToBeCalled[i]["myFunction"].call(this.functionsToBeCalled[i]["myContext"], eventObj); 				
				};
			}
		},
	
	// Function to check that there are no crazy characters in the input text
	safeInputText : function(inputString){
		
//		var regExFormat = /^[0-9]{1,3}([.][0-9]{1,2}){0,1}$/i;
//		if(!regExFormat.test(givenPrice)){
	},
	
	userProfileLink : function(user){
		return "<a href='viewProfile.php?member=" + user.userId +"'>" + user.displayName + "</a><br>";
	},
	userProfileLinkInline : function(user){
		return "<a href='viewProfile.php?member=" + user.userId +"'>" + user.displayName + "</a>";
	},
	
	
	/***
	 * Takes a JS date Object and turns it to an ISO 8601 string 
	 * according to UTC 
	 * @param {Object} dateObj JS Date type object
	 */
	jS_UTCDateToISO : function(dateObj){
		var fullUTCYear = dateObj.getUTCFullYear();		
		var UTCMonth = dateObj.getUTCMonth() + 1; // JS date is 0-based
		var fullUTCmonth = UTCMonth < 10 ? '0'+UTCMonth : UTCMonth;
		var fullUTCdate = dateObj.getUTCDate() < 10 ? '0'+dateObj.getUTCDate() : dateObj.getUTCDate();
		var fullUTChours = dateObj.getUTCHours() < 10 ? '0'+dateObj.getUTCHours() : dateObj.getUTCHours();
		var fullUTCminutes = dateObj.getUTCMinutes() < 10 ? '0'+dateObj.getUTCMinutes() : dateObj.getUTCMinutes();
		
		return fullUTCYear + "-" +fullUTCmonth + "-" +fullUTCdate + "T" + fullUTChours + ":" +fullUTCminutes;
	},

	/***
	 * Creates a date object from an ISO8601 date string 
	 * and sets the date and time based on GMT/UTC.
	 * Returns a date object.
	 * @param {String} dateString "yyyy-mm-ddThh:mm",
	 */
	iSOtoJS_UTCDate : function(dateString){
		//NOTE: new Date("ISOdateString") exists but has cross browser issues 
		if(typeof(dateString) !== "undefined" && dateString !== "" && dateString !== null){
				var dateObj  = new Date();
				var UTCyear = dateString.substring(0,4);
				var UTCmonth = dateString.substring(5,7) - 1; // JavaScript stores months as 0-11 
				var UTCdate = dateString.substring(8,10);
				var UTChours = dateString.substring(11,13);
				var UTCminutes = dateString.substring(14,16);
				
				// Set year month and day
				dateObj.setUTCFullYear(UTCyear, UTCmonth, UTCdate);
				
				// Set hours and minutes
				dateObj.setUTCHours(UTChours, UTCminutes);
				return dateObj;
		}
		else {
				console.warn(dateString + " is not a date string");
				return null;
		}
	},
		

		
	createTimeToDeadlineString : function(deadlineDateObj){
			//console.log(deadlineDateObj);
			if(deadlineDateObj instanceof Date){	
				var currentDateTime = new Date();
				var diffInMs = deadlineDateObj - currentDateTime;
				
				// console.log("Local Deadline: " + deadlineDateObj.toLocaleString());
				
				if (diffInMs > 0) {
					var aDayInMs = 1000 * 60 * 60 * 24;
					var numberOfDays = Math.floor(diffInMs / aDayInMs);
					var numberOfHours = Math.round(((diffInMs / aDayInMs) - numberOfDays) * 24);
					var dayString = numberOfDays > 1 ? numberOfDays + " days " : (numberOfDays == 1 ? "1 day " : "");
					var hourString = numberOfHours > 1 ? numberOfHours + " hours" : (numberOfHours == 1 ? "1 hour" : "");
					return dayString + hourString;
				}
				else{
					return "expired";
				}
			}
			else {
				// console.warn("supplied parameter was not a date object");
				return null;
			}
	},
	
	restoreFormatting : function(text){
		if(typeof(text) === "string"){
			return text.replace(/\n/g, "<br>");
		}
		else{
			return text;
		}
	}
	
};


	// Crockfords prototypal inheritance 
	// http://javascript.crockford.com/prototypal.html
	
	if (typeof Object.create !== 'function') {
		Object.create = function(o){
			function F(){
			}
			F.prototype = o;
			return new F();
		};
	}
	
	//Array - Remove - By John Resig (MIT Licensed)
	if (!Array.prototype.remove){
		Array.prototype.remove = function(from, to){
			var rest = this.slice((to || from) + 1 || this.length);
			this.length = from < 0 ? this.length + from : from;
			return this.push.apply(this, rest);
		};
	}
	
	// Array - Index of - By Mozilla
	if (!Array.prototype.indexOf)
	{
	  Array.prototype.indexOf = function(searchElement /*, fromIndex */)
	  {
	    "use strict";
	
	    if (this === void 0 || this === null)
	      throw new TypeError();
	
	    var t = Object(this);
	    var len = t.length >>> 0;
	    if (len === 0)
	      return -1;
	
	    var n = 0;
	    if (arguments.length > 0)
	    {
	      n = Number(arguments[1]);
	      if (n !== n) // shortcut for verifying if it's NaN
	        n = 0;
	      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
	        n = (n > 0 || -1) * Math.floor(Math.abs(n));
	    }
	
	    if (n >= len)
	      return -1;
	
	    var k = n >= 0
	          ? n
	          : Math.max(len - Math.abs(n), 0);
	
	    for (; k < len; k++)
	    {
	      if (k in t && t[k] === searchElement)
	        return k;
	    }
	    return -1;
	  };
	}
	
	try{
		// Extension of jQuery to handle url paramters from 
		// http://jquery-howto.blogspot.com/2009/09/get-url-parameters-values-with-jquery.html 
		$.extend({
		  getUrlVars: function(){
		    var vars = [], hash;
		    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		    for(var i = 0; i < hashes.length; i++)
		    {
		      hash = hashes[i].split('=');
		      vars.push(hash[0]);
		      vars[hash[0]] = hash[1];
		    }
		    return vars;
		  },
		  getUrlVar: function(name){
		    return $.getUrlVars()[name];
		  }
		});
	}
	catch(e){
		// console.error(e);
		}

