// remap jQuery to $
(function($){

	var delay = (function(){
		var timer = 0;
		return function(callback, ms){
			clearTimeout (timer);
			timer = setTimeout(callback, ms);
		};
	})();

	function copyToClipboard(text) {
		window.prompt ("Copy to clipboard: Right-click (ctrl+click) and select 'Copy' or Cmd+C (Ctrl+C in Windows)", text);
	}

	//same as $(document).ready();
	$(function() {


		$('nav a.subnav').click(function(){
			$(this).next('ul').addClass('Open');
		});
		
		
		$('.center').each(function(){
			$(this).css({ left: $(this).parent().width()/2  - $(this).width()/2 });
		});
		
		
		$('form#formArtSearch').submit(function(e){
			e.preventDefault();
		});
		$('form#formArtSearch').keyup(function(){
			var regexp = /^[a-zA-Z0-9-_]+$/;
			var search = $('form#formArtSearch').find('input[name=search]').val().toLowerCase();
			var action = $('form#formArtSearch').find('input[name=action]').val().toLowerCase();
			var eID = $('form#formArtSearch').find('input[name=eID]').val().toLowerCase();
			if ( search.search(regexp) != -1 || !search ) {
				delay(function(){
					$('article#exhibitionSearch ul.grid').empty();
					$.ajax({
						type: 'POST',
						url: 'actions.php',
						data: "action="+action+"&search="+search+"&eID="+eID,
						dataType: 'json',
						error: function (XMLHttpRequest, textStatus, errorThrown) { alert('HTTP Error: '+errorThrown+' | Error Message: '+textStatus); console.log(arguments); },
						success: function(data) {
							$.each(data,function(k,v){
								if ( v.wID != '' ) {
									var series = '';
									if ( v.sName ) series = ", "+v.sName;
									$('<li id="w_'+v.wID+'"><img src="img/artworks/170/'+v.wiImage+'" /><p>'+v.wTitle+', '+v.wYear+''+series+'</p><p>by '+v.aFirstName+' '+v.aLastName+'</p><a class="edit" title="Edit this artwork." href="?page=Artworks&amp;aID='+v.aID+'&amp;editArtwork='+v.wID+'"></a><div class="handle" title="Drag to assign this artwork to the exhibition."></div></li>').appendTo('article#exhibitionSearch ul.grid');
								}
							});
						}
					});
				}, 500 );
			}
		});
		
		$('.bio .toggler').click(function(){
			$(this).next('.toggled').slideToggle(500);
			$('body').animate({ scrollTop: $(this).offset().top },500);
		});

		$('.newseventsListing .toggler').click(function(){
			$(this).prev('.toggled').slideToggle(500);
			if ( $(this).text() == "more..." ) {
				$(this).text("less...");
				var nID = $(this).attr('id').split('_')[1];
				$.ajax({
					type: 'POST',
					url: 'actions.php',
					data: "action=news-image&nID="+nID,
					dataType: 'json',
					error: function(jqXHR, textStatus, errorThrown) { alert(errorThrown); },
					success: function(data) {
						$('img.newsImage').fadeOut(200,function(){
							$(this).attr('src',data.nImage).fadeIn(200);
						});
					}
				});
			}
			else $(this).text("more...");
		});
		
		$('.copy').click(function(){
			var text = $(this).attr('data-text');
			copyToClipboard(text);
		})


/********************************************   ___   ____  ___  _____  ___  ****************
 ********************************************  |___  |   | |__/   |    |___  ****************
 ********************************************  ___| |___| |  \   |     ___|  ****************
 ********************************************                                ****************/

		$('section.admin article#exhibitionList ul.grid').sortable({
			opacity: 0.5,
			placeholder: 'placeholder',
			connectWith: 'section.admin article#exhibitionList ul.grid',
			handle: '.handle',
			start: function (e, ui) {
				ui.placeholder.css({ width: 170, height: 170, marginBottom: 70 });
			},
			update : function(e, ui) {
				if (ui.sender) {
					var status = ui.sender.attr('id').split('_')[1];
					var serial = ui.sender.sortable('serialize')+'&action=sort-exhibitions&eStatus='+status;
				}
				else {
					var status = ui.item.parent('ul').attr('id').split('_')[1];
					var serial = ui.item.parent('ul').sortable('serialize')+'&action=sort-exhibitions&eStatus='+status;
				}
				$.ajax({
					type: "POST",
					url: "actions.php",
					data: serial
				});
			}
		});

		$('section.admin article#exhibitionSearch ul.grid').sortable({
			opacity: 0.5,
			placeholder: 'placeholder',
			connectWith: 'section.admin article#exhibitionArt ul.grid',
			handle: '.handle',
			start: function (e, ui) {
				ui.placeholder.css({ width: 170, height: 170, marginBottom: 70 });
			},
			update : function(e, ui) {
				if (ui.sender) {
					var eID = ui.sender.attr('id').split('_')[1];
					var wID = ui.item.attr('id').split('_')[1];
					var data = '&action=remove-exhibition-artwork&eID='+eID+'&wID='+wID;
					$.ajax({
						type: "POST",
						url: "actions.php",
						data: data
					});
				}
			}
		});

		$('section.admin article#exhibitionArt ul.grid').sortable({
			opacity: 0.5,
			placeholder: 'placeholder',
			connectWith: 'section.admin article#exhibitionSearch ul.grid',
			handle: '.handle',
			start: function (e, ui) {
				ui.placeholder.css({ width: 170, height: 170, marginBottom: 70 });
			},
			update : function(e, ui) {
				if (ui.sender) {
					var eID = ui.item.parent('ul').attr('id').split('_')[1];
					var wID = ui.item.attr('id').split('_')[1];
					var serial = ui.item.parent('ul').sortable('serialize')+'&action=add-sort-exhibition-artworks&eID='+eID+'&wID='+wID;
					$.ajax({
						type: "POST",
						url: "actions.php",
						data: serial
					});
				}
				else {
					var eID = ui.item.parent('ul').attr('id').split('_')[1];
					var serial = ui.item.parent('ul').sortable('serialize')+'&action=sort-exhibition-artworks&eID='+eID;
					$.ajax({
						type: "POST",
						url: "actions.php",
						data: serial
					});
				}
			}
		});

		$('section.admin article#artistList ul.grid').sortable({
			opacity: 0.5,
			placeholder: 'placeholder',
			handle: '.handle',
			start: function (e, ui) {
				ui.placeholder.css({ width: 170, height: 170, marginBottom: 70 });
			},
			update : function(e, ui) {
				var serial = ui.item.parent('ul').sortable('serialize')+'&action=sort-artists';
				$.ajax({
					type: "POST",
					url: "actions.php",
					data: serial
				});
			}
		});

		$('section.admin article#artworksList.all ul.grid').sortable({
			opacity: 0.5,
			placeholder: 'placeholder',
			handle: '.handle',
			start: function (e, ui) {
				ui.placeholder.css({ width: 170, height: 170, marginBottom: 70 });
			},
			update : function(e, ui) {
				var serial = ui.item.parent('ul').sortable('serialize')+'&action=sort-artists-artworks';
				$.ajax({
					type: "POST",
					url: "actions.php",
					data: serial
				});
			}
		});

		$('section.admin article#artworksList.series ul.grid').sortable({
			opacity: 0.5,
			placeholder: 'placeholder',
			connectWith: 'section.admin article#artworksList.series ul.grid',
			handle: '.handle',
			start: function (e, ui) {
				ui.placeholder.css({ width: 170, height: 170, marginBottom: 70 });
			},
			update : function(e, ui) {
				if (ui.sender) {
					var sID = ui.sender.attr('id').split('_')[1];
					var serial = ui.sender.sortable('serialize')+'&action=sort-series-artworks&sID='+sID;
				}
				else {
					var sID = ui.item.parent('ul').attr('id').split('_')[1];
					var serial = ui.item.parent('ul').sortable('serialize')+'&action=sort-series-artworks&sID='+sID;
				}
				$.ajax({
					type: "POST",
					url: "actions.php",
					data: serial
				});
			}
		});

		$('section.admin article#seriesList ul.list').sortable({
			opacity: 0.5,
			placeholder: 'placeholder',
			handle: '.handle',
			start: function (e, ui) {
				var phW = ui.placeholder.prev('li').width();
				var phH = ui.placeholder.prev('li').height();
				ui.placeholder.css({ width: phW, height: phH });
			},
			update : function(e, ui) {
				var serial = ui.item.parent('ul').sortable('serialize')+'&action=sort-series';
				$.ajax({
					type: "POST",
					url: "actions.php",
					data: serial
				});
			}
		});

		$('section.admin article#articlesList ul.list').sortable({
			opacity: 0.5,
			placeholder: 'placeholder',
			handle: '.handle',
			start: function (e, ui) {
				var phW = ui.placeholder.prev('li').width();
				var phH = ui.placeholder.prev('li').height();
				ui.placeholder.css({ width: phW, height: phH });
			},
			update : function(e, ui) {
				var serial = ui.item.parent('ul').sortable('serialize')+'&action=sort-articles';
				$.ajax({
					type: "POST",
					url: "actions.php",
					data: serial,
					success: function(data) {
						alert(data);
					}
				});
			}
		});

		$('section.admin div#wiImagesEdit').sortable({
			opacity: 0.5,
			placeholder: 'placeholder',
			handle: '.handle',
			start: function (e, ui) {
				var phW = ui.placeholder.prev('div').find('img').width();
				var phH = ui.placeholder.prev('div').find('img').height();
				ui.placeholder.css({ width: phW, height: phH });
			},
			update : function(e, ui) {
				var serial = ui.item.parent('#wiImagesEdit').sortable('serialize')+'&action=sort-artworksimages';
				$.ajax({
					type: "POST",
					url: "actions.php",
					data: serial
				});
			}
		});
		
		$('section.admin article#newsList ul.list').sortable({
			opacity: 0.5,
			placeholder: 'placeholder',
			handle: '.handle',
			start: function (e, ui) {
				var phW = ui.placeholder.prev('li').width();
				var phH = ui.placeholder.prev('li').height();
				ui.placeholder.css({ width: phW, height: phH });
			},
			update : function(e, ui) {
				var serial = ui.item.parent('ul').sortable('serialize')+'&action=sort-newsevents';
				$.ajax({
					type: "POST",
					url: "actions.php",
					data: serial
				});
			}
		});

		$('section.admin article#publicationList ul.grid').sortable({
			opacity: 0.5,
			placeholder: 'placeholder',
			handle: '.handle',
			start: function (e, ui) {
				ui.placeholder.css({ width: 170, height: 170, marginBottom: 70 });
			},
			update : function(e, ui) {
				var serial = ui.item.parent('ul').sortable('serialize')+'&action=sort-publications';
				$.ajax({
					type: "POST",
					url: "actions.php",
					data: serial
				});
			}
		});




/********************************************   ____  ____  ___   _    _  ___  ****************
 ********************************************  |___  |   | |__/  | \_/ | |___  ****************
 ******************************************** |     |___| |  \  |     |  ___|  ****************
 ********************************************                                  ****************/

		/*------------------------------ Add Exhibition Form */
		
		$('form#eAdd').validate({
			debug: true,
			errorElement: "em",
			errorClass: "invalid",
			rules: {
				eImage:			{ required: true },
				eTitle:			{ required: true }
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.prevAll('label') );
			},
			success: function(label) {
				label.html("ok!").addClass("success");
			},
			submitHandler: function(form) {
				form.submit();
			}
		});
		

		/*------------------------------ Edit Exhibition Form */
		
		$('form#eEdit').validate({
			debug: true,
			errorElement: "em",
			errorClass: "invalid",
			rules: {
				eTitle:			{ required: true }
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.prevAll('label') );
			},
			success: function(label) {
				label.html("ok!").addClass("success");
			},
			submitHandler: function(form) {
				jQuery(form).ajaxSubmit({
					dataType: 'json',
					success: function(data) {
						$('div#success').html('Exhibition Updated').fadeIn(0).delay(2000).fadeOut(1000,function(){
							$(this).empty();
						});
						$('input[name=eImage]').val('');
						$('input[name=curImage]').val(data.eImage);
						$('img.main').attr('src','img/exhibitions/main/'+data.eImage);
					}
				});
			}
		});


		/*------------------------------ Delete Exhibition 'Form' */
		
		$('article#exhibitionList div.delete').live('click',function(){
			var $this = $(this).closest('li');
			var $thID = $this.attr('id').split('_')[1];
			if ( confirm('Delete this Exhibition? This cannot be undone!') ) {
				$.post(
					'actions.php',
					{ action: "delete-exhibition", eID: $thID },
					function(data) {
						$this.fadeOut(200,function(){
							$this.remove();
						});
					}
				);
			}
			else {
				return false;
			}
		});


		/*------------------------------ Add Artist Form */
		
		$('form#aAdd').validate({
			debug: true,
			errorElement: "em",
			errorClass: "invalid",
			rules: {
				aLastName:			{ required: true }
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.prev('label') );
			},
			success: function(label) {
				label.html("ok!").addClass("success");
			},
			submitHandler: function(form) {
				form.submit();
			}
		});
		

		/*------------------------------ Edit Artist Form */
		
		$('form#aEdit').validate({
			debug: true,
			errorElement: "em",
			errorClass: "invalid",
			rules: {
				aLastName:			{ required: true }
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.prevAll('label') );
			},
			success: function(label) {
				label.html("ok!").addClass("success");
			},
			submitHandler: function(form) {
				jQuery(form).ajaxSubmit({
					dataType: 'json',
					success: function(data) {
						$('div#success').html('Artist Updated').fadeIn(0).delay(2000).fadeOut(1000,function(){
							$(this).empty();
						});
						$('input[name=aImage]').val('');
						$('input[name=curImage]').val(data.aImage);
						if ( !data.aImage ) data.aImage = "default.jpg";
						$('img.main').attr('src','img/artists/170x170/'+data.aImage);
					}
				});
			}
		});


		/*------------------------------ Visible Artist 'Form' */
		
		$('article#artistList div.visible').live('click',function(){
			var $this = $(this);
			var thID = $this.closest('li').attr('id').split('_')[1];
			$.post('actions.php',{ action: "visible-artist", aID: thID },function(data) {
				$this.toggleClass('On');
			});
		});


		/*------------------------------ Delete Artist 'Form' */
		
		$('article#artistList div.delete').live('click',function(){
			var $this = $(this).closest('li');
			var $thID = $this.attr('id').split('_')[1];
			if ( confirm('Delete this Artist? Any artworks will also be deleted! This cannot be undone!!') ) {
				$.post(
					'actions.php',
					{ action: "delete-artist", aID: $thID },
					function(data) {
						$this.fadeOut(200,function(){
							$this.remove();
						});
					}
				);
			}
			else {
				return false;
			}
		});


		/*------------------------------ Add Artwork Form */
		
		$('form#wAdd').validate({
			debug: true,
			errorElement: "em",
			errorClass: "invalid",
			rules: {
				'wiImage[]':	{ required: true },
				wTitle:			{ required: true }
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.prevAll('label') );
			},
			success: function(label) {
				label.html("ok!").addClass("success");
			},
			submitHandler: function(form) {
				form.submit();
			}
		});
		
		$('form#wAdd input[type=file]').change(function(){
			var filename = $(this).val().split('.')[0].split('\\')[2];
			$(this).closest('form').find('input[name=wTitle]').val(filename);
		});
		
		$('form#wAdd #addWImage').click(function(){
			$('<br /><br /><input type="file" name="wiImage[]" />').appendTo('#wiImages .files');
		});
		

		/*------------------------------ Edit Artwork Form */
		
		$('form#wEdit').validate({
			debug: true,
			errorElement: "em",
			errorClass: "invalid",
			rules: {
				wTitle:			{ required: true }
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.prevAll('label') );
			},
			success: function(label) {
				label.html("ok!").addClass("success");
			},
			submitHandler: function(form) {
				jQuery(form).ajaxSubmit({
					dataType: 'json',
					success: function(data) {
						$('div#success').html('Artwork Updated').fadeIn(0).delay(2000).fadeOut(1000,function(){
							$(this).empty();
						});
						$('input[type=file]').remove();
						if ( data.wiImages ) {
							$.each(data.wiImages,function(k,v){
								$('<div class="wiImage" id="wi_'+v.wiID+'"><img class="main" src="img/artworks/main/'+v.wiImage+'" /><div class="handle" title="Drag to reorder this image to a new position."></div><div class="delete" title="Delete this artwork image."></div></div>').prependTo('#wiImagesEdit');
							});
							
						}
						$('span#wTitle').html(data.wTitle);
					}
				});
			}
		});

		$('form#wEdit #addWImage').click(function(){
			$('<input type="file" name="wiImage[]" />').appendTo('#wiImagesEdit');
		});


		/*------------------------------ Delete Artwork Image 'Form' */
		
		$('div.wiImage div.delete').live('click',function(){
			var $this = $(this).parent();
			var $thID = $this.attr('id').split('_')[1];
			if ( confirm('Delete this Artwork Image? This cannot be undone!') ) {
				$.post(
					'actions.php',
					{ action: "delete-artworkimage", wiID: $thID },
					function(data) {
						$this.fadeOut(200,function(){
							$this.remove();
						});
					}
				);
			}
			else {
				return false;
			}
		});


		/*------------------------------ Delete Artwork 'Form' */
		
		$('article#artworksList div.delete').live('click',function(){
			var $this = $(this).closest('li');
			var $thID = $this.attr('id').split('_')[1];
			if ( confirm('Delete this Artwork? This cannot be undone!') ) {
				$.post(
					'actions.php',
					{ action: "delete-artwork", wID: $thID },
					function(data) {
						$this.fadeOut(200,function(){
							$this.remove();
						});
					}
				);
			}
			else {
				return false;
			}
		});


		/*------------------------------ Add Series Form */
		
		$('form#sAdd').validate({
			debug: true,
			errorElement: "em",
			errorClass: "invalid",
			rules: {
				sName:			{ required: true }
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.prevAll('label') );
			},
			success: function(label) {
				label.html("ok!").addClass("success");
			},
			submitHandler: function(form) {
				jQuery(form).ajaxSubmit({
					dataType: 'json',
					resetForm: true,
					success: function(data) {
						$('div#success').html('Series Added').fadeIn(0).delay(2000).fadeOut(1000,function(){
							$(this).empty();
						});
						var newArtist = '				<li id="s_'+data.sID+'" class="clearfix">';
							newArtist += '					<div class="tools left">';
							newArtist += '						<label>&nbsp;</label>';
							newArtist += '						<div class="handle" title="Drag to reorder this series to a new position."></div>';
							newArtist += '						<div class="delete" title="Delete this series."></div>';
							newArtist += '					</div>';
							newArtist += '					<div class="main left"><a href="?page=Artworks&amp;aID='+data.aID+'&amp;show=Series"><img src="img/artworks/30x30/default.jpg" /></a></div>';
							newArtist += '					<div class="name left">';
							newArtist += '						<label>Series Name</label>';
							newArtist += '						<form action="actions.php" method="post" class="ajax sEditName"><input type="text" name="sName" value="'+data.sName+'" /><input type="hidden" name="action" value="edit-series-name" /><input type="hidden" name="sID" value="'+data.sID+'" /></form>';
							newArtist += '					</div>';
							newArtist += '					<div class="submit left">';
							newArtist += '							<label>&nbsp;</label>';
							newArtist += '							<div class="visible" title="Show/hide this series on the site"></div>';
							newArtist += '					</div>';
							newArtist += '					<input type="hidden" name="action" value="edit-series" />';
							newArtist += '				</li>';
						$(newArtist).prependTo('article#seriesList ul.list.edit').hide().slideDown(300);
					}
				});
			}
		});
		
		/*------------------------------ Edit Series Name */
		
		$('form.sEditName').live('blur',function(){
			var sID = $(this).find('input[name=sID]').val();
			var sName = $(this).find('input[name=sName]').val();
			$.post('actions.php',{ action: "edit-series-name", sID: sID, sName: sName },function(data) {
				$('div#success').html('Series Name Updated').fadeIn(0).delay(2000).fadeOut(1000,function(){
					$(this).empty();
				});
			});
		});


		/*------------------------------ Visible Series 'Form' */
		
		$('article#seriesList div.visible').live('click',function(){
			var $this = $(this);
			var thID = $this.closest('li').attr('id').split('_')[1];
			$.post('actions.php',{ action: "visible-series", sID: thID },function(data) {
				$this.toggleClass('On');
			});
		});


		/*------------------------------ Delete Series 'Form' */
		
		$('article#seriesList div.delete').live('click',function(){
			var $this = $(this).closest('li');
			var $thID = $this.attr('id').split('_')[1];
			if ( confirm('Delete this Series? This cannot be undone!! (The associated artworks will not be deleted)') ) {
				$.post(
					'actions.php',
					{ action: "delete-series", sID: $thID },
					function(data) {
						$this.fadeOut(200,function(){
							$this.remove();
						});
					}
				);
			}
			else {
				return false;
			}
		});


		/*------------------------------ Add News & Events Form */
		
		$('form#nAdd').validate({
			debug: true,
			errorElement: "em",
			errorClass: "invalid",
			rules: {
				nTitle:			{ required: true }
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.prevAll('label') );
			},
			success: function(label) {
				label.html("ok!").addClass("success");
			},
			submitHandler: function(form) {
				form.submit();
			}
		});
		

		/*------------------------------ Edit News & Events Form */
		
		$('form#nEdit').validate({
			debug: true,
			errorElement: "em",
			errorClass: "invalid",
			rules: {
				nTitle:			{ required: true }
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.prevAll('label') );
			},
			success: function(label) {
				label.html("ok!").addClass("success");
			},
			submitHandler: function(form) {
				jQuery(form).ajaxSubmit({
					dataType: 'json',
					success: function(data) {
						$('div#success').html('News / Event Updated').fadeIn(0).delay(2000).fadeOut(1000,function(){
							$(this).empty();
						});
						$('input[name=nImage]').val('');
						$('input[name=curImage]').val(data.nImage);
						$('img.main').attr('src','img/news/main/'+data.nImage);
					}
				});
			}
		});


		/*------------------------------ Delete News & Events 'Form' */
		
		$('article#newsList div.delete').live('click',function(){
			var $this = $(this).closest('li');
			var $thID = $this.attr('id').split('_')[1];
			if ( confirm('Delete this News / Event? This cannot be undone!') ) {
				$.post(
					'actions.php',
					{ action: "delete-newsevents", nID: $thID },
					function(data) {
						$this.fadeOut(200,function(){
							$this.remove();
						});
					}
				);
			}
			else {
				return false;
			}
		});


		/*------------------------------ Add News & Events Default Image Form */
		
		$('form#niAdd').validate({
			debug: true,
			errorElement: "em",
			errorClass: "invalid",
			rules: {
				niImage:			{ required: true }
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.prevAll('label') );
			},
			success: function(label) {
				label.html("ok!").addClass("success");
			},
			submitHandler: function(form) {
				jQuery(form).ajaxSubmit({
					dataType: 'json',
					success: function(data) {
						$('div#success').html('News &amp; Events Default Image Uploaded').fadeIn(0).delay(2000).fadeOut(1000,function(){
							$(this).empty();
						});
						var newImage = '				<li>';
							newImage += '					<img src="img/news/170/'+data.niImage+'" />';
							newImage += '					<div class="delete" title="Delete this image."></div>';
							newImage += '				</li>';
						$(newImage).prependTo('article#newsImagesList ul.grid.edit').hide().fadeIn(300);
					}
				});
			}
		});
		

		/*------------------------------ Delete News & Events Default Image 'Form' */
		
		$('article#newsImagesList div.delete').live('click',function(){
			var $this = $(this).closest('li');
			var $thID = $this.attr('id').split('_')[1];
			if ( confirm('Delete this News / Event default image? This cannot be undone!') ) {
				$.post(
					'actions.php',
					{ action: "delete-newseventsimage", niID: $thID },
					function(data) {
						$this.fadeOut(200,function(){
							$this.remove();
						});
					}
				);
			}
			else {
				return false;
			}
		});


		/*------------------------------ Add Article / Review Form */
		
		var numArticlesAdded = 1;
		$('form#aaAdd').validate({
			debug: true,
			errorElement: "em",
			errorClass: "invalid",
			rules: {
				aaTitle:			{ required: true }
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.prevAll('label') );
			},
			success: function(label) {
				label.html("ok!").addClass("success");
			},
			submitHandler: function(form) {
				jQuery(form).ajaxSubmit({
					dataType: 'json',
					resetForm: true,
//					error: function (XMLHttpRequest, textStatus, errorThrown) { alert('HTTP Error: '+errorThrown+' | Error Message: '+textStatus); console.log(arguments); },
					success: function(data) {
						$('div#success').html('Article / Review Added').fadeIn(0).delay(2000).fadeOut(1000,function(){
							$(this).empty();
						});
						var newArticle = '				<li id="aa_'+data.aaID+'" class="clearfix">';
							newArticle += '					<div class="tools left">';
							newArticle += '						<label>&nbsp;</label>';
							newArticle += '						<div class="handle" title="Drag to reorder this article / review to a new position."></div>';
							newArticle += '						<div class="delete" title="Delete this article / review."></div>';
							newArticle += '					</div>';
							newArticle += '					<div class="name left">';
							newArticle += '						<label>Article / Review Title</label>';
							newArticle += '						<form action="actions.php" method="post" class="ajax aaEditTitle"><input type="text" name="aatitle" value="'+data.aaTitle+'" /><input type="hidden" name="action" value="edit-article-name" /><input type="hidden" name="aaID" value="'+data.aaID+'" /></form>';
							newArticle += '					</div>';
							newArticle += '					<div class="details left">';
							newArticle += '						<label>Details</label>';
							newArticle += '						<form action="actions.php" method="post" class="ajax aaEditDetails"><textarea name="aaDetails" class="tinymce" id="t'+numArticlesAdded+'">'+data.aaDetails+'</textarea><input type="hidden" name="action" value="edit-article-details" /><input type="hidden" name="aaID" value="'+data.aaID+'" /></form>';
							newArticle += '					</div>';
							newArticle += '					<div class="submit left">';
							newArticle += '							<label>&nbsp;</label>';
							newArticle += '							<div class="visible" title="Show/hide this article / review on the site"></div>';
							newArticle += '					</div>';
							newArticle += '					<input type="hidden" name="action" value="edit-article" />';
							newArticle += '				</li>';
						$(newArticle).prependTo('article#articlesList ul.list.edit').hide().slideDown(300);
						tinyMCE.execCommand( 'mceAddControl', false, 't'+numArticlesAdded );
						numArticlesAdded++;
					}
				});
			}
		});

		
		/*------------------------------ Edit Article / Review Title */
		
		$('form.aaEditTitle').live('blur',function(){
			var aaID = $(this).find('input[name=aaID]').val();
			var aaTitle = $(this).find('input[name=aaTitle]').val();
			$.post('actions.php',{ action: "edit-article-title", aaID: aaID, aaTitle: aaTitle },function(data) {
				$('div#success').html('Article / Review Title Updated').fadeIn(0).delay(2000).fadeOut(1000,function(){
					$(this).empty();
				});
			});
		});


		/*------------------------------ Edit Article / Review Details */
		
		// see tinymce init below


		/*------------------------------ Visible Article / Review 'Form' */
		
		$('article#articlesList div.visible').live('click',function(){
			var $this = $(this);
			var thID = $this.closest('li').attr('id').split('_')[1];
			$.post('actions.php',{ action: "visible-article", aaID: thID },function(data) {
				$this.toggleClass('On');
			});
		});


		/*------------------------------ Delete Article / Review 'Form' */
		
		$('article#articlesList div.delete').live('click',function(){
			var $this = $(this).closest('li');
			var aaID = $this.attr('id').split('_')[1];
			if ( confirm('Delete this Article / Review? This cannot be undone!!') ) {
				$.post(
					'actions.php',
					{ action: "delete-article", aaID: aaID },
					function(data) {
						$this.fadeOut(200,function(){
							$this.remove();
						});
					}
				);
			}
			else {
				return false;
			}
		});


		/*------------------------------ Add Publication / Edition Form */
		
		$('form#pAdd').validate({
			debug: true,
			errorElement: "em",
			errorClass: "invalid",
			rules: {
				pImage:			{ required: true },
				pTitle:			{ required: true }
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.prevAll('label') );
			},
			success: function(label) {
				label.html("ok!").addClass("success");
			},
			submitHandler: function(form) {
				form.submit();
			}
		});
		

		/*------------------------------ Edit Publication / Edition Form */
		
		$('form#pEdit').validate({
			debug: true,
			errorElement: "em",
			errorClass: "invalid",
			rules: {
				pTitle:			{ required: true }
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.prevAll('label') );
			},
			success: function(label) {
				label.html("ok!").addClass("success");
			},
			submitHandler: function(form) {
				jQuery(form).ajaxSubmit({
					dataType: 'json',
					error: function(data) {
						$.each(data,function(k,v){
							alert(k+' - '+v);
						});
					},
					success: function(data) {
						$('div#success').html('Publication / Edition Updated').fadeIn(0).delay(2000).fadeOut(1000,function(){
							$(this).empty();
						});
						$('input[name=pImage]').val('');
						$('input[name=curImage]').val(data.pImage);
						$('img.main').attr('src','img/publications/main/'+data.pImage);
						if ( data.pDownload != "same" ) {
							$('input[name=pDownload]').val('');
							$('input[name=curDownload]').val(data.pDownload);
							$('a.curPub').attr('href','downloads/'+data.pDownload);
						}
					}
				});
			}
		});


		/*------------------------------ Delete Publication / Edition 'Form' */
		
		$('article#publicationList div.delete').live('click',function(){
			var $this = $(this).closest('li');
			var $thID = $this.attr('id').split('_')[1];
			if ( confirm('Delete this Publication / Edition? This cannot be undone!') ) {
				$.post(
					'actions.php',
					{ action: "delete-publication", pID: $thID },
					function(data) {
						$this.fadeOut(200,function(){
							$this.remove();
						});
					}
				);
			}
			else {
				return false;
			}
		});


		/*------------------------------ Edit About Form */
		
		$('form#abEdit').validate({
			debug: true,
			errorElement: "em",
			errorClass: "invalid",
			rules: {
				abName:			{ required: true }
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.prevAll('label') );
			},
			success: function(label) {
				label.html("ok!").addClass("success");
			},
			submitHandler: function(form) {
				jQuery(form).ajaxSubmit({
					dataType: 'json',
					error: function(data) {
						$.each(data,function(k,v){
							alert(k+' - '+v);
						});
					},
					success: function(data) {
						$('div#success').html(data.abName+' Updated').fadeIn(0).delay(2000).fadeOut(1000,function(){
							$(this).empty();
						});
						$('article.col3 h1').html('Edit '+data.abName);
						if ( data.abImage ) {
							$('input[name=abImage]').val('');
							$('input[name=curImage]').val(data.abImage);
							$('img.main').attr('src','img/about/main/'+data.abImage);
						}
					}
				});
			}
		});


		/*------------------------------ Edit Contact Form */
		
		$('form#cEdit').validate({
			submitHandler: function(form) {
				jQuery(form).ajaxSubmit({
					dataType: 'json',
					success: function(data) {
						$('div#success').html('Contact Info Updated').fadeIn(0).delay(2000).fadeOut(1000,function(){
							$(this).empty();
						});
						if ( data.cImage ) {
							$('input[name=cImage]').val('');
							$('input[name=curImage]').val(data.cImage);
							$('img.main').attr('src','img/contact/main/'+data.cImage);
						}
					}
				});
			}
		});


		/*------------------------------ Join Mailing List Form */
		
		$('form#newslist').validate({
			debug: true,
			errorElement: "em",
			errorClass: "invalid",
			groups: {
				PHONE: "PHONE[area] PHONE[detail1] PHONE[detail2]"
			},
			rules: {
				FNAME:				{ required: true, maxlength: 50 },
				LNAME:				{ required: true, maxlength: 50 },
				EMAIL:				{ required: true, maxlength: 70, email: true },
				'PHONE[area]':		{ required: function() { return $('input[value="Telephone"]').is(':checked'); }, numeric: true, maxlength: 3 },
				'PHONE[detail1]':	{ required: function() { return $('input[value="Telephone"]').is(':checked'); }, numeric: true, maxlength: 3 },
				'PHONE[detail2]':	{ required: function() { return $('input[value="Telephone"]').is(':checked'); }, numeric: true, maxlength: 4 },
				'ADDRESS[addr1]':	{ required: function() { return $('input[value="Regular Mail"]').is(':checked'); }, maxlength: 150 },
				'ADDRESS[city]':	{ required: function() { return $('input[value="Regular Mail"]').is(':checked'); }, maxlength: 100 },
				'ADDRESS[state]':	{ required: function() { return $('input[value="Regular Mail"]').is(':checked'); }, maxlength: 50 },
				'ADDRESS[zip]':		{ required: function() { return $('input[value="Regular Mail"]').is(':checked'); }, maxlength: 10, alphaNumeric: true },
				'COMMENTS':			{ maxlength: 255 }
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.closest('td').prev('td').find('label') );
			},
			success: function(label) {
				label.html("ok!").addClass("success");
			},
			submitHandler: function(form) {
				$(form).ajaxSubmit({
					error: function(data) {
						$.each(data,function(k,v){
							alert('JS----'+k+' - '+v+'----JS');
						});
					},
					success: function(data) {
						$('form#newslist').slideUp(500,function(){
							$('p#signup').html(data);
						});
					}
				});
			}
		});
		

		/*------------------------------ Add Upload Form */
		
		$('form#uAdd').validate({
			debug: true,
			errorElement: "em",
			errorClass: "invalid",
			rules: {
				uUpload:	{ required: true }
			},
			errorPlacement: function(error, element) {
				error.appendTo( element.prevAll('label') );
			},
			success: function(label) {
				label.html("ok!").addClass("success");
			},
			submitHandler: function(form) {
				$(form).ajaxSubmit({
					resetForm: true,
					type: 'POST',
					dataType: 'json',
					error: function(data) {
						$.each(data,function(k,v){
							alert('JS----'+k+' - '+v+'----JS');
						});
					},
					success: function(data) {
						if ( data.uID ) {
							$('<li id="u_'+data.uID+'"><img class="copy" data-text="uploads/'+data.uUpload+'" src="'+data.icon+'" '+data.style+' /><p class="copy forceWrap" data-text="uploads/'+data.uUpload+'">'+data.uUpload+'</p><div class="delete" title="Delete this upload."></div></li>').appendTo('article#uploadsList ul.grid').hide().fadeIn(300);
						}
						$('div#success').html(data.message);
					}
				});
			}
		});


		/*------------------------------ Delete Upload 'Form' */
		
		$('article#uploadsList div.delete').live('click',function(){
			var $this = $(this).parent();
			var $thID = $this.attr('id').split('_')[1];
			if ( confirm('Delete this Upload? This cannot be undone!') ) {
				$.post(
					'actions.php',
					{ action: "delete-upload", uID: $thID },
					function(data) {
						$this.fadeOut(200,function(){
							$this.remove();
						});
					}
				);
			}
			else {
				return false;
			}
		});
		
		

		/*------------------------------ All Forms */
		
		$('form.ajax').submit(function(e){
			e.preventDefault();
		});

		
		$.validator.addMethod("alphaNumeric", function(value, element) {
			return this.optional(element) || /^[a-z0-9 \-]+$/i.test(value);
		}, "Use only letters, numbers, spaces and dashes.");
		
		$.validator.addMethod("numeric", function(value, element) {
			return this.optional(element) || /^[0-9]+$/.test(value);
		}, "Numbers only.");
		
		$('form.validateIt input,form.validateIt textarea').each(function(index) {
			$(this).rules("add", {
				messages: {
					required: 'Required',
					email: "Invalid",
					zipcode: "Numbers and dashes only"
				}
			});
		});
		
		$('input.opt').click(function(){
			$(this).parent('label').next('span.optional').toggleClass('Open');
		});

		$('textarea.tinymce').tinymce({
			// Location of TinyMCE script
			script_url : 'js/tiny_mce/tiny_mce.js',

			// General options
			theme : "advanced",
//			plugins : "autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",
			plugins : "inlinepopups,paste",
			paste_auto_cleanup_on_paste : true,
			paste_remove_styles: true,
			paste_remove_spans: true,
			paste_strip_class_attributes: "all",
			
			// Theme options
			theme_advanced_buttons1 : "bold,italic,link,unlink,code",
			theme_advanced_buttons2 : "",
			theme_advanced_buttons3 : "",
			theme_advanced_buttons4 : "",
//			theme_advanced_buttons1 : "save,newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect",
//			theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
//			theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
//			theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
			theme_advanced_toolbar_location : "external",
			theme_advanced_toolbar_align : "left",
			theme_advanced_statusbar_location : "bottom",
			theme_advanced_resizing : true,
			theme_advanced_path : false,

			// Example content CSS (should be your site CSS)
			content_css : "css/tinymce.css",
			editor_css : "css/editor.css",
			

			theme_advanced_resizing_min_height : 19,

			setup : function(editor) {
				editor.onInit.add(function(editor,ev) {
					var s = editor.settings;
					var f = editor.getElement();
					if ( $(f).closest('form').hasClass('aaEditDetails') ) {
						editor.theme.resizeTo(170,19);
						tinymce.dom.Event.add(s.content_editable ? editor.getBody() : (tinymce.isGecko ? editor.getDoc() : editor.getWin()), 'blur', function(e) {
							editor.theme.resizeTo(170,19);
							var $form = $(f).closest('form'),
								aaID = $form.find('input[name="aaID"]').val(),
								action = $form.find('input[name="action"]').val(),
								aaDetails = editor.getContent(),
								url = $form.attr('action');
							$.post( url, { aaID: aaID, aaDetails: aaDetails, action: action }, function(data) {
								$('div#success').html('Article / Review Details Updated').fadeIn(0).delay(1000).fadeOut(1000,function(){
									$(this).empty();
								});
							});
						});
						tinymce.dom.Event.add(s.content_editable ? editor.getBody() : (tinymce.isGecko ? editor.getDoc() : editor.getWin()), 'focus', function(e) {
							editor.theme.resizeTo(170,100);
						});
					}
				});
			}


			// 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"
//			}
			
		});
		
		
	});


	$(window).bind("load", function() {
		
		$('.col2 .block').each(function(){
			if ( $('img.main').height() > 240 ) {
				$(this).css({ minHeight: $('img.main').height() });
			}
			$('ul#aboutNav').show();
		});
		
	});
	

})(window.jQuery);
