// utility function to set the value for a <select> box
Element.implement({
	setSelected: function(value) {
		var options = this.getElements('option');
		options.each(function(option,index) {
			if(option.get('value') == value) this.selectedIndex = index;
		}.bind(this));
	}
});

/*	---------------------------------------------------------------------------
	CLASS:		Filter
	AUTHOR:		Ryan J. Salva, ryan@capitolmedia.com

	ABOUT:		Used to filter a list of items as you type
*/

var Filter = new Class({
	Implements: [Options,Events],
	options: {
		parentSelector: false,
		show: $empty,
		hide: $empty
	},
	initialize: function(input, els, options) {
		this.setOptions(options);
		this.input = $(input);
		this.els = els;
		this.input.addEvent('keyup',function(e) {
			this.filter(e.target.value);
		}.bind(this));
		if (Browser.Engine.trident) {
			this.display = 'block'; // IE doesn't understand 'table-row'
		} else {
			this.display = (this.options.parentSelector == 'tr')?'table-row':'block';
		}
	},
	filter: function(str) {
		if (str != '') {
			str = str.escapeRegExp();
			this.els.each(function(el,index) {
				var hide = (this.options.parentSelector)?el.getParent(this.options.parentSelector):el;
				if (el.get('text').test(str,'i')) {
					hide.setStyles({
						'display':this.display,
						'color':'#000000' // safari and IE cannot remove options dynamically, so we just "dim" the non-matching options
					});
				} else {
					hide.setStyles({
						'display':'none',
						'color':'#cccccc'
					});
				}
			}.bind(this));
		} else {
			this.els.setStyles({
				'display':this.display,
				'color':'#000000'
			});
		}
	}
});

var Blinds = new Class({

	Implements: [Options,Events],
	options: {
		alwaysShow: false,
		showMany: false,
		show: $empty,
		hide: $empty
	},
	initialize: function(togglers, elements, options) {
		this.setOptions(options);
		this.togglers = togglers;
		this.elements = elements;
		this.containers = [];
		
		if (this.togglers.length == this.elements.length) {
			// wrap each element in a container
			this.elements.each(function(el,index) {
				this.add(this.togglers[index],el);
			}.bind(this));
		}
	},
	show: function(index) {
		this.fireEvent('onShow',[this.togglers[index], this.elements[index]]);
		this.containers[index].getElements('select,textarea').setStyle('display','block');
		this.containers[index].morph({
			'height':this.elements[index].getSize().y,
			'opacity':1
		});
		this.togglers[index].addClass('Active');
		
		if (!this.options.showMany) {
			this.containers.each(function(el,i) {
				if (index!=i) this.hide(i);
			}.bind(this));
		};

	},
	hide: function(index) {
		this.fireEvent('onHide',[this.togglers[index], this.elements[index]]);
		this.containers[index].morph({
			'height':0,
			'opacity':0
		});
		this.containers[index].getElements('select,textarea').setStyle('display','none');
		this.togglers[index].removeClass('Active');
	},
	add: function(toggler,el) {
		var index = this.containers.length;
		var div = new Element('div',{
			'styles':{
				'opacity':0,
				'height':0,
				'overflow':'hidden'
			}
		});
		div.replaces(el);
		div.adopt(el);
		
		this.containers.include(div);
		this.togglers.include(toggler);
		this.elements.include(el);
		el.getElements('select,textarea').setStyle('display','none');

		toggler.addEvent('click',function(e) {
			(div.getSize().y == 0)?this.show(index):this.hide(index);
		}.bind(this));
	}
});


/*	---------------------------------------------------------------------------
	CLASS:		Pop
	AUTHOR:		Ryan J. Salva, ryan@capitolmedia.com
	HISTORY:	06/21/08 - v1.0

	ABOUT:		Displays a pop up to the right of lists on controlpanel views
*/

