/**
 * CraftStylish.com: Gallery Photo Organizer Component
 *
 * Copyright (c) 2008 Matthew Knight (http://www.reconstrukt.com)
 * for Taunton Press
 *
 * @requires jQuery v1.2
 *
 */

$(document).ready(function(){
    
  // setup for ajax requests
	$().ajaxStart(function(){
		
	}).ajaxStop(function(){
		$('input#ajax').val( '0' );
	});
	
	// toggle between save/preview modes depending on clicked button
	$('input#button_save').click(function(){
		$('input#preview').val('0');
	});
	$('input#button_preview').click(function(){
		$('input#preview').val('1');
	});
	
	// on submit, push richtext content to hidden el's
	// populate content from richtext editors
	$('form#share-gallery').submit(function(){
		populate_from_richtext();
	});

	// bind the attachment form's submit button
	$('a#submit-save-photo').click(function() {
		
		var form_opt = { 
			beforeSubmit : function(formData, jqForm, options) { 
				// formData is an array
				// jqForm is a jQuery object encapsulating the form element
				// options are the options used for this call
				// here, you can run validation and return false to prevent the form from being submitted
				return true;				
			},
			success : function(html, statusText)  { 
				// for normal html responses, the first argument to the success callback 
				// is the XMLHttpRequest object's responseText property 
		 
				// if the ajaxForm method was passed an Options Object with the dataType 
				// property set to 'xml' then the first argument to the success callback 
				// is the XMLHttpRequest object's responseXML property 
		 
				// if the ajaxForm method was passed an Options Object with the dataType 
				// property set to 'json' then the first argument to the success callback 
				// is the json data object returned by the server 
								
				// tinymce binds itself to iframes and injects garbage HTML (like <p> tags, etc)
				// so, we're trying to strip that out here...
				cutoff = html.lastIndexOf("}");
				var _json  = html.substring(0, cutoff + 1);
				var json   = eval( "(" + _json + ")" );
				
				if (json.errors) {
					
					// build the error string
					err = '';
					for (i=0; i<json.errors.length; i++) {
						err += json.errors[i] + "\n";						
					}
					alert(err);
					reset_add_form();
										
				} else if (json.update_success) {
					
					// render updated caption, credit
					var attach_id = $('input#attachment_id').val();
					var o = $('div#picture-container-' + attach_id);
					
					var cap = o.find('textarea').attr('id');
					var cre = o.find('input.attachment_credit');
					
					o.find('span.text').html( tinyMCE.get( cap ).getContent() + '<span class="more">' + (cre.val() == cre.attr('_default') ? '' : cre.val()) + '</span>' );
					
					// alert success msg
					// alert(json.update_success);
					reset_picture_form();
										
				} else {
					// render the post ID
					$('input#post_id').val( json.post_parent );
										
					// render the thumbnail, and initialize
					var thumb_id	= 'picture-container-' + json.ID;
					var filename	= json.img_sqs.substring(json.img_sqs.lastIndexOf('/') + 1, json.img_sqs.length);
							filename  = filename.replace('_sqs', '');
					
					/*
					I know. The more elegant way to do this is to have hidden markup templated into the page, clone a copy, and manipulate.
					Actually, this is the way I originally did.  Neat and clean that way, no markup in my js object... but
					Unfortuantely this will not work in IE6. IE6 will always attach events to the original (not the clone).  
					So we hack it like this old skool.
					yuck
					*/
					
					var t  = '';
							t += '<img src="/assets/images/circle2.gif" class="photo-num" />';
							
							t += '<span class="photo">';
							t += '<img class="thumbnail-image" src="' + json.img_sqs + '" alt="" width="90" height="90" />';
							t += '<br />';
							t += '<a href="#" name="thumb1" class="thumbnail-zoom" rel="' + json.img_xl + '"><img src="/assets/images/upload_photo_zoom.gif" alt="zoom" /></a>';
							t += '</span>';
							
							t += '<span class="text">';
							t += ($('#attachment_caption').val() == $('#attachment_caption').attr('_default') ? '' : $('#attachment_caption').val());
							t	+= '<span class="more">' + ($('#attachment_credit').val() == $('#attachment_credit').attr('_default') ? '' : $('#attachment_credit').val()) + '</span>';
							t += '</span>';
      
							t += '<span class="upload" style="display:none;">';
							t += 'file: <b>' + filename + '</b>';
							t += '<br /><br />Optional photo caption:';
							t	+= '<textarea name="attachment_caption_' + json.ID + '" id="attachment_caption_' + json.ID + '" rows="5" class="attachment-caption" style="width:250px;">' + $('#attachment_caption').val() + '</textarea><br />';
							t	+= '<input type="text" name="attachment_credit_' + json.ID + '" value="' + $('#attachment_credit').val() + '" _default="Optional photo credit" class="text-box attachment_credit" /><br />';
							t	+= '<a href="#" class="thumbnail-save" id="thumbnail-save-' + json.ID + '"><img src="/assets/images/button_save_changes_photo.gif" alt="save changes" /></a>';
							t	+= '&nbsp;';
							t	+= '<a href="#" class="thumbnail-cancel" id="thumbnail-cancel-' + json.ID + '"><img src="/assets/images/button_cancel_photo.gif" alt="cancel" /></a>';
							t	+= '<div class="loading-indicator" id="loading-wait-' + json.ID + '" style="display:none;">Saving, Please Wait...</div>';
							t	+= '</span>';
							
							t	+= '<span class="options">';
							t	+= '<a href="#" class="thumbnail-edit" rel="' + json.ID + '">edit</a><br />';
							t	+= '<a href="#" class="thumbnail-delete" rel="' + json.ID + '">delete</a><br /><br />';
							t	+= '<a href="#" class="thumbnail-up" rel="' + json.ID + '">move up</a><br />';
							t	+= '<a href="#" class="thumbnail-down" rel="' + json.ID + '">move down</a><br />';
							t	+= '</span>';
			
					var thumb  = $('<div class="pictures picture-container" id="' + thumb_id + '" />').html( t );
					var addnew = $('#add-new-image');
					
					addnew.before( thumb );					
					init_thumb( thumb );
					
					// clean up some fields
					reset_add_form();
					
					reorder_thumbs();
					
				}
			},
			dataType : 'html'  // can be 'xml', 'script', or 'json' (default = html)
		};

		// hide submit + show wait indicator
		if ($('input#attachment_id').val() != '') {
			// we're editing
			$('#thumbnail-save-' + $('input#attachment_id').val()).hide();
			$('#thumbnail-cancel-' + $('input#attachment_id').val()).hide();
			$('#loading-wait-' + $('input#attachment_id').val()).fadeIn('fast');
		} else {
			$('#submit-save-photo').hide();
			$('#loading-wait').fadeIn('fast');
		}
		
		// populate content from richtext editors
		populate_from_richtext();
		
		// set ajax mode
		$('input#ajax').val( '1' );

		// submit.
		$('form#share-gallery').ajaxSubmit(form_opt);
		
		return false;
	});
	
	// init thumbs
	$('div.picture-container').each(function(i){		
		init_thumb( $(this) );
	});
	
	// init order
	reorder_thumbs();
		
	// setup default values on attachment credit textboxes
	$('[_default]').each(function(){		
		default_value_behaviors( $(this) );
	});
	
});

