
$( function() {
		
	
	$("table.sq_table").treeTable( { initialState: 'expanded' } );
	
	
	$('ul#mainNav. li a.parent').toggle( function  () {		
		$(this).parent().find('ul.submenu').slideDown();
		$(this).parent().addClass('highlighted');
		
	} , function() {
		$(this).parent().find('ul.submenu').slideUp();
		$(this).parent().removeClass('highlighted');
	});
	
			
	$('div.dsShadow').dropShadow();
	

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

		
	//quick popup login form 
	$('a.loginLink').bind('click',function(e) {
		
		e.preventDefault();
		$(this).addClass('on');
		
		var $this = $(this);  
				
		var $usernameField = $('<div></div>',{
			'class' : 'field'
		}).append( $('<label></label>',{
			'for': 'username',
			html : 'Username'
		}).after( $('<input></input>',{
			'id' : 'username',
			'type' : 'text',
			'name' : 'users[USER][username]'
		}) ));
		
		var $passwordField = $('<div></div>',{
			'class' : 'field'
		}).append( $('<label></label>',{
			'for': 'password',
			html : 'Password'
		}).after( $('<input></input>',{
			'id' : 'password',
			'type' : 'password',
			'name' : 'users[USER][password]'
		}) ));
		
		var $submitButton = $('<input></input>',{
			'type' : 'submit',
			'class' : 'submit',
			'value' : 'Login'
		});
		
		var $cancelButton = $('<input></input>',{
			'type' : 'submit',
			'class' : 'submit',
			'value' : 'Cancel',
			click : function(e) {
				e.preventDefault();
				$('#quickLoginBox').fadeOut('fast',function(){
					$this.removeClass('on');
					$(this).remove();
				});
			}
		});
		
		$(this).parent().prepend( $('<div></div>',{
			'id' : 'quickLoginBox'
		})
		.fadeIn()
		.append( $('<form></form>',{
			submit: function(e){
				e.preventDefault();
				
				// remove error message
				$('#quickLoginBox').find('div.error').fadeOut(function(){$(this).remove()});
								
				var usernameValue = $(this).find('input#username').val();
				var passwordValue = $(this).find('input#password').val();
				
				$.ajax({
					url: '/helpers/quickLogin.php',
					cache: false,
					type: 'POST',
					dataType: 'json',
					data : {
						'username' : usernameValue,
						'password' : passwordValue
					},			
					error : function(){
						// redirect to admin area for standard login
						window.location.replace("/admin");
					},
					success : function(data, textStatus) {
						if ( data.error ) {
							$('#quickLoginBox').prepend( $('<div></div>',{
								'class' : 'error',
								html: data.error
							}));
							$(':input[type=password]','#quickLoginBox').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></fieldset>')
			.append($usernameField)
			.append($passwordField)
			.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();
		var oldContent = $parent.html();
		// copy the content
		
		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.find('textarea').val(oldContent);
		if ( $parent.hasClass('editableMCE') ) {
			// edit with tinyMCE
			tinyMCE.init({
				mode : 'exact',
				elements : id+'Editor',
				theme: 'advanced',
				body_class : "cms",
				content_css : "/css/cms.css",
				plugins: "safari,inlinepopups,paste,table",
				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,h1,h2,h3,h4",
				convert_urls : false,
				verify_html : true,
				valid_elements : 
					"@[class|style|title],br,h1,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",
	editor_selector : /(tiny_mce|image_mce)/,
	theme : "advanced",
	editor_deselector : "mceNoEditor",
	body_class : "cms",
	content_css : "/css/cms.css",
	plugins: "inlinepopups,table,paste",
    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,h1,h2,h3,h4",
	convert_urls : false,
	verify_html : true,
	valid_elements : 
		"@[class|style|title],br,h1,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"
});