var Pop = new Class({
	Implements: Options,
	options: {
		className: 'Pop',
		onComplete: Class.empty,
		onStart: Class.empty
	},
	initialize: function(el,pop,options){
		this.setOptions(options);
		this.el = el;
		this.pop = pop;
		$$('body')[0].adopt(this.pop);
		this.el.addEvent('mouseenter',this.show.bindWithEvent(this));
		this.el.addEvent('mouseleave',this.hide.bindWithEvent(this));
	},
	show: function(e) {
		var coord = this.el.getCoordinates();
		this.pop.setStyles({
			'display':'block',
			'opacity': 0,
			'position': 'absolute',
			'left': coord.left + coord.width + 10,
			'top': coord.top
		});
		this.pop.tween('opacity',1); 
	},
	hide: function() {
		this.pop.setStyle('display','none');
	}
});



/*	---------------------------------------------------------------------------
	CLASS:		FormTip(selector[,options]);
	OPTIONS:	className: CSS class given to each tip (default: 'FormTip')
	EVENTS:		onComplete
				onStart
	AUTHOR:		Ryan J. Salva, http://www.capitolmedia.com
	LICENSE:	MIT License, <http://en.wikipedia.org/wiki/MIT_License>	
	REVISED:	January 2008
	EXAMPLE:	<input type="text" name="FooBar" title="Please provide your full name" />
				var tip = new FormTip('input[title]');
*/
var FormTip = new Class({
	Implements: Options,
	options: {
		className: 'FormTip',
		onComplete: $empty,
		onStart: $empty
	},
	initialize: function(selector,options){
		this.setOptions(options);
		this.els = $$(selector);
		this.els.each(function(el,index){
			el.addEvent('focus',this.show.bindWithEvent(this));
			el.addEvent('blur',this.hide.bindWithEvent(this));
		}.bind(this));
	},
	show: function(e) {
		var e = new Event(e);
		var el = e.target;
		if ($type(el) != 'element') return false;
		var title = el.getAttribute('title');
		if (!$defined(title)) return false;
		var pos = el.getPosition(el.getOffsetParent());
		var width = el.getWidth();
		this.tip = new Element('div',{
			'class':this.options.className,
			'styles':{
				'opacity': 0,
				'position': 'absolute',
				'left': pos.x + width,
				'top': pos.y,
				'z-index':10
			},
			'text':title
		});
		this.tip.inject(el.getParent(),'inside');
		this.tip.tween('opacity',1); 
	},
	hide: function() {
		this.tip.destroy();
	}
});

/*	---------------------------------------------------------------------------
	CLASS:		Tabs
	AUTHOR:		Ryan J. Salva, ryan@capitolmedia.com

	ABOUT:		Creates tabbed property panels 
*/

var Tabs = new Class({
	Implements: Options,
	options: {
		classPrefix: 'Panel'
	},
	initialize: function(panels, options) {
		this.setOptions(options);
		if (panels.length <= 0) return false;
		
		this.panels = panels;
		this.panels.setStyle('display','none');
		
		this.tabs = [];
		this.panels.each(function(el,index) {
			var tab = new Element('span',{
				'class':this.options.classPrefix+'Tab',
				'text':el.get('title'),
				'events':{
					'click':function(e){
						e.stop();
						this.activate(el,e.target);
					}.bindWithEvent(this)
				}
			});
			this.tabs.include(tab);
		}.bind(this));
		
		this.container = new Element('div',{
			'class':this.options.classPrefix+'Container',
			'styles':{
				'overflow':'hidden',
				'height':0
			}
		});
		this.container.inject(this.panels[0],'before');
		this.panels.each(function(el,index) {
			this.container.adopt(el);
		}.bind(this));
		
		this.tabs.each(function(el,index){
			el.inject(this.container,'before');
		}.bind(this));
		
		this.activate(this.panels[0],this.tabs[0])

		
	},
	
	activate: function(panel,tab){
		this.panels.removeClass(this.options.classPrefix+'Active');
		panel.addClass(this.options.classPrefix+'Active');
		
		this.panels.setStyle('display','none');
		panel.setStyle('display','block');
		
		this.tabs.each(function(el,index){
			el.removeClass(this.options.classPrefix+'Active');
		}.bind(this));
		tab.addClass(this.options.classPrefix+'Active');
		
		this.container.tween('height',panel.getSize().y);
	}
});