function reset_picture_form(){
	// if an attachment is marked for editing, clear it
	var attach_id = $('input#attachment_id').val();
	if (attach_id != '') {
		// revert the form back to its original state
		$('input#attachment_id').val( '' );
		var o = $('div#picture-container-' + attach_id);
		o.removeClass('selected');
		o.find('span.text').show();
		o.find('a.thumbnail-save').show();
		o.find('a.thumbnail-cancel').show();
		o.find('div.loading-indicator').hide();
		o.find('span.upload').hide();
	}
}

function reset_add_form(){
	// clear the add form
	$('span#attachment_file_container').html( '<input type="file" name="attachment" id="attachment" class="text-box" />' );	
	tinyMCE.get('attachment_caption').setContent( '' );
	$('#attachment_credit').val( '' ).blur();
	$('#loading-wait').hide();
	$('#submit-save-photo').show();
}

// bind events to a thumb container
function init_thumb(o) {
	
	var textarea_id = o.find('textarea').attr('id');
	
	// bind zoom action 
	o.find('a.thumbnail-zoom').click(function(){
		window.open( $(this).attr('rel') );
		return false;
	});
	// bind edit action
	o.find('a.thumbnail-edit').click(function(){
		
		// cancel any existing edits in process
		reset_picture_form();
		
		// set the attachment ID value
		$('input#attachment_id').val( $(this).attr('rel') );
		
		// hilite, hide text, show form
		o.addClass('selected')
		o.find('span.text').hide();
		o.find('span.upload').show();
		
		return false;
	});
	// bind delete action
	o.find('a.thumbnail-delete').click(function(){
		
		var tot = $('div.picture-container').length;
		var min = $('#max-images').attr('_min');
		if (tot > min) {			
			if (confirm('Are you sure you want to delete this image?')) {
				var del_id  = $(this).attr('rel');
				// read out deleted IDs into an array
				var deleted = $('input#images_delete').val() == '' ? new Array() : $('input#images_delete').val().split(',')
				// add to the stack
				deleted.push( del_id );
				// back to string value
				$('input#images_delete').val( deleted.join(',') );
				// remove this el, reset order
				tinyMCE.execCommand('mceRemoveControl', false, textarea_id);
				o.remove();
				reorder_thumbs();
			}
		} else {
			alert("A minimum of " + min + " image is required on a published post.  If you'd like to delete this image, please add another image in its place first.");
		}
		return false;
	});
	// bind move up
	o.find('a.thumbnail-up').click(function(){
		// move this above (left) of the one previous
		var prev = o.prev();
		tinyMCE.execCommand('mceRemoveControl', false, textarea_id);
		o.fadeOut('normal', function(){
			prev
			.before(
				o.fadeIn('normal', function(){
					reorder_thumbs(); 
					tinyMCE.execCommand('mceAddControl', false, textarea_id); 
				})
			);
		});
		return false;
	});
	// bind move down
	o.find('a.thumbnail-down').click(function(){
		// move this below (right) of the next
		var next = o.next();		
		tinyMCE.execCommand('mceRemoveControl', false, textarea_id);
		o.fadeOut('normal', function(){
			next
			.after(o.fadeIn('normal', function(){ 
					reorder_thumbs(); 
					tinyMCE.execCommand('mceAddControl', false, textarea_id); 
				})
			);
		});
		return false;
	});
	// bind form submit
	o.find('a.thumbnail-save').click(function(){
		$('a#submit-save-photo').click();
		return false;
	});
	// bind form cancel
	o.find('a.thumbnail-cancel').click(function(){
		reset_picture_form();
		return false;
	});
	// bind default value behaviors
	o.find('[_default]').each(function(){
		default_value_behaviors( $(this) );
	});
	// make textarea wysiwyg
	tinyMCE.execCommand('mceAddControl', false, textarea_id);
}	

