$(function() {

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

	$.fn.jPicker.defaults.images.clientPath = '/images/jpicker/';
	$('.colorPicker').jPicker();

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

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

	// quick popup login form
	$('a.login-link').bind('click', function(e) {

		e.preventDefault();
		$(this).addClass('on');

		var $this = $(this);

		var $usernameField = $('<div />', {
			'class' : 'field'
		}).append($('<label></label>', {
			'for' : 'username',
			html : 'Username'
		}).after($('<input></input>', {
			'id' : 'username',
			'type' : 'text',
			'name' : 'users[USER][username]'
		})));

		var $passwordField = $('<div />', {
			'class' : 'field'
		}).append($('<label />', {
			'for' : 'password',
			html : 'Password'
		}).after($('<input />', {
			'id' : 'password',
			'type' : 'password',
			'name' : 'users[USER][password]'
		})));

		var $checkboxField = $('<div />', {
			'class' : 'field'
		}).append($('<input />', {
			'id' : 'remember',
			'type' : 'checkbox',
			'value' : 1,
			'value' : 'users[USER][remember]',
			'checked' : 'checked',
			'class' : 'checkbox'
		}).after($('<label />', {
			'for' : 'remember',
			html : 'Remember me'
		})));

		var $submitButton = $('<input />', {
			'type' : 'submit',
			'class' : 'submit',
			'value' : 'Login'
		});

		var $cancelButton = $('<input />', {
			'type' : 'submit',
			'class' : 'submit',
			'value' : 'Cancel',
			click : function(e) {
				e.preventDefault();
				$('#quick-login-box').fadeOut('fast', function() {
					$this.removeClass('on');
					$(this).remove();
				});
			}
		});

		$(this).parent().prepend($('<div />', {
			'id' : 'quick-login-box'
		}).fadeIn().append($('<form />', {
			submit : function(e) {
				e.preventDefault();

				// remove error message
				$('#quick-login-box').find('div.error').fadeOut(function() {
					$(this).remove();
				});

				var usernameValue = $(this).find('input#username').val();
				var passwordValue = $(this).find('input#password').val();
				var rememberMe = $(this).find('input#remember').attr('checked');

				$.ajax({
					url : '/helpers/quickLogin.php',
					cache : false,
					type : 'POST',
					dataType : 'json',
					data : {
						'username' : usernameValue,
						'password' : passwordValue,
						'remember' : rememberMe
					},
					error : function() {
						// redirect to admin area for standard login
						window.location.replace("/admin");
					},
					success : function(data, textStatus) {
						if (data.error) {
							$('#quick-login-box').prepend($('<div />', {
								'class' : 'error',
								html : data.error
							}));
							$(':input[type=password]', '#quick-login-box').each(function() {
								$(this).val('');
							});
						} else if (data.success) {
							// should be logged in now so refresh the page
							window.location = self.location;
						}
					}
				});
				return false;
			}
		}).append($('<fieldset />').append($usernameField).append($passwordField).append($checkboxField).append($submitButton).append($cancelButton))));
	});

	/**
	 * inline edits
	 */
	// add the edit buttons
	$('div.editableMCE,div.editableText').append($('<a></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 />', {
					'method' : 'post'
				}).append($('<fieldset />').append($('<textarea />', {
					width : defaultWidth,
					height : defaultHeight + 30,
					'id' : id + 'Editor'
				}).after($('<input />', {
					'type' : 'submit',
					'value' : 'Save',
					'class' : 'submit'
				}).after($('<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 />', {
						'class' : 'editContentButton',
						'href' : 'javascript:',
						html : 'edit'
					}));
				}))))));
				$parent.children('form').find('textarea').val(oldContent);
				if ($parent.hasClass('editableMCE')) {
					// edit with tinyMCE
					tinyMCE.init({
						mode : 'exact',
						theme_advanced_resizing_min_width : 550,
						elements : id + 'Editor',
						theme : 'advanced',
						body_class : "cms",
						content_css : "/css/content.css",
						plugins : "safari,inlinepopups,paste,table,advimage",
						file_browser_callback : "tinyBrowser",
						paste_auto_cleanup_on_paste : true,
						theme_advanced_buttons1 : "bold, italic, underline, justifyleft,justifycenter, justifyright, justifyfull , 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,h3,h4,h5",
						convert_urls : false,
						verify_html : true,
						valid_elements : "@[class|style|title],br,h2,h3,h4,-p[align],-strong/b,a[name|href|target],span," + "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 />', {
									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 />', {
					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 />', {
								'class' : 'editContentButton',
								'href' : 'javascript:',
								html : 'edit'
							}));
						});
					});
				}, 5000);
			},
			success : function(data, textStatus) {
				$parent.html(newContent);
				$parent.append($('<a />', {
					'class' : 'editContentButton',
					'href' : 'javascript:',
					html : 'edit'
				}));
			}
		});
	};

	// style switchers
	$(".change-background").switchstylesheet({
		seperator : "background"
	});
	$(".change-size").switchstylesheet({
		seperator : "text"
	});

	// homepage image switchy thing
	$('#image-switcher').switcher({
		boxId : 'testimonial-box'
	});

	$('a[rel="external"]').each(function() {
		$(this).attr({
			target : '_blank',
			title : 'Open ' + $(this).attr('href') + ' in a new window'
		});
	});

});

/**
 * !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,advimage",
	file_browser_callback : "tinyBrowser",
	paste_auto_cleanup_on_paste : true,
	width : "640",
	height : "500",
	theme_advanced_buttons1 : "bold, italic, underline, justifyleft,justifycenter, justifyright, justifyfull , 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,h3,h4,h5",
	convert_urls : false,
	verify_html : true,
	valid_elements : "@[class|style|title],br,h2,h3,h4,-p[align],-strong/b,a[name|href|target],span," 
			+ "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"
});