/*	---------------------------------------------------------------------------
	CLASS:		FormHelper
	AUTHOR:		Ryan J. Salva, ryan@capitolmedia.com

	ABOUT:		Cleans up form text input within the control panel
*/

var FormHelper = new Class({
	Implements: Options,
	options: {
	},
	initialize: function(form, options) {
		this.setOptions(options);
		this.form = form;
		this.elements = $A(this.form.elements);
		this.elements.each(function(el,index) {
			el = $(el);
			switch(el.tagName.toLowerCase()) {
				case 'input':
					if (el.get('type') == 'text') {
						el.addEvent('blur',function(e) {
							this.clean(el);
						}.bindWithEvent(this));
					}
					break;
				case 'select':
					break;
				case 'textarea':
					break;
				default:
					break;
			}
		}.bind(this));
	},
	clean: function(el){
		var str = el.value;
		if (el.hasClass('URI')) str = this.URI(str);
		if (el.hasClass('StripPunctuation')) str = this.stripPunctuation(str);
		el.value = str;
	},
	URI: function(str) {
		str = str.replace(/[^A-Za-z0-9\s-]/g,''); // remove non-character entities from the file name
		str = str.clean().replace(/\s/g,'-'); // replace spaces with hyphens
		return str;
	},
	stripPunctuation: function(str) {
		str = str.replace(/[^A-Za-z0-9\s-]/g,''); // remove non-character entities from the file name
		return str;
	}
});


//	---------------------------------------------------------------------------
//	CLASS:		Modal();
//	OPTIONS:	speed: the transition speed (default:500)
//				maskColor: the background color of the mask (default: black)
//				width: default width of the dialog box (default:400px)
//				height: default height of the dialog box (default: auto)
//				classPrefix: used to define unique classes for each dialog box (default: "Modal")
//				onHide: event
//				onShow: event
//				onStart: event
//	AUTHOR:		Ryan J. Salva, http://www.capitolmedia.com
//	REVISED:	January 2008

Modal = new Class({
	Implements: [Events, Options],
	options: {
		speed: 200,
		maskColor: '#000000',
		width: 'auto',
		height: 'auto',
		classPrefix: 'Modal',
		onHide: Class.empty,
		onShow: Class.empty,
		onStart: Class.empty
	},
	initialize: function(options) {
		this.setOptions(options);
		this.isShowing = false;
		var classPrefix = this.options.classPrefix;
		this.mask = new Element('div', {
			'class':classPrefix+'Mask',
			'styles':{
				'position':'absolute',
				'top': 0,
				'left': 0,
				'opacity': 0,
				'height': (window.getHeight() > window.getScrollHeight()) ? window.getHeight() : window.getScrollHeight(),
				'width': '100%',
				'background':this.options.maskColor,
				'z-index': 9999
			}
		});
		this.pop = new Element('div',{
			'class':classPrefix+'Pop',
			'styles':{
				'position': 'absolute',
				'visibility': 'hidden',
				'width': '100%',
				'margin': 0,
				'z-index': 10000
			}
		});
		this.container = new Element('div',{
			'class':classPrefix+'Container',
			'styles':{
				'margin':'0 auto'
			}
		});
		this.mask.set('tween',{duration:this.options.speed});
		this.pop.set('tween',{duration: this.options.speed});
		
		this.fireEvent('onStart');
	},
	show: function(el, title) {
		var classPrefix = this.options.classPrefix;
		switch($type(el)) {
			case 'element':
				this.el = new Element('div',{'styles':{'height':this.options.height}}).adopt(el);
				break;
			case 'string':
				this.el = new Element('div',{'styles':{'height':this.options.height}}).set('html', el);
				break;
			default:
				return false;
				break;
		}
		
		if(this.isShowing) {
			this.container.adopt(title, message);
		} else {
			window.addEvent('keydown', function(event) {
				if(event.key == 'esc') this.hide();
			}.bind(this));
			
			$$('object', 'select').setStyle('visibility', 'hidden');
			
			$$('body').adopt(this.mask, this.pop);
			this.container.adopt(this.el);
			this.container.inject(this.pop, 'inside').setStyle('width', this.options.width);
		}
		
		this.pop.setStyles({
			'top': window.getScroll().y - this.pop.getSize().y,
			'visibility':'visible'
		});

		this.mask.tween('opacity',0.8);
		var slideTo = ((window.getSize().y - this.container.getSize().y) / 2 + window.getScroll().y);
		this.pop.tween('top',slideTo);
		this.periodical = this.update.periodical(100, this);
		this.isShowing = true;
		this.fireEvent('onShow');
	},
	update: function() {
		var slideTo = ((window.getSize().y - this.container.getSize().y) / 2 + window.getScroll().y);
		this.pop.tween('top',slideTo);
		var h = (window.getSize().y > window.getScrollSize().y) ? window.getSize().y : window.getScrollSize().y;
		this.mask.setStyle('height', h);
	},
	hide: function() {
		$$('object', 'select').setStyle('visibility', 'visible');
		$clear(this.periodical);
		var slideTo = window.getScroll().y - this.pop.getSize().y;
		this.pop.dispose();
		this.mask.tween('opacity',0);
		this.isShowing = false;
		this.fireEvent('onHide');
	}
});