// setup behaviors for default textbox values
function default_value_behaviors(o) {
	// bind events
	o
	.focus(function(){
		if ($(this).val() == $(this).attr('_default')) {
			$(this).val('');
		}
	})
	.blur(function(){
		if ($(this).val() == '') {
			$(this).val( $(this).attr('_default') );
		}
	})	
	// init default value
	if (o.val() == '') {
		o.val( o.attr('_default') );
	}
}

// populate content from richtext editors
function populate_from_richtext(){
	$('input#post_content').val( tinyMCE.get('post_content_richtext').getContent() );
	$('textarea.attachment-caption').each(function(){
		var id = $(this).attr('id')
		var tm = tinyMCE.get( id );
		$(this).val( tm.getContent() );
	});
}

// update sort order
function reorder_thumbs() {
	var thu 			= $('div.picture-container');
	var tot 			= thu.length;
	var img_sort 	= new Array();
	var max 			= $('#max-images').attr('_max');
	
	// handle max images...
	if (Number(tot) >= Number(max)) {
		// hide the add form
		$('#add-new-image').hide();
	} else {
		// show the add form
		$('#add-new-image').show();
	}
	
	thu.each(function(i){			
		var num = i + 1;
		// fil number
		$(this).find('img.photo-num').attr('src', '/assets/images/circle' + num.toString() + '.gif');
		// fill sort order
		img_sort.push( $(this).find('a.thumbnail-delete').attr('rel') );			
		// hide 1st "up"
		(i == 0) ? $(this).find('a.thumbnail-up').hide() : $(this).find('a.thumbnail-up').show();
		// hide last "down"
		(i == tot - 1) ? $(this).find('a.thumbnail-down').hide() : $(this).find('a.thumbnail-down').show();
	});
	// set sort order
	$('input#images_sort').val( img_sort.join(',') );
}
