prepare = function(options){
	for(i=0;i<options.length;i++){
		if(jQuery.fn[options[i]] == undefined){
			jQuery.fn[options[i]] = function(){};
			i--;
		}
	}
	$.ajaxFileUpload = function(){};
}

jQuery.fn.removeAttention = function(){
	$(this).css("outline", "none");
	$(this).unbind("change");
	$(this).unbind("keydown");
	$(this).removeAttr("attention");
};

jQuery.fn.attention = function(){
    $(this).css("outline", "1px solid #00FF00");
	$(this).animate({"outlineColor":"#FFFFFF"}, 1000);
}

jQuery.fn.memberInput = function(){
	member = $(this).parent().attr("member");
	url = $(this).parent().parent().parent().attr("action");
	$.get(url, { 'function':'save-member', 'id':member, 'field':$(this).attr("name"), 'value':$(this).val() }, function(data){
		data = data.split(",");
		$('div[member='+data[0]+']').find("input[name='"+data[1]+"']").attention();
	});
}

jQuery.fn.memberDelete = function(){
	url = $(this).parent().parent().parent().attr("action");
	member = $(this).parent().attr("member");
	$.get(url, { 'function':'delete-member', 'id':member });
	$(this).parent().fadeOut(500, function(){ $(this).remove(); });
}

