//******************
//* Element Extras *
//******************
Element.implement({
	// Element.toFormObject
	toFormObject : function(){
		var o = {};
		this.getElements('input,textarea,button').each(function(el){
			if ((el.type == 'checkbox' || el.type == 'radio') && el.checked){
				o[el.name] = el.value;
			}else if (el.get('richtext') == 'initialized' && typeof tinyMCE != 'undefined'){
				tinyMCE.getInstanceById(el.get('id')).save();
				o[el.name] = el.value;
			}else if (el.type != 'checkbox' && el.type != 'radio')
				o[el.name] = el.value;
		})
		return o;
	},
	
	showErrors : function(errors){
		this.getElements('.error').each(function(e){e.removeClass('error')});
		this.getElements('.message').each(function(e){e.addClass('hide')});
		for(field in errors){
			var element = this.getElement('[name='+field+']');
			if (!element)
				continue;
			var errorMessage = this.getElement('.message[errorfor='+field+']');
			if (!errorMessage){
				errorMessage = new Element('p',{'class':'message',errorfor:field});
				errorMessage.inject(element,'before');
			}
			var dd = element.getParent();
			while (dd.get('tag') != 'dd')
			 	dd = dd.getParent();

			errorMessage.set('text',errors[field]);
			errorMessage.removeClass('hide');
			dd.addClass('error');
			dd.getPrevious().addClass('error');
		}
		
		alert(errors._all.join('\n'));
	},
	
	
	toRichTextarea : function(options){
		if (!this.get('tag').match(/^(div|textarea)$/))
			throw this.get('tag')+' cannot be turned into a rich textarea.';
		if (typeof tinyMCE == 'undefined')
			throw 'TinyMCE is not included.';
		if (this.get('richtext') == 'initialized')
			return;
			
		if (!this.get('id'))
			this.set('id', 'richtext' + Native.UID++);

		tinyMCE.init($merge({
			theme : "advanced",
			skin : "digication",
			mode : "none",
			width : "100%",
			height : "250",
			plugins : "safari,paste,searchreplace,inlinepopups",
			theme_advanced_buttons1 : "undo,redo,|,pasteword,|,search,replace,|,justifyleft,justifycenter,justifyright,justifyfull",
			theme_advanced_buttons2 : "forecolor,fontselect,fontsizeselect,|,bold,italic,underline,strikethrough,|,bullist,numlist,outdent,indent,|,link,unlink",
			theme_advanced_buttons3 : "",
			theme_advanced_fonts : "Arial=arial;Georgia=georgia;Impact=impact;Times New Roman=times;Trebuchet MS=trebuchet;Verdana=verdana;Webdings=webdings",
			theme_advanced_toolbar_location : "top",
			theme_advanced_toolbar_align : "left",
			button_tile_map : true,
			cleanup: true,
			convert_urls : false,
			auto_reset_designmode : true,
			debug : false,
			convert_fonts_to_spans : true, 
			auto_focus : this.get('id'),
			inlinepopups_skin:"digication",
			entity_encoding : 'numeric'
		},options));
		
		tinyMCE.execCommand('mceAddControl', false, this.get('id'));
		this.set('richtext','initialized');
	},
	
	removeRichTextarea : function(){
		if (!this.get('tag').match(/^(div|textarea)$/))
			throw this.get('tag')+' cannot be turned into a rich textarea.';
		if (typeof tinyMCE == 'undefined')
			throw 'TinyMCE is not included.';
		if (this.get('richtext') != 'initialized')
			return;

		tinyMCE.execCommand('mceRemoveControl', false, this.get('id'));
		this.erase('richtext');
	},
	
	destroyGracefully : function(){
		this.morph({
			opacity : 0,
			height : 0
		}).retrieve('morph').chain(this.destroy.bind(this));
	},
	
	setClass : function(klass,bool){
		if (bool)
			this.addClass(klass);
		else
			this.removeClass(klass);
	}
});