/*	---------------------------------------------------------------------------
	CLASS:		CalendarEvents
	AUTHOR:		Ryan J. Salva, ryan@capitolmedia.com

	ABOUT:		Used strictly for the events control panel
*/

var CalendarEvents = new Class({
	Implements: [Options,Events],
	options: {
		onFail: $empty,
		onSuccess: $empty
	},
	initialize: function(form, options) {
		this.setOptions(options);
		
		// create an array for the event data
		this.data				= [];
		
		// capture all the form elements
		this.form				= $('EditEvent');
		this.event_id			= $('event_id');
		this.title				= $('title');
		this.message			= $('message');
		this.start_date			= $('start_date');
		this.end_date			= $('end_date');
		this.all_day			= $('all_day');
		this.command			= $('command');
		this.removerestore_url	= $('removerestore_url');
		this.repeat_interval	= $('repeat_interval');
		this.repeat_count		= $('repeat_count');
		this.repeat_unit		= $('repeat_unit');
		this.page_id			= $('page_id');
		this.calendar_id		= $('calendar_id');
		
		// create an instance of our modal dialog box
		this.modal = new Modal({width:550});
		
		// show the "Edit Event" form when a user clicks on an event title
		$$('a[event]').addEvent('click',function(e) {
			e = new Event(e);
			e.stop();
			this.show(e.target.get('event').toInt());
		}.bind(this));

		// show the "Create Event" form when a user clicks on a date
		$$('a[date]').addEvent('click',function(e) {
			e = new Event(e);
			e.stop();
			this.show(0);
		}.bind(this));
		
		// show the "Create Event" modal when user clicks on the "new event" button
		$('CreateEvent').addEvent('click',function() {
			this.show(0);
		}.bind(this));
		
		// auto-format the start and end date 
		$('start_date').addEvent('blur',this.formatDate);
		$('end_date').addEvent('blur',this.formatDate);
	},
	
	show:function(event_id) {
		this.update(event_id);
		this.modal.show(this.form);
	},
	
	update:function(event_id) {
		var E = null;
		for (i=0;i<this.data.length;i++) {
			if (this.data[i].event_id == event_id) {
				E = this.data[i];
				break;
			}
		};
		
		if (E != null) {
		
			// user selected an existing event, update the form with event values
			this.event_id.value				= E.event_id;
			this.title.value				= E.title;
			this.message.value				= E.message;
			this.start_date.value			= Date.parse(E.start_date).toString('dddd, MMMM dd, yyyy h:mm tt');
			this.end_date.value				= Date.parse(E.end_date).toString('dddd, MMMM dd, yyyy h:mm tt');
			this.all_day.checked			= ('E.all_day' == 'yes')?true:false;
			this.command.value				= 'EditEvent';
			this.removerestore_url.set('href',E.removerestore_url);
			this.removerestore_url.set('text',E.removerestore_str);
			this.removerestore_url.set('class',E.removerestore_str);
	
			this.repeat_interval.setSelected(E.repeat_interval);
			this.repeat_count.setSelected(E.repeat_count);
			this.repeat_unit.setSelected(E.repeat_unit);
			this.page_id.setSelected(E.page_id);
			this.calendar_id.setSelected(E.calendar_id);
			
		} else {
		
			// event doesn't exist, update the form with null values so we can create a new event
			this.event_id.value				= '';
			this.title.value				= '';
			this.message.value				= '';
			this.start_date.value			= ''
			this.end_date.value				= '';
			this.all_day.checked			= false;
			this.repeat_interval.value		= 0;
			this.repeat_count.value			= 0;
			this.command.value				= 'CreateEvent';
			this.removerestore_url.set('class','Hidden');
	
			this.repeat_unit.setSelected('day');
			this.page_id.setSelected('');
			this.calendar_id.setSelected('');
		}
	},
	
	formatDate: function(e) {
		e = new Event(e);
		el = e.target;
		var date = Date.parse(el.value);
		if (date == null) {
			el.value = '';
		} else {
			el.value = date.toString('dddd, MMMM dd, yyyy h:mm tt');
		}
	}
});


