var Base = {
	
	cascadeSelect: function(parent, child, options) {
		options = $.extend({
			autoFocus: true
		}, options || {})
		
		child.data('options', child.find('option[value!=""]').each(function(index, item) {
			var option = $(item);
			var optGroup = option.parent().attr('label');
			
			option.data('parent', optGroup);
		}));
		
		parent.change(function() {
			child.find('optgroup, option[value!=""]').detach();
			
			var selectedOption = parent.find('option:selected');
			if (selectedOption.val() == '') {
				child.data('options').each(function(index, item) {
					var optGroup = child.find('optgroup[label="' + $(this).data('parent') + '"]');
					if (!optGroup.length) {
						optGroup = $('<optgroup/>', {
							label: $(this).data('parent')
						}).appendTo(child);
					}
					optGroup.append(item);
				});
				child.val('');
			}
			else {
				child.append(child.data('options').filter(function(index, item){
					return $(this).data('parent') == selectedOption.text();
				}));
			}
			
			if (options.autoFocus && parent.is(':focus')) {
				child.focus();
			}
		}).change();
	},
	
	datepicker: function(options){
	//	$('.input.date select:nth-child(3n):not(:disabled)')
		var year = $('.input.date select:nth-child(3n)');
		year.after('<input type="text" class="datepicker" />')
			.parent()
				.css({
					'position'	: 'relative',		
				});
		
		$('.datepicker')
			.datepicker($.extend({
				//properties
				dateFormat: 'yy-mm-dd',
				buttonImage: App.url('/asset/img/calendar.gif'),
				buttonImageOnly: true,
				duration: 'slow',
				showOn: 'button',
				showAnim: 'slideDown',
				minDate: new Date(year.find('option:not(:empty)').min(), 0, 1),
				maxDate: new Date(year.find('option:not(:empty)').max(), 11, 31),
				//callbacks
				onSelect: function(sel_date) {
					var newDate = sel_date.split('-');
					
					$(this).siblings('select').each(function(){
						id = $(this).attr('id');
						if (id.substring(id.length - 3, id.length) == 'Day') 
							$(this).val(newDate[2]);
						else 
							if (id.substring(id.length - 5, id.length) == 'Month') 
								$(this).val(newDate[1]);
							else 
								if (id.substring(id.length - 4, id.length) == 'Year') 
									$(this).val(newDate[0]);
					});
				},
				beforeShow: function() {
					var year = '';
					var month = '';
					var day = '';
					var id = '';
					var datepicker = $(this);
					datepicker.siblings('select').each(function(){
						id = $(this).attr('id');
						if (id.substring(id.length - 3, id.length) == 'Day') {
							day = $(this).val();
						}
						else 
							if (id.substring(id.length - 5, id.length) == 'Month') {
								month = $(this).val();
							}
							else 
								if (id.substring(id.length - 4, id.length) == 'Year') {
									year = $(this).val();
									if (typeof datepicker.datepicker('option', 'maxDate') == 'null') {
										datepicker.datepicker('option', 'maxDate', new Date($(this).children(':last').val(), 11, 31));
									}									
								}
					});
					$(this).val(year + '-' + month + '-' + day);
				}
			}, options || {}));
	},
		
	superfish: function(element, options){
		element.superfish($.extend({
			delay:			500,
			hoverClass:		'hover',
			animation: {
				height:		'toggle'
			},
			autoArrows:		false,
			dropShadows:	false
		}, options || {}));
	},
	
	tableChecker: function() {
		var tableCheckbox = $('.table-checkbox'); 
		tableCheckbox.click(function() {
			$('.tabular tbody th:first-child :checkbox').prop('checked', tableCheckbox.is(':checked'));
		});
	},
	
	photoGallery: function(gallery, options) {
		options = $.extend({
			sortable: false
		}, options || {});
		
		var photos = gallery.find('.photo');		
		photos
			//clickable
			.addClass('clickable')
			.click(function() {
				var checkbox = $(this).find(':checkbox');
				checkbox.attr('checked', !checkbox.is(':checked'));
			})
		
		photos.find(':checkbox')
			.click(function(event){
				event.stopPropagation();
			});
		
		if (options.sortable) {
			photos.append('<a class="dragger" href="#" title="Drag to reorder"></a>');
			photos.find('.dragger').click(function(event){
				event.stopPropagation();
			});
			
			gallery.sortable({
				items		: '.photo',
				handle		: '.dragger',
				containment	: 'parent',
				update		: function(event, ui) {
					var flash = $('#flashMessage');
					if (flash.length) {
						flash.remove();
					}
					flash = $('<div id="flashMessage" class="message notice">The changes to these photos will not be saved until the <strong>Update</strong> button is clicked.</div>')
					flash.prependTo(gallery.parents('form'));
					
					var update = gallery.find('.update');
					if (update.length) {
						update.remove();
					}
					update = $('<li class="update">To reorder photos, drag it then click <button type="submit" name="action" value="reorder_photos" >Update</button></li>');
					
					var remove = gallery.find('.delete');
					remove.before(update);
					
					gallery.find('.photo :input:text').each(function(index, element){
						$(element).val(index);
					});
				}
			});
			gallery.disableSelection();
		}
	},
	
	tinymce: function(options) {
		options = $.extend({
			script_url:	App.url('/asset/js/vendors/tiny_mce/tiny_mce.js'),
			
			skin:			'cirkuit',
			theme:			'advanced',
			relative_urls:	false,
			plugins:		'autolink,spellchecker,safari,pagebreak,style,layer,advimage,advlink,advlist,iespell,inlinepopups,media,contextmenu,fullscreen,paste',
			
			theme_advanced_buttons1: 'bold,italic,strikethrough,|,bullist,numlist,blockquote,|,justifyleft,justifycenter,justifyright,|,link,unlink,pagebreak,|,spellchecker,fullscreen,code,|,help',
			theme_advanced_buttons2: 'formatselect,underline,justifyfull,forecolor,|,pastetext,pasteword,removeformat,|,charmap,|,outdent,indent,|,undo,redo,|,image',
			theme_advanced_buttons3: '',
			
			theme_advanced_toolbar_location:	'top', 
	        theme_advanced_toolbar_align:		'left', 
	        theme_advanced_statusbar_location:	'bottom', 
	        theme_advanced_resizing:			true, 
	        
	        file_browser_callback: function(field_name, url, type, win) {
	        	browserField = field_name;
	            browserWin = win;
	            window.open(App.url('/admin/attachments/index/layout:full'), 'browserWindow', 'modal,width=960,height=720,scrollbars=yes');
	        },
			
			height:		"300", 
	        width:		'100%' 
		}, options || {});
		
		$('.input.tinymce textarea').tinymce(options);
	},
	
	tinymce_selectUrl: function(url) {
		if (url == '') {
			return false;
		}
		url = App.url(url);
		
		field = window.top.opener.browserWin.document.forms[0].elements[window.top.opener.browserField];
		field.value = url;
		if (field.onchange != null) {
			field.onchange();
		}
		window.top.close();
		window.top.opener.browserWin.focus();
	}
};
