$(function() {

	$(".editLink").draggable();

	$('#homeImages .imgs').cycle();

	$("ul#mainNav > li").hover(

	function() {

		var h = $(this).outerHeight() - 30;
		var newH = 379 - 30 - h;

		$(this).animate({
			"margin-top" : newH + "px"
		}, {
			queue : false,
			duration : 300
		});

	}, function() {

		$(this).animate({
			"margin-top" : "349px"
		}, {
			queue : false,
			duration : 300
		});
	});

	$("table.sq_table").treeTable({
		initialState : 'expanded'
	});

	// lightbox
	$("a.fancyBox").colorbox({
		photo : true,
		opacity : 0.65,
		scalePhotos : true,
		maxWidth : '75%',
		maxHeight : '75%'
	});

	// ui calendar
	$('input.datePicker').datepicker({
		changeMonth : true,
		changeYear : true,
		dateFormat : 'dd/mm/yy',
		showOn : 'button',
		buttonImage : '/images/btn_calendar.gif',
		buttonImageOnly : true,
		autoSize : true,
		buttonText : 'Select a date from a calendar',
		yearRange : 'c-90:c+10'
	});

	// Image Cropper
	$('.cropbox').each(
			function(n) {

				var $this = $(this);
				var $parent = $this.parent();
				var $data = $parent.find('div.crop-data')
				// get the ratio if it's set
				var aspectRatio = ($parent.find('input.crop-ratio').val() == 0) ? false : $parent.find('input.crop-ratio').val();
				var widthRatio = 1;
				var heightRatio = 1;

				// need to wait for the image to load to get the correct current
				// size
				$this.load(function() {
					var sizes = {
						imageWidth : $data.find('input.crop-image-width').val(),
						imageHeight : $data.find('input.crop-image-height').val(),
						currentWidth : $this.width(),
						currentHeight : $this.height()
					};
					// work out ratio from old to new
					widthRatio = sizes.imageWidth / sizes.currentWidth;
					heightRatio = sizes.imageHeight / sizes.currentHeight;
					console.debug(sizes);
				});

				$('.cropbox').Jcrop(
						{
							aspectRatio : aspectRatio,
							bgOpacity : 0.7,
							onChange : function(c) {
								if (c.w > 0 && c.h > 0) {
									$data.find('input.crop-image-dimensions').val(
											parseInt(c.x * widthRatio) + ',' + parseInt(c.y * heightRatio) + ',' + parseInt(c.w * widthRatio) + ',' + parseInt(c.h * heightRatio));
									// remove the crop on the thumb

								} else {
									$data.find('input.crop-image-dimensions').val('');
								}
							}
						});

				// see if there is a thumbnail that needs cropping too
				$thumb = ($parent.find('div.image-thumbnail').length == 1) ? $parent.find('div.image-thumbnail img') : false;

				if ($thumb) {

					$thumb.Jcrop({

						onChange : function(c) {
							if (c.w > 0 && c.h > 0) {
								$data.find('input.crop-thumb-dimensions').val(c.x + ',' + c.y + ',' + c.w + ',' + c.h);
								// $data.find('input.crop-save').val('true');
							} else {
								$data.find('input.crop-thumb-dimensions').val('');
							}
						}

					});
				}

			});

	/**
	 * inline edits
	 */
	// add the edit buttons
	$('div.editableMCE,div.editableText').append($('<a/>', {
		'class' : 'editContentButton',
		'href' : 'javascript:',
		html : 'edit'
	}));

	// add the rollover
	$('div.editableMCE,div.editableText').live('mouseover mouseout', function(e) {
		var $button = $(this).children('a.editContentButton');
		if (e.type == 'mouseover' && $(this).find('textarea').length == 0) {
			$button.show();
			$(this).addClass('highlight');
		} else {
			$button.hide();
			$(this).removeClass('highlight');
		}

	});

	// make it work
	$('a.editContentButton').live(
			'click',
			function(e) {

				e.preventDefault();

				var $this = $(this);
				var $parent = $(this).parent();
				$this.remove();
				var defaultWidth = $parent.width();
				var defaultHeight = $parent.height();

				// copy the content
				var oldContent = $parent.html();
				var newContent = oldContent;

				var regex = /([\w_]+)_([0-9]+)_([\w]+)/i;
				var id = $parent.attr('id');
				result = regex.exec(id);
				var dataSource = result[1];
				var recordId = result[2];
				var field = result[3];

				// remove the old content
				$parent.removeClass('highlight').html('');
				$parent.append($('<form></form>', {
					'method' : 'post'
				}).append($('<fieldset></fieldset>').append($('<textarea></textarea>', {
					width : defaultWidth,
					height : defaultHeight + 30,
					'id' : id + 'Editor'
				}).after($('<input></input>', {
					'type' : 'submit',
					'value' : 'Save',
					'class' : 'submit'
				}).after($('<input></input>', {
					'type' : 'submit',
					'value' : 'Cancel',
					'class' : 'submit'
				}).bind('click', function(e) {
					e.preventDefault();
					var $parentDiv = $(this).parent().parent().parent();
					$parentDiv.html(oldContent);
					$parentDiv.append($('<a></a>', {
						'class' : 'editContentButton',
						'href' : 'javascript:',
						html : 'edit'
					}));
				}))))));
				$parent.children('form').find('textarea').val(oldContent);
				if ($parent.hasClass('editableMCE')) {
					// edit with tinyMCE
					tinyMCE.init({
						mode : 'exact',
						elements : id + 'Editor',
						theme : 'advanced',
						theme_advanced_resizing_min_width : 550,
						body_class : "cms",
						content_css : "/css/content.css",
						plugins : "safari,inlinepopups,paste,table",
						theme_advanced_buttons1 : "bold, italic, underline, justifyleft,justifycenter, justifyright, justifyfull , styleselect,formatselect,  |, pasteword, code",
						theme_advanced_buttons2 : "undo,redo,|,bullist, numlist,|,outdent,indent, |, link, unlink, image ,forecolor",
						theme_advanced_buttons3 : "tablecontrols",
						theme_advanced_resizing : true,
						theme_advanced_toolbar_location : "top",
						theme_advanced_toolbar_align : "center",
						theme_advanced_statusbar_location : "bottom",
						theme_advanced_blockformats : "p,h2,h4",
						convert_urls : false,
						verify_html : true,
						valid_elements : "@[class|style|title],br,h2,h3,h4,-p[align],-strong/b,a[name|href|target]," + "img[src|border=0|alt|title|width|height|align],hr[width|size|noshade],"
								+ "table[border|cellspacing|cellpadding|width],tr[rowspan],td[colspan],th[colspan],-ul,ol,-li",
						setup : function(ed) {
							ed.onSaveContent.add(function(ed, o) {
								newContent = o.content;
							});
							ed.onSubmit.add(function(ed, e) {
								e.preventDefault();
								// hide form and show saving animation
								$(e.target).replaceWith($('<div></div>', {
									width : defaultWidth,
									height : defaultHeight
								}).css({
									'text-align' : 'center',
									'font-size' : '10px',
									'background' : 'rgba(99,99,99,.2)'
								}).append($('<img />', {
									'src' : '/images/ajax_saving.gif',
									'alt' : '',
									'style' : 'margin-top: ' + ((defaultHeight / 2) - 10) + 'px'
								})).append($('<br />')).append($('<span></span>', {
									html : 'saving..'
								})));

								saveEdit($parent, dataSource, recordId, field, newContent);

							});
						}
					});

				} else {
					// edit in textarea so add the on submit event
					$parent.find('form').bind('submit', function(e) {
						e.preventDefault();
						newContent = $(this).find('textarea:eq(0)').val();
						saveEdit($parent, dataSource, recordId, field, newContent);
					});

				}

			});

	// the ajax save function
	var saveEdit = function($parent, dataSource, id, field, newContent) {
		// now save with ajax
		$.ajax({
			url : '/helpers/saveInlineEdit.php',
			cache : false,
			type : 'POST',
			dataType : 'json',
			data : {
				'dataSource' : dataSource,
				'id' : id,
				'field' : field,
				'data' : newContent
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				$parent.find('div').css({
					'background' : '#b00',
					'color' : '#fff'
				}).html($('<span></span>', {
					html : 'Failed to save, new content will be displayed, please click edit and attempt to save again'
				}));
				setTimeout(function() {
					$parent.fadeOut(100, function() {
						$parent.html(newContent);
						$parent.fadeIn(100, function() {
							$parent.append($('<a></a>', {
								'class' : 'editContentButton',
								'href' : 'javascript:',
								html : 'edit'
							}));
						});
					});
				}, 5000);
			},
			success : function(data, textStatus) {
				$parent.html(newContent);
				$parent.append($('<a></a>', {
					'class' : 'editContentButton',
					'href' : 'javascript:',
					html : 'edit'
				}));
			}
		});
	}

});