$(document).bind("ready", function(){
	prepare(["contextMenu", "tags", "tinymce", "finder", "datepicker"]);
	
	$('.member > input').bind("blur", function(){
		$(this).memberInput();
	});
	
	$('.member > .delete-member').bind("click", function(){
		$(this).memberDelete();
		return false;
	});
	
	$('.add-member').bind("click", function(){
		url = $(this).parent().parent().parent().attr("action");
		name = $(this).parent().find("input[name='name']").val();
		email = $(this).parent().find("input[name='email']").val();
		$(this).parent().find("input[name='name']").val("");
		$(this).parent().find("input[name='email']").val("");
		$.get(url, { 'function':'add-member', 'name':name, 'email':email }, function(data){
			data = data.split(",");
			$('.member:first').clone().insertBefore(".member:last");
			$('.member:last').prev().attr("member", data[0]).find("input[name='name']").val(data[1]).parent().find("input[name='email']").val(data[2]);
			$('.member > input').unbind("blur");
			$('.member > input').bind("blur", function(){
				$(this).memberInput();
			});
			$('.member > .delete-member').unbind("click");
			$('.member > .delete-member').bind("click", function(){
				$(this).memberDelete();
				return false;
			});
		});
		return false;
	});
	
	$('.tinymce-clean').live("click", function(){
		value = $(tinyMCE.activeEditor).html();
		remove = [/ style=[\"]([^\"]+)[\"]/gi, / style=[\']([^\']+)[\']/gi, / mce_style=[\"]([^\"]+)[\"]/gi, / mce_style=[\']([^\']+)[\']/gi, / (class|id)=[\"]([^\"]+)[\"]/gi, / (class|id)=[\']([^\']+)[\']/gi, / style=([^\s\"\'>]+)/gi,  / mce_style=([^\s\"\'>]+)/gi, /<(span|div)>/gi, /<p>(&nbsp;|)<\/p>/gi];
		for(regexp in remove) value = value.replace(remove[regexp], "");
		$(tinyMCE.activeEditor).html(value);
		return false;
		//alert($('#content_ifr').html());
		//this.live("click", function(){
			//alert(1);
			//$(tinyMCE.activeEditor).html(tinymceClean("", $(tinyMCE.activeEditor).html()));
		//});
	});
	
	$('#date').datepicker({ dateFormat: 'MM d yy',  maxDate: '+0d', duration: 300 });
	$('#eventdate').datepicker({ dateFormat: 'MM d yy',  duration: 300 });
	$('#date, #eventdate').keypress(function(){ return false; });
	$('#tag').tags();
	
	$('.highlight').animate({ opacity: 254 }, 2000).animate({ opacity: 0 }, 500, function(){ $(this).css({display:'none'}) });
			   	
	$('.change-slideshow').finder({root:'/uploads', url:'/finder/finder.php', duration:100, type:['jpg', 'gif', 'png'] }, function(event, options){
		$.get($(this).parent().parent().attr("href")+'/process', { 'function':'save-slideshow', 'url':''+options.file, 'id':$(this).parent().find("img").attr("id") });
		$(this).parent().find("img").attr("src", ''+options.file);
		return false;
	});
	
	$('.page-image').finder({root:'/uploads', url:'/finder/finder.php', duration:100, type:['jpg', 'gif', 'png'] }, function(event, options){
		$('#image').val(options.file);
		$('.page-image').html("Click here to change image<br/><img src=\""+options.file+"\" alt=\"\" />");
		return false;
	});
	
	$('.remove-header-image').ask({ data:"<span style=\"color:#FF0000\">Are you sure you want to remove this image?</span>" }, function(){
		 $('#image').val("");
		 $('.page-image').html("Click here to choose an image");
		message("Image removed");
		return false;
	});
	
	$('.new-slideshow').finder({root:'/uploads', url:'/finder/finder.php', duration:100, type:['jpg', 'gif', 'png'] }, function(event, options){
		$.get($(this).attr("href")+'/process', { 'function':'add-slideshow', 'url':''+options.file }, function(data){
			$('.slideshow-image:first').clone().appendTo('.slideshow-editor').find("img").attr("id", data).attr("src", options.file);
		});
		message(options.file+' added to the slideshow');
		
		return false;
	});
	
	$('.delete-slideshow').bind("click", function(){
		$.get($(this).parent().parent().attr("href")+'/process', { 'function':'delete-slideshow', 'id':$(this).parent().find("img").attr("id") });
		message('Image removed from the slideshow');
		$(this).parent().remove();
		return false;
	});
	
	$('.file-manager').finder({root:'/', url:'/finder/finder.php', duration:100, type:'all' }, function(event, options){
		return false;
	});
	
	$('button[role="saveCHANGE"]').bind("click", function(){
		out = $('form').serialize();
		out = out.replace(new RegExp("=", "gi"), ":'").replace(new RegExp("&", "gi"), "',"); 
		result = out.match(new RegExp(":'([0123456789]*)',", "gi"));
		for(i=0;i<result.length;i++) out = out.replace(result[i], result[i].replace(new RegExp("'", "gi"), ""));
		out = "{ 'function':'save-form',"+out+" }";
		alert(out);
		$.get($('form').attr("action")+'/process', out, function(data){
			$('.finder').append("<p style=\"padding:30px;\">"+data+"</p>");
			$('.finder-overlay').click();
		}, 'html');
		return false;
	});
		
	$('.admin-edit-link').live("click", function(){
		window.location.href = $(this).attr("href");
		return false;
	});
	
	$('.remove-post-image').bind("click", function(){
		$(".quicklinks-single-image img").attr("src", '/theme/images/default-image.png');
		$('#image').val('/theme/images/default-image.png');
	});
	
	$('#type').bind("change", function(){
		if($(this).val() != "Event"){
			$('.event-details').css("display", "none");
		}else{
			$('.event-details').css("display", "block");
		}
	});
	
	if($('#type').val() != "Event"){
		$('.event-details').css("display", "none");
	}
	
	$('.more-news').bind("click", function(){
		 $.get($(this).attr("href"), { 'function':'more_news', 'date':$('.news-post:last').attr("date"), 'id':$('.news-post:last').attr("news") }, function(data){
			data = data.split("###");
			for(news in data){
				if(data[news]!="") $('.news-post:last').after(data[news]).slideUp(0).slideDown(500);	
			}
			$('.news-post:last').after("");
		});
		return false;
	});
	
	$('.delete-page').ask({ data:"<span style=\"color:#FF0000\">Are you sure you want to delete this page?</span> This can not be undone" }, function(){
		 $.get($(this).attr("page"), { 'id':$(this).attr("id") }, function(data){
			data = data.split("#");
			if(data[0] == "true"){
				message(data[1], data[2]);
			}
		});
		return false;
	});
	
	$('.delete-post').ask({ data:"<span style=\"color:#FF0000\">Are you sure you want to delete this post?</span> This can not be undone" }, function(){
		 $.get($(this).attr("href"), { 'id':$(this).attr("id"), 'function':'delete' }, function(data){
			data = data.split("#");
			if(data[0] == "true"){
				message(data[1], data[2]);
			}
		});
		return false;
	});
	
	$('.friendly').live("keyup", function(e){
		value = $(this).friendly();
		$(this).attr("value", value);
	});
	
	$('#title, #keywords, #description').bind("keyup", function(){
		if($(this).attr("value") == ""){
			$(this).css("border", "1px solid #F00");
		}else{
			$(this).css("border", "1px solid #CCC");
		}
	});
	
	$('#alias').bind("keyup", function(){
		if($(this).attr("value") == ""){
			$(this).css("border", "1px solid #F00");
			$(this).css("border-left", "none");
			$("#disabled-url").css("border", "1px solid #F00");
			$("#disabled-url").css("border-right", "none");
		}else{
			$(this).css("border", "1px solid #CCC");
			$(this).css("border-left", "none");
			$("#disabled-url").css("border", "1px solid #CCC");
			$("#disabled-url").css("border-right", "none");
		}
	});

	$('#title').keyup(function(e){
		value = $('#title').friendly();
		if(value[value.length-1] == "-") value = value.substring(0, value.length-1);

		$('#alias').attr("value", value.toLowerCase());
		$('#alias').keyup();
	});
	
	$('#alias').keyup(function(e){
		value = $(this).friendly();
		$('#alias').attr("value", value.toLowerCase());
	});
	
	$('#content').tinymce({
		// Location of TinyMCE script
		script_url : '/scripts/jscripts/tiny_mce/tiny_mce.js',
		
		// General options
		theme : "advanced",
		plugins : "tinyclean,finderdownload,finderimage,safari,pagebreak,style,layer,table,save,advhr,advimage,imagebrowser,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
		// Theme options
		theme_advanced_buttons1 : "undo,redo,|,bold,italic,formatselect,bullist,blockquote,|,link,unlink,image,code,preview,finderdownload,finderimage,tinyclean",
		theme_advanced_buttons2 : "",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "center",
		theme_advanced_statusbar_location : "none",
		theme_advanced_resizing : true,
		
		// Example content CSS (should be your site CSS)
		content_css : "/theme/tinymce.css",
		
		// Drop lists for link/image/media/template dialogs
		template_external_list_url : "lists/template_list.js",
		external_link_list_url : "lists/link_list.js",
		external_image_list_url : "lists/image_list.js",
		media_external_list_url : "lists/media_list.js",
		
		// Replace values for the template plugin
		template_replace_values : {
			username : "Some User",
			staffid : "991234"
		}
	});
	
	if($('.news-post').length > 0){
		$(window).bind("scroll", function(){
			if($(window).scrollTop() == ($(document).height()-$(window).height())){
				$('.more-news').click();
			}
		});
	}
	
	$("form").not(".basic").bind("submit", function(){
		$.ajax({
			type: "POST",
			url: $(this).attr("action"),
			data: $(this).serialize(),
			success: function(data){
				data = data.split("#");
				if(data[0] == "true"){
					message(data[1], data[2]);
				}else if(data[0] == "false"){
					message(data[1], data[2]);
				}else{
					message(data[0]);
				}
			}
		});
		return false;
	});
});