/* Catch console.log calls in IE */
if(!window.console){var console={log:function(message){alert(message);}}};

/* Class support (http://ejohn.org/blog/simple-javascript-inheritance/ ) */
(function(){var initializing=false,fnTest=/xyz/.test(function(){xyz;})?/\b_super\b/:/.*/;this.Class=function(){};Class.extend=function(prop){var _super=this.prototype;initializing=true;var prototype=new this();initializing=false;for(var name in prop){prototype[name]=typeof prop[name]=="function"&&typeof _super[name]=="function"&&fnTest.test(prop[name])?(function(name,fn){return function(){var tmp=this._super;this._super=_super[name];var ret=fn.apply(this,arguments);this._super=tmp;return ret;};})(name,prop[name]):prop[name];} function Class(){if(!initializing&&this.init) this.init.apply(this,arguments);} Class.prototype=prototype;Class.constructor=Class;Class.extend=arguments.callee;return Class;};})();

// Simulates PHP's date function
// http://jacwright.com/projects/javascript/date_format
Date.prototype.format=function(format){var returnStr='';var replace=Date.replaceChars;for(var i=0;i<format.length;i++){var curChar=format.charAt(i);if(replace[curChar]){returnStr+=replace[curChar].call(this);}else{returnStr+=curChar;}}return returnStr;};Date.replaceChars={shortMonths:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],longMonths:['January','February','March','April','May','June','July','August','September','October','November','December'],shortDays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],longDays:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d:function(){return(this.getDate()<10?'0':'')+this.getDate();},D:function(){return Date.replaceChars.shortDays[this.getDay()];},j:function(){return this.getDate();},l:function(){return Date.replaceChars.longDays[this.getDay()];},N:function(){return this.getDay()+1;},S:function(){return(this.getDate()%10==1&&this.getDate()!=11?'st':(this.getDate()%10==2&&this.getDate()!=12?'nd':(this.getDate()%10==3&&this.getDate()!=13?'rd':'th')));},w:function(){return this.getDay();},z:function(){return"Not Yet Supported";},W:function(){return"Not Yet Supported";},F:function(){return Date.replaceChars.longMonths[this.getMonth()];},m:function(){return(this.getMonth()<9?'0':'')+(this.getMonth()+1);},M:function(){return Date.replaceChars.shortMonths[this.getMonth()];},n:function(){return this.getMonth()+1;},t:function(){return"Not Yet Supported";},L:function(){return"Not Yet Supported";},o:function(){return"Not Supported";},Y:function(){return this.getFullYear();},y:function(){return(''+this.getFullYear()).substr(2);},a:function(){return this.getHours()<12?'am':'pm';},A:function(){return this.getHours()<12?'AM':'PM';},B:function(){return"Not Yet Supported";},g:function(){return this.getHours()%12||12;},G:function(){return this.getHours();},h:function(){return((this.getHours()%12||12)<10?'0':'')+(this.getHours()%12||12);},H:function(){return(this.getHours()<10?'0':'')+this.getHours();},i:function(){return(this.getMinutes()<10?'0':'')+this.getMinutes();},s:function(){return(this.getSeconds()<10?'0':'')+this.getSeconds();},e:function(){return"Not Yet Supported";},I:function(){return"Not Supported";},O:function(){return(this.getTimezoneOffset()<0?'-':'+')+(this.getTimezoneOffset()/60<10?'0':'')+(this.getTimezoneOffset()/60)+'00';},T:function(){return"Not Yet Supported";},Z:function(){return this.getTimezoneOffset()*60;},c:function(){return"Not Yet Supported";},r:function(){return this.toString();},U:function(){return this.getTime()/1000;}};