/**
 * !important! if you change something here remember to copy it to tinyMCE part
 * in the inline editor above
 */
tinyMCE.init({
	mode : "specific_textareas",
	theme_advanced_resizing_min_width : 550,
	editor_selector : /(tiny_mce|image_mce)/,
	theme : "advanced",
	editor_deselector : "mceNoEditor",
	body_class : "cms",
	content_css : "/css/content.css",
	plugins : "safari,inlinepopups,paste,table",
	paste_auto_cleanup_on_paste : true,
	width : "640",
	height : "500",
	theme_advanced_buttons1 : "bold, italic, underline, justifyleft,justifycenter, justifyright, justifyfull , styleselect, formatselect,  |, pasteword,pastetext, code ",
	theme_advanced_buttons2 : "undo,redo,|,bullist, numlist,|,outdent,indent, |, link, unlink, image ,forecolor",
	theme_advanced_buttons3 : "tablecontrols",
	theme_advanced_resizing : true,
	theme_advanced_toolbar_location : "top",
	theme_advanced_toolbar_align : "center",
	theme_advanced_statusbar_location : "bottom",
	theme_advanced_blockformats : "p,h2,h4",
	convert_urls : false,
	verify_html : true,
	valid_elements : "@[class|style|title],br,h2,h3,h4,-p[align],-strong/b,a[name|href|target]," + "img[src|border=0|alt|title|width|height|align],hr[width|size|noshade],"
			+ "table[border|cellspacing|cellpadding|width],tr[rowspan],td[colspan],th[colspan],-ul,ol,-li"
});