//*****************
//* String Extras *
//*****************
String.implement({
	// String.truncate
	// thank you smarty truncate
	truncate : function(length,etc,break_words,middle){
		length = length || 80;
		etc = etc || '...';
		break_words = break_words || false;
		middle = middle || false;
		
	    if (length == 0)
	        return '';
	
		var s = this;

	    if (this.length > length) {
	        length -= etc.length;
	        if (!break_words && !middle) {
	            s = this.substr(0,length+1).replace(/\s+?(\S+)?$/,'');
	        }
	        if(!middle) {
	            return s.substr(0, length)+etc;
	        } else {
	            return this.substr(0, length/2) + etc + this.substr(-length/2);
	        }
	    } else {
	        return s;
	    }
	},
	
	// String.phpDtsToString
	phpDtsToString : function(format){
		var time = (this.toInt() * 1000) + '';
		return time.dtsToString(format);
	},
	
	// String.dtsToString
	// ---------- Day ----------
	// d	Day of the month, 2 digits with leading zeros	01 to 31
	// D	A textual representation of a day, three letters	Mon through Sun
	// j	Day of the month without leading zeros	1 to 31
	// l	(lowercase 'L')	A full textual representation of the day of the week	Sunday through Saturday
	// N	ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0)	1 (for Monday) through 7 (for Sunday)
	// S	English ordinal suffix for the day of the month, 2 characters	st, nd, rd or th. Works well with j
	// w	Numeric representation of the day of the week	0 (for Sunday) through 6 (for Saturday)
	// z	The day of the year (starting from 0)	0 through 365
	// --- Week ---
	// not yet supported: %W	ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0)	Example: 42 (the 42nd week in the year)
	// ---------- Month ----------
	// F	A full textual representation of a month, such as January or March	January through December
	// m	Numeric representation of a month, with leading zeros	01 through 12
	// M	A short textual representation of a month, three letters	Jan through Dec
	// n	Numeric representation of a month, without leading zeros	1 through 12
	// t	Number of days in the given month	28 through 31
	// ---------- Year ----------
	// L	Whether it's a leap year	1 if it is a leap year, 0 otherwise.
	// not yet supported: o	ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0)	Examples: 1999 or 2003
	// Y	A full numeric representation of a year, 4 digits	Examples: 1999 or 2003
	// y	A two digit representation of a year	Examples: 99 or 03
	// ---------- Time ----------
	// a	Lowercase Ante meridiem and Post meridiem	am or pm
	// A	Uppercase Ante meridiem and Post meridiem	AM or PM
	// B	Swatch Internet time	000 through 999
	// g	12-hour format of an hour without leading zeros	1 through 12
	// G	24-hour format of an hour without leading zeros	0 through 23
	// h	12-hour format of an hour with leading zeros	01 through 12
	// H	24-hour format of an hour with leading zeros	00 through 23
	// i	Minutes with leading zeros	00 to 59
	// s	Seconds, with leading zeros	00 through 59
	// u	Milliseconds (added in PHP 5.2.2)	Example: 54321
	// ---------- Timezone ----------
	// not yet supported: e	Timezone identifier (added in PHP 5.1.0)	Examples: UTC, GMT, Atlantic/Azores
	// not yet supported: I (capital i)	Whether or not the date is in daylight saving time	1 if Daylight Saving Time, 0 otherwise.
	// not yet supported: O	Difference to Greenwich time (GMT) in hours	Example: +0200
	// not yet supported: P	Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3)	Example: +02:00
	// not yet supported: T	Timezone abbreviation	Examples: EST, MDT ...
	// not yet supported: Z	Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive.	-43200 through 50400
	// ---------- Full Date/Time ----------
	// not yet supported: c	ISO 8601 date (added in PHP 5)	2004-02-12T15:19:21+00:00
	// not yet supported: r	» RFC 2822 formatted date	Example: Thu, 21 Dec 2000 16:01:07 +0200
	// U	Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)	See also time()
	dtsToString : function(format){
		var days = {
			short : ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
			full : ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
		};
		var months = {
			short : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
			full : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
			days : [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
		};
		
		var pad = function(num){
			return (num < 10) ? '0'+num : num;
		};
		
		var date               = new Date();
		date.setTime(this); //thank you IE
		var milliseconds       = date.getMilliseconds();
		var seconds            = date.getSeconds();
		var minutes            = date.getMinutes();
		var hours              = date.getHours();
		var dayOfMonth         = date.getDate();
		var dayOfWeek          = date.getDay();
		var month              = date.getMonth();
		var year               = date.getFullYear();
		var timeInMilliseconds = date.getTime();
		
		//mark replacements
		return format.replace(/(d|D|j|l|n|s|w|z|F|m|M|n|t|L|Y|y|a|A|B|g|G|h|H|i|s|u|U)/g,function(c){
			switch(c){
				//day
				case 'd': return pad(dayOfMonth);
				case 'D': return days.short[dayOfWeek];
				case 'j': return dayOfMonth ;
				case 'l': return days.full[dayOfWeek];
				case 'N': return dayOfWeek+1;
				case 'S': return dayOfMonth.ordinalSuffix();
				case 'w': return dayOfWeek;
				case 'z': return dayOfMonth+months.days.sum(0,month);

				//month
				case 'F': return months.full[month];
				case 'm': return pad(month+1);
				case 'M': return months.short[month];

				case 'n': return month+1;
				case 't': return months.days[month];

				//year
				case 'L': return (((year % 4 == 0) && (year % 100 != 1)) || (year % 400 == 0)) ? '1' :'0';
				case 'Y': return year ;
				case 'y': return pad(year%100);

				//time
				case 'a': return (hours < 12) ? 'am' : 'pm';
				case 'A': return (hours < 12) ? 'AM' : 'PM';
				case 'B': return Math.floor((hours*60*60+minutes*60+seconds)/60/60/24*1000);
				case 'g': return (hours+1)%12;
				case 'G': return hours;
				case 'h': return pad(hours%12);
				case 'H': return pad(hours);
				case 'i': return pad(minutes);
				case 's': return pad(seconds);
				case 'u': return milliseconds;

				//full date time
				case 'U': return Math.floor(timeInMilliseconds/1000);
			}
		});
	}
});


//*****************
//* Number Extras *
//*****************
Number.implement({
	// Number.phpDtsToString
	phpDtsToString : function(format){
		return (this * 1000).dtsToString(format);
	},
	
	// Number.dtsToString
	dtsToString : function(format){
		return (this + '').dtsToString(format);
	},
	
	// Number.ordinalSuffix
	ordinalSuffix : function(){
		var n = Math.abs(this);
		if (n%100-n%10 == 10)
			return 'th';
		switch(n%10){
			case 1:
				return 'st';
			case 2:
				return 'nd';
			case 3:
				return 'rd';
			default:
				return 'th';
		}
	}
	
});


//****************
//* Array Extras *
//****************
Array.implement({
	// Array.sum
	sum : function(begin,end) {
		var a = this.slice(begin || 0, end || this.length);
		var sum = 0;
		for(var i=0;i<a.length;i++){
			sum += parseInt(a[i]);
		}
		return sum;
	}
});



//***************
//* DigiRequest *
//***************
var DigiRequest = new Class({
	createRequest : function(asynchronous){
		this.request = new Request.JSON({
			async : asynchronous,
			onRequest : function(){
				$runaway.start();
			},
			onFailure : function(){
				$runaway.stop();
				$runaway.error();
			},
			onCancel : function(){
				$runaway.stop();
				$runaway.error();
			},
			onException : function(){
				$runaway.stop();
				$runaway.error();
			}
		});
		return this;
	},
	
	//requests
	makeRequest : function(address,extra,handlers){
		handlers = handlers || {};
		extra = $merge({ajax:1},extra);
		this.request.onSuccess = function(json){
			$runaway.stop();
			if (json && json.success)
				(handlers.success || $empty).apply(this,[json.result]);
			else if(json){
				(handlers.error || $empty).apply(this,[json.errors]);
			}else
				alert('An unexpected error occurred.');
		}.bind(this);
		this.request.send.delay(10,this.request,{
			url:address,
			data : ($type(this.getRequestData) == 'function') ? this.getRequestData(extra) : extra
		});
	}
});

//*****************
//* Runaway Timer *
//*****************

var $runaway = {
	timer : [],
	
	alarm : function(){
		$runaway.error();
		$runaway.stop();
	},
	
	start : function(){
		$runaway.timer.push($runaway.alarm.delay(15000,$runaway)); //15 seconds
	},
	
	stop : function(){
		$clear($runaway.timer.shift());
	},
	
	error : function(){
		alert('An error occurred while communicating with the server. Please try again in a moment.\nIf this problem persists, please try refreshing the page.');
	}
}

//**********
//* Fx.Pie *
//**********

Fx.Pie = new Class({
	Extends : Fx,
	
	options: {
		transition: Fx.Transitions.Circ.easeOut,
		duration : 750
	},
	
	initialize: function(element, options) {
		this.element = $(element);
		this.stepSize = this.element.getSize().x - this.element.getStyle('padding-top').toInt() - this.element.getStyle('padding-bottom').toInt() - this.element.getStyle('border-top-width').toInt() - this.element.getStyle('border-bottom-width').toInt();
		if (Browser.Engine.ie)
			this.now = Math.abs(this.element.getStyle('background-position-x').match(/(-?\d+)/)[0]/this.stepSize);
		else
			this.now = Math.abs(this.element.getStyle('background-position').match(/(-?\d+)/)[0]/this.stepSize);
		this.parent(options);
	},
	
	compute: function(from,to,delta){
		return Math.floor((to - from) * delta + from);
	},
	
	
	start: function(to, total) {
		return this.parent(this.now, (arguments.length == 1) ? to.limit(0, 100) : to / total * 100);
	},
	

	set: function(to) {
		this.now = to;
		this.element.setStyle('backgroundPosition', -(to*this.stepSize) + 'px 0px');
		return this;
	}
});

//*********
//* Popup *
//*********

var Popup = new Class({
	options : {
		width : 500,
		height : 500,
		left : 200,
		top : 100,
		name : '',
		resizable : true,
		scrollbars : true,
		location : false
	},
	
	initialize : function(address,options){
		this.options = $merge(this.options, options);
		this.options.name = this.options.name || 'DigicationPopup'+Native.UID++
		
		var windowOptions = '';
		var events = {};
		
		for (var option in this.options){
			if ($type(this.options[option]).match(/(string|number)/))
				windowOptions += option+'='+this.options[option]+',';
			else if ($type(this.options[option]) == 'boolean')
				windowOptions += option+'='+(this.options[option] ? 'yes' : 'no')+',';
			else if ($type(this.options[option]) == 'function' && (/^on[\w]/).test(option)){
				events[option] = this.options[option];
				delete this.options;
			}
		}
		this.window = window.open(address,this.options.name,windowOptions.substr(0,windowOptions.length-1));

		for (var event in events)
			this.window[event] = events[event];

		return this.focus();
	},
	
	focus : function(){
		this.window.focus();
		return this;
	},
	
	close : function(){
		this.window.close();
		return this;
	},
	
	
	load : function(href){
		this.window.location = href;
		return this;
	}
});