Utilities = {
	/**
	 * Bind a function to an object scope
	 *
	 * @param		function		fn				A (usually anonymous) function
	 * @param		object			scope			An object to bind the function to
	 * @param		array			args			[ Optional ] A list of arguments to pass to the function
	 * @param		boolean			override		[ Optional ] If args supplied, should they overwrite the normal arguments or be appended?
	 *
	 * @return		function
	 */
	Bind: function( fn, scope, args, override ) {
		args = jQuery.makeArray( args );

		return function()
			{
				arguments = jQuery.makeArray( arguments );
				if( args ){
					if( override ){
						arguments = args;
					} else {
						for( var i = 0; i < args.length; i++ ){
							arguments.push( args[ i ] );
						}
					}
				}
				return fn.apply( scope, arguments );
			};
	},
	Create:function( type, properties ){
		var element = jQuery( document.createElement( type ) );

		if( typeof properties == 'object' ){
			for( var name in properties ){
				var value = properties[ name ];
				switch( name ){
					case 'css':{
						element.css( value );
						break;
					}
					case 'text':{
						element.attr
						(
							( ( jQuery.browser.mozilla ) ? 'textContent' : 'innerText' ),
							value
						);
						break;
					}
					case 'html':{
						element.append( value );
						break;
					}
					case 'events':{
						for( var event in value ){
							element.bind( event, value[ event ] );
						 }
						 break;
					}
					case 'class':{
						// Convert array to string
						if( typeof value == 'object' ){
							value = value.join( ' ' );
						}
						element.addClass( value );
						break;
					}
					default:{
						element.attr( name, value )
						break;
					}
				}
			}
		}

		return element[0];
	},
	Replace:function(search, replace, subject) {
		// http://kevin.vanzonneveld.net
		// +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +   improved by: Gabriel Paderni
		// +   improved by: Philip Peterson
		// +   improved by: Simon Willison (http://simonwillison.net)
		// +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
		// +   bugfixed by: Anton Ongson
		// +      input by: Onno Marsman
		// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
		// +    tweaked by: Onno Marsman
		// *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
		// *     returns 1: 'Kevin.van.Zonneveld'
		// *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
		// *     returns 2: 'hemmo, mars'

		var f = search, r = replace, s = subject;
		var ra = r instanceof Array, sa = s instanceof Array, f = [].concat(f), r = [].concat(r), i = (s = [].concat(s)).length;

		while (j = 0, i--) {
			if (s[i]) {
				while (s[i] = (s[i]+'').split(f[j]).join(ra ? r[j] || "" : r[0]), ++j in f){};
			}
		};

		return sa ? s : s[0];
	},
	Interpolate:function( keys_values, template ){
		var keys = [];
		var values = [];
		for( key in keys_values ){
			keys.push( '[[' + key  + ']]' );
			values.push( keys_values[ key ] );
		}
		return this.Replace( keys, values, template );
	},
	nl2br:function(str, is_xhtml) {
    // Converts newlines to HTML line breaks
    //
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/nl2br
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Philip Peterson
    // +   improved by: Onno Marsman
    // +   improved by: Atli Þór
    // +   bugfixed by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Maximusya
    // *     example 1: nl2br('Kevin\nvan\nZonneveld');
    // *     returns 1: 'Kevin\nvan\nZonneveld'
    // *     example 2: nl2br("\nOne\nTwo\n\nThree\n", false);
    // *     returns 2: '<br>\nOne<br>\nTwo<br>\n<br>\nThree<br>\n'
    // *     example 3: nl2br("\nOne\nTwo\n\nThree\n", true);
    // *     returns 3: '\nOne\nTwo\n\nThree\n'
    var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '' : '<br>';

    return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ breakTag +'$2');
	},

	Popup:function( title, content, width, height, open, parameters ){

		if( typeof parameters == 'undefined' ){
			parameters = {};
		}
		if( typeof parameters.modal == 'undefined' ){
			parameters.modal = false;
		}

		$( content ).dialog
		(
			{
				title: title,
				width: width,
				height: height,
				autoOpen: open,
				buttons:parameters.buttons,
				modal: parameters.modal
			}
		)
	},
	PopupOpen:function( popup ){
		$( popup ).dialog( 'open' );
	},
	PopupClose:function( popup ){
		$( popup ).dialog( 'close' );
	},
	/**
	 * Get the nearest ancestor of a node, of a given type
	 *
	 * @param		HTMLNode		node			The node
	 * @param		string			node_type		What type of node to look for
	 *
	 * @return		HTMLNode
	 */
	GetNearestAncestor:function( node, node_type ){
		var target = $( node );
		while( target[ 0 ].nodeName != node_type ){
			// Can't go any further, return null
			if( target[ 0 ].nodeName == 'HTML' ){
				return null;
			}
			target = $( target ).parent();
		}
		return target[ 0 ];
	},
	ShowPageInPopup:function( url, title ){
		var preview_wrapper = Utilities.Create
		(
			'div',
			{
				width: '1050px',
				height: viewport_height - 100,
				'class' : 'popup_overlay'
			}
		);

		var iframe_width = 1050;
		var viewport_height = $(window).height();
		var viewport_width = $(window).width();

		var preview_iframe = Utilities.Create
		(
			'iframe',
			{
				src: url,
				width: iframe_width,
				height: viewport_height - 100
			}
		);
		$(preview_wrapper).html( '<div class="title"><h2>' + title + '</h2></div>' ).append( preview_iframe );
		$(document.body).append( preview_wrapper );
		$( preview_wrapper ).overlay
		(
			{
				mask: {
					color: '#000',
					loadSpeed: 200,
					opacity: 0.5
				},
				top: 50,
				left: (viewport_width - iframe_width)/2,
				closeOnClick: false,
				load: true
			}
		);
	}
}

