// Ozan's Javascript Tool Library
// Basic tools by Ozan Turgut on July 2009
// Dependencies	: none

/***************************************************************************************************/
/********************************************** TOOLS **********************************************/
if (typeof Tool == "undefined") Tool = {};
if (typeof Tool.parse == "undefined") Tool.parse = {};
if (typeof Tool.pattern == "undefined") Tool.pattern = {};
if (typeof Tool.date == "undefined") Tool.date = {};
if (typeof Tool.time == "undefined") Tool.time = {};

//-------------------------------------------- Helpers --------------------------------------------//
Tool.proxy = "/turgut/nimbus/resource/proxy.php";

/**	@name 	Tool.pattern
	@note	Default helper regular expression patterns */
Tool.pattern.URI = /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
Tool.pattern.URI_Query = /(?:^|&)([^&=]*)=?([^&]*)/g;
Tool.pattern.URL = new RegExp("^([a-zA-Z]+://)?([a-zA-Z0-9-]+\\.)+[a-zA-Z0-9-]+[^.](?:\\s|:|/|$|\\?)");
Tool.pattern.Domain = /\w+.(?:\w{1,2}.|com.|org.|net.)\w+$/;

/**	@name	Tool.date
	@note	Default arrays to turn months and days in to natural language form. */
Tool.date.month = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
Tool.date.month_short = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec");
Tool.date.day = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
Tool.date.day_short = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");

Tool.time.second = 1000;
Tool.time.minute = Tool.time.second * 60;
Tool.time.hour = Tool.time.minute * 60;
Tool.time.day = Tool.time.hour *24;
Tool.time.year = Tool.time.day * 365;

/** @name 	time.natural 
	@note	Returns the natural language time: If less than an hour "minutes ago", if less than a day "today at ##:## p.m.", if this year exempt year, else, return time
	@param 	date		Date object to be compared against today
	@param 	prefix		Whether the function should return appropriate prefixes ("on").
	@return string		Formatted time object	*/
Tool.time.natural = function(date, prefix){
	if(!date) return "just now";
	var now = new Date();
	var difference = now.getTime() - (date.getTime());
	var days = difference/Tool.time.day;
	
	if (days < 7){
		if (days < 1){
			if(difference/Tool.time.hour < 1){
				if(difference/Tool.time.minute < 2) return "just now";
				else return (Math.round(difference/Tool.time.minute)) + " minutes ago";
			} else {
				return "today at " + Tool.time.getTime(date, true);		
			}
		} else {
			return (prefix?" on ":"") + Tool.date.day[date.getDay()] + " at " + Tool.time.getTime(date, true);		
		}
	} else {
		return (prefix?" on ":"") + date.getDate() + " " + Tool.date.month[date.getMonth()] + ((date.getFullYear() == now.getFullYear())? "" : " " + date.getFullYear()) + " at " + Tool.time.getTime(date, true);
	}
}

Tool.time.natural_month = function(date, prefix){
	if(!date) return "";
	var now = new Date();
	if(date.getYear() == now.getYear()){
		return (prefix?"in ":"") + Tool.date.month[date.getMonth()];
	} else {
		return (prefix?"in ":"") + Tool.date.month[date.getMonth()] + " " + date.getFullYear();
	}
}

Tool.time.getTime = function(date, suffix){
	var minutes = date.getMinutes();
	var hours = date.getHours();
	if (minutes < 10) minutes = "0" + minutes;
	if(suffix){
		var hour = hours%12;
		if(hour == 0) hour = 12;
		return hour + ":" + minutes + (((hours/12) < 1)?" a.m.": " p.m.");
	} else {
		return hours + ":" + minutes;
	}
}
//------------------------------------------- Functions --------------------------------------------//

Tool.empty_function = function(){};
/** @name 	explode 
	@note	Takes a string and explodes in to an array
	@param 	string		String to be turned in to an array
	@param 	dynomite	String or regexp which will act as the splitting device. Default is spaces.
	@return Array		Array of pieces	*/
Tool.explode = function(string, dynomite) {
	if (typeof string != "string") return [];
	if (!dynomite) dynomite = /\s+/;
	string = Tool.trim(string);
	return string ? string.split(dynomite) : [];
}

Tool.trim = function(string){
	return string.replace(/^\s+|\s+$/g,"");
}

/**	@name	underscorize
	@note	Takes a string and replaces periods and spaces with underscores
	@param	string		String to be underscored
	@return	string		Underscored string
*/
Tool.underscorize = function(string){
	var searchFor = /(\.|\s)/g;
	return Tool.replace(string, searchFor, "_");
}

/**	@name	capitalize
	@note	Takes a string and replaces the first letter with it's capital form
	@param	string		String to be capitalize
	@return	string		Capitalized string
*/
Tool.capitalize = function(string){
	if(!string) return false;
	return string.replace(/^./,string.charAt(0).toUpperCase());
}

/**	@name 	replace
	@note	Takes a string and searches and replaces a variable within it
	@param	string		String to search in
	@param	searchFor	Can be either string or RegExp
	@param	replaceWith
	@return string		The new string with values replaced
*/
Tool.replace = function(string, searchFor, replaceWith){
	if (typeof string != "string") return [];
	if (typeof searchFor == "string") searchFor = new RegExp(searchFor, "g");
	return string.replace(searchFor,replaceWith);
}

/**	@name	is_dblclick
	@note	Works around IE quirks and enables double clicks in iPhone
	@var	timeout		Milliseconds to wait for next click to qualify for double click
	@param 	target		The target being clicked upon
	@return	bool		Returns true if the target has been clicked twice within [timeout] milliseconds. */
Tool.is_dblclick = function(target){
	var timeout = 500;
	if(Tool.is_dblclick.target == target){
		return true;
	} else {
		Tool.is_dblclick.target = target;
		setTimeout(function(){Tool.is_dblclick.target = null},timeout);		
		return false;
	}
}

/**	@name	parse.URI
	@attr	Parts of this code were taken from Steven Levithan's parseURI file (http://blog.stevenlevithan.com/archives/parseuri).
	@note	Takes a URI and parses it in to a URI object using patterns in Tool.pattern
	@param	uri_string		The URI to be parsed
	@return	object			An object containing URI params (anchor, port, host, etc...) */
Tool.parse.URI = function(uri_string){
	if(typeof uri_string != "string"){ return false; }	
	var item = {anchor:null,query:null,file:null,directory:null,path:null,relative:null,port:null,host:null,password:null,user:null,userInfo:null,authority:null,protocol:null,source:null};
	var result = Tool.pattern.URI.exec(uri_string);
	for (x in item)item[x] = result.pop();
	if(item.query){
		item.param = {};
		while(result = Tool.pattern.URI_Query.exec(item.query)) item.param[result[1]] = result[2];
	}
	return item;
};