/*	---------------------------------------------------------------------------
	CLASS:		ImageGroup
	AUTHOR:		Ryan J. Salva, ryan@capitolmedia.com

	ABOUT:		Used strictly for banner/image content creation pages
*/

var ImageGroup = new Class({
	initialize: function(image_group, image, json, preview, options) {
		this.image_group = $(image_group);
		this.image = $(image);
		this.json = json;
		this.preview = $(preview);

		var group_id = null;
		// populate the image_group select box with values
		this.json.each(function(group,index) {
			var el = new Element('option',{'value':group.id,'text':group.name});
			this.image_group.adopt(el);
			group.images.each(function(image) {
				if (image.selected) {
					el.setAttribute('selected','selected');
					group_id = group.id;
				}
			});
		}.bind(this));
		
		// update the value select box when a user selects a new image_group
		this.image_group.addEvent('change',function(e) {
			e = new Event(e);
			this.update(e.target.value);
		}.bind(this));
		
		this.update(group_id);
	},
	removeAll: function() {
		this.image.getElements('option').dispose();
		this.preview.getElements('img').setStyle('display','none');
	},
	update: function(group_id) {
		this.removeAll();
		if (!$defined(group_id)) return false;

		$('Preview'+this.image_group.value).setStyle('display','block');	

		var i; // counter
		for (i=0;i<this.json.length;i++) {
			if (this.json[i].id == group_id) {
				this.json[i].images.each(function(image,i) {
					var el = new Element('option',{'value':image.id,'text':image.type});
					if (image.selected) el.setAttribute('selected','selected');
					this.image.adopt(el);
				}.bind(this));
				break;
			}
		}
	}
});


/*	---------------------------------------------------------------------------
	CLASS:		MenuContent
	AUTHOR:		Ryan J. Salva, ryan@capitolmedia.com

	ABOUT:		Used strictly for menu content creation pages
*/

var MenuContent = new Class({
	initialize: function(menu_list,preview,options) {
		
		this.preview = $(preview);
		this.preview.set('tween',{'link':'cancel','duration':250});
		
		this.menu_list = $(menu_list);
		this.menu_list.addEvent('change',function(e) {
			this.update(e.target);
		}.bind(this));
		this.update(this.menu_list);
	},
	update:function(el) {
		this.preview.getElements('ul').setStyle('display','none');
		var menu;
		if (menu = $('Menu_'+el.value)) {
			menu.setStyle('display','block');
			this.preview.tween('height',menu.getSize().y);
		};
	}
});


window.addEvent('domready',function(e) {
	var blind = new Blinds($$('.Toggler'),$$('.Collapsable'),{'display':0,'showMany':false});
	var formtip = new FormTip('input[title], select[title], textarea[title]');
	$A(document.forms).each(function(el,index){
		var formhelper = new FormHelper(el);
	});
});
