$(function(){
	
// functions
function password_prompt() {
	var bar = $(this).parent('div')
	var original_height = bar.height()
	
	$.get('panels/prompt.php', function(fields) {
		bar.next('div').find('ol:first').prepend(fields)
	})
	
	$('.cancel').live('click', function(){
		var login = $(this).parents('li:first')
		var login_height = login.height()+15
		var panel = login.parents('li[class*="panel"]')
		var panel_height = panel.height()
		var toggle = login.parents('div:first').prev('div').find('.editPanel')
		login.remove()
		panel.height(panel_height - login_height)
		toggle.trigger('click')
	})
	$('.confirm').live('click', function(){
		var year = $(this).parents('div:first').parents('div:fisrt').attr('id')
		var email = $('input#userEmail').val();
		var password = $('input#userPassword').val();
		var login = $(this).parents('li:first')
		var login_height = login.height()+15
		var panel = login.parents('li[class*="panel"]')
		var panel_height = panel.height()
		var toggle = login.parents('div:first').prev('div').find('.editPanel')
		$.post('db/passwordCheck.php', {year:year, email:email, password:password}, function(confirm){
			if (confirm == 1) {
				login.remove()
				panel.height(panel_height - login_height)
				$('div[id="'+ year +'"]').prev('div').find('.editPanel').text('done editing').parents('li[class*="panel"]').find('.customize').addClass('editable').click(function(click) {
					click.preventDefault();
				})
			} else {
				$('.confirm').val('please try again');
			}
		})
	});
	
}

function open_editor () {
	$(this).text('done editing').parents('li[class*="panel"]').find('.customize').addClass('editable').click(function(click){
		click.preventDefault();
	})
}

function close_editor () {
	//console.log('second function')
	$(this).text('edit panel').parents('li[class*="panel"]').find('.customize').removeClass('editable')
}

function edit () {
	var panel = $(this).parents('li[class*="panel"]')
	var original_panel_height = panel.height()
	var original_edit_height = $(this).height()
	var original_text = $(this).text()
	var year = $(this).parents('div[class="panelCont"]').attr('id')
	var db_column = $(this).attr('id')
	
	$(this).removeClass('editable')
	
	$(this).html('<textarea class="" style="height:'+ original_edit_height +'px" value="" >'+ original_text +'</textarea> <input type="submit" class="cancelEdit" value="cancel" /> <input type="submit" class="saveEdit" value="save" />')
	if (jQuery.browser.msie) {
		$(this).find('textarea:first').select()
	}
	
	var new_edit_height = $(this).height()
	var height_difference = new_edit_height - original_edit_height
	
	panel.height(original_panel_height + height_difference);

	$('.saveEdit').click(function(save){
		save.preventDefault();
		var changed = $(this).parent().find('textarea:first').val()
		var email = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/.test(original_text);
		if (email) {
				$(this).parent().empty().html('<a href="mailto:'+ changed +'">'+ changed +'</a>').addClass('editable')
		} else {
			$(this).parent().empty().text(changed).addClass('editable')
		}
			
		var new_panel_height = panel.height()
		panel.height(new_panel_height - height_difference)
		
		$.post('db/editable.php', {year:year, db_column:db_column, edit:changed});
	});
	
	$('.cancelEdit').click(function(cancel){
		cancel.preventDefault();
		var email = /^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$/.test(original_text);
		if (email) {
			$(this).parent().empty().html('<a href="mailto:'+ original_text +'">'+ original_text +'</a>').addClass('editable')
		} else {
			$(this).parent().empty().text(original_text).addClass('editable')
		}
		
		var new_panel_height = panel.height()
		panel.height(new_panel_height - height_difference)
	});
}

function show_details () {
	var panel_height = $(this).parents('li[class*="panel"]').height();
	var table_height = $(this).parents('li:first').next('.cal').height();
	$(this).text('-').parents('li[class*="panel"]').height(panel_height+table_height)
	$(this).parents('li:first').next('.cal').show()	
}

function hide_details () {
	var panel_height = $(this).parents('li[class*="panel"]').height();
	var table_height = $(this).parents('li:first').next('.cal').height();
	$(this).text('+').parents('li[class*="panel"]').height(panel_height-table_height)
	$(this).parents('li:first').next('.cal').hide()	
}
	
	// load default content
	$('#columns li[id*="default"]').each(function() {
		var filename = $(this).find('.panelCont').attr('id')
    	$(this).find('.panelCont')
		.load('panels/'+ filename +'.php')
		.ajaxStop(function(){
			// height animation
			var bar_height = $(this).parents('li:first').find('#bar').height();
			var panel_height = $(this).height();
			$(this).parents('li:first').animate({'height' : panel_height+bar_height+18})
	
			// icons
			var icon = $(this).attr('id')
			$(this).parents('li:first').find('.icon').attr('src', 'images/'+ icon +'.png')
		});
		
	});
	
	// load custom content
	$('#columns li[id*="custom"]').each(function() {
		var panel_name = $(this).find('.panelCont').attr('id')
		var referer = $('#custom a:contains("'+ panel_name +'")')
		var row_index = referer.attr('id').replace('custom_', '');
    	
		$(this).find('.panelCont')
		.load('panels/custom.php', {row:row_index})
		.ajaxStop(function(){
			// height animation
			var bar_height = $(this).parents('li:first').find('#bar').height();
			var panel_height = $(this).height();
			$(this).parents('li:first').animate({'height' : panel_height+bar_height+18})
	
			// icons
			$(this).parents('li:first').find('.icon').attr('src', 'images/newspaper.png')
		});
	});
	
	// toggle panel directory
	var speed = 150;
	$("#title li:last").toggle(function(){
		var list_height = $("#directory ul").height()
		$('#explore').fadeOut();
		$("#directory").animate({"height" : list_height + 70}, speed)
		$("#header").animate({"height" : list_height + 125}, speed)
	}, function() {
		$("#directory").animate({"height" : "0"}, speed)
		$("#header").animate({"height" : "125"}, speed)
	});
	

	$('#directory span').click(function(){
    	$.post('db/layout.php', {})
	});	
	
	// style default links
	$("#default a").each(function(){
		var link_id = $(this).attr("id").replace(/ /g,'_')
		var linked_panel = $('.column li[id="' + link_id + '"]')
		if (linked_panel.length > 0) {
			$(this).addClass('open')
		} else {
			$(this).addClass('closed')
		}
		// get rid of the underscore
		var space = $(this).text().replace(/_/g,' ');
		$(this).html(space);
	});
	
	// open default panels
	$("#default a").click(function(click){
		click.preventDefault()
		var clicked = $(this).attr("id").replace(/ /g, '_')
		var cap_name = $(this).text()
		var name = $(this).text().replace(/ /g,'_')
		var target_panel = $('.column li[id="' + clicked + '"]')
		
		if (target_panel.length > 0) {
			alert('The ' + cap_name + ' panel is already open!')
		} else {
			$.post('panels/defaultPanel.php', {row:clicked}, function(panel){
        		$('#column3').prepend(panel);
				// update layout position in database
				$('.column li[class*="panel"]').each(function(){
				    var column = $(this).parents('ul') 
				    var panel_id = $(this).attr('id').replace(/ /g,'_')
				    var panel_index = column.find('li[class*="panel"]').index($(this))+1
				    var column_id = column.attr('id')
				    var column_index = column_id.replace('column', '')
					var panel_name = $(this).find('.panelCont:first').attr('id').replace(/ /g,'_')
					var panel_class = $(this).attr('class').replace('panel_', '')
					$.post('db/layout.php', {row:panel_id, column:column_index, spot:panel_index, name:panel_name, scheme:panel_class})  
				});
				$('#default a[id="' + clicked + '"]').removeClass('closed').addClass('open') 
				$('#' + name)
				.load('panels/' + name + '.php')
				.ajaxStop(function(){
					// height animation
					var bar_height = $(this).parents('li:first').find('#bar').height();
					var panel_height = $(this).height();
					$(this).parents('li:first').animate({'height' : panel_height+bar_height+18})
			
					// icons
					var icon = $(this).attr('id').replace(/ /g,'_')
					$(this).parents('li:first').find('.icon').attr('src', 'images/'+ icon +'.png')
				});		
			});
		}
	});
	
	// style custom links
	$('#custom a').each(function(){
	    var text = $(this).text().replace('class of ', '')
	    var target_panel = $('.panelCont[id="'+ text +'"]') 
	    if (target_panel.length > 0) {
	        $(this).addClass('open')
	    } else {
	        $(this).addClass('closed')    
	    } 
	});
	
	// open custom panels
	$("#custom a").live("click", function(click){
		click.preventDefault()
		var clicked = $(this).attr("id")
		var cap_name = $(this).text()
		var name = $(this).text().replace(/class of /,'')
		var text = $(this).text().replace('class of ', '')
	    var target_panel = $('.panelCont[id="'+ text +'"]')
		
		if (target_panel.length > 0) {
			alert('The ' + cap_name + ' panel is already open!')
		} else {
			$.post('panels/customPanel.php', {row:clicked}, function(panel){
        		$('#column3').prepend(panel);
				// update layout position in database
				$('.column li[class*="panel"]').each(function(){
				    var column = $(this).parents('ul') 
				    var panel_id = $(this).attr('id')
				    var panel_index = column.find('li[class*="panel"]').index($(this))+1
				    var column_id = column.attr('id')
				    var column_index = column_id.replace('column', '')
					var panel_name = $(this).find('.panelCont:first').attr('id')
					var panel_class = $(this).attr('class').replace('panel_', '')
					$.post('db/layout.php', {row:panel_id, column:column_index, spot:panel_index, name:panel_name, scheme:panel_class}) 
				});
				$('#custom a[id="' + clicked + '"]').removeClass('closed').addClass('open') 
				$('#' + name)
				.load('panels/custom.php', {row:clicked})
				.ajaxStop(function(){
					// height animation
					var bar_height = $(this).parents('li:first').find('#bar').height();
					var panel_height = $(this).height();
					$(this).parents('li:first').animate({'height' : panel_height+bar_height+18})
			
					// icons
					$(this).parents('li:first').find('.icon').attr('src', 'images/newspaper.png')
				});
			});
		}
	});
	
	
	// create new custom panel
	$('#newBtn[rel]').each(function(){
		$(this).overlay({
		top: '3%',
		//oneInstance: false,
		close: '.closeWizard',
		expose: {
			color: '#000000'
		},
		onBeforeLoad: function(){
			// reset all fields
			/*var forms = $('#wizard :text')
			forms.val('');
			$('.wizard .error').empty();
			$('.wizard .success').empty();
			$('.swatches').removeClass('clicked').removeClass('notClicked').css({'opacity' : '1.0'})*/
			$('#wizard').load('panels/wizard.php', function(data){
				$(this).html(data)
			});
		},
		onLoad: function() {
			// handle the ie cleartype bug
			if(jQuery.browser.msie) {
				$('.simple_overlay').each(function(){
					$(this).get(0).style.removeAttribute("filter");
				})
			}
		},
		onClose: function() {
			$original_links = $('#custom li').length;
			$('#customLinks').load('db/refreshDirectory.php', function(data){
				$(this).html(data);
			});
			$new_links = $('#custom li').length;
			if ($new_links > $original_links) {
				//console.log('new panel')
			} else {
				//console.log('no new panel')
			}
		}
	});
	});
	
	/*$('.scrollable').scrollable({
		size: 1,
		clickable: false
	});*/
	
	// rearrange panels
	$(".column").sortable({
		cursor:'move', 
		//revert: 150,
		placeholder:'placeholder',
		handle: '#bar',
		connectWith:'#column1, #column2, #column3',
		update: function(){
			$('.column li[class*="panel"]').each(function(){
		    var column = $(this).parents('ul') 
		    var panel_id = $(this).attr('id').replace(/ /g,'_')
		    var panel_index = column.find('li[class*="panel"]').index($(this))+1
		    var column_id = column.attr('id')
		    var column_index = column_id.replace('column', '')
			var panel_name = $(this).find('.panelCont:first').attr('id').replace(/ /g,'_')
			var panel_class = $(this).attr('class').replace('panel_', '')
			$.post('db/layout.php', {row:panel_id, column:column_index, spot:panel_index, name:panel_name, scheme:panel_class}) 
			});
		} 
	});
			
	// close panels
	$(".closePanel").live("click", function(){
		var bar_height = $(this).parent('div:first').height();
		// remove panel from DOM and update the database
		$(this).parents("li").animate({'height' : bar_height}).fadeOut(300, function() { 
			$(this).remove() 
		})
		var id = $(this).parents('li').attr('id').replace(' ', '_')
		var panel_name = $(this).parent('div').next('div').attr('id')
		$.post('db/layout.php', {row:id, name:panel_name, column:0, spot:0})
		
		// re-style directory link
		var parent_panel = $(this).parents('li:first').attr('id')
		var custom =  /custom_/.test(parent_panel);
		
		if (custom) {
			var text = $(this).parents('li:first').find('.panelCont').attr('id')
			$('#directory a:contains("'+ text +'")').removeClass('open').addClass('closed')
		} else {
			var linked_to =  $(this).parents("li").attr("id").replace(/ /g,'_')
			$('#directory a[id="' + linked_to + '"]').removeClass('open').addClass('closed')
		}
		
		// show restore notification
		setTimeout(function(){
		if ($("#restore").length <= 0) {
			$('#explore').hide();
			$('<div id="restore"><p><b>note: </b>you can always re-open a panel by selecting it from the "panels" tab</p></div>')
			.insertAfter("#title")
			.fadeIn("slow", function(){
				if (jQuery.browser.msie) {
					this.style.removeAttribute('filter');
				}
			})
		}}, 750);
		// hide notification after x seconds
		setTimeout(function(){
			$("#restore").fadeOut("slow")
		}, 5000);
		// update layout database
		setTimeout(function(){
			$('.column li[class*="panel"]').each(function(){
			var column = $(this).parents('ul') 
		    var panel_id = $(this).attr('id').replace(/ /g,'_')
		    var panel_index = column.find('li[class*="panel"]').index($(this))+1
		    var column_id = column.attr('id')
			var column_index = column_id.replace('column', '')
		    var panel_name = $(this).find('.panelCont:first').attr('id').replace(/ /g,'_')
			var panel_class = $(this).attr('class').replace('panel_', '')
			$.post('db/layout.php', {row:panel_id, column:column_index, spot:panel_index, name:panel_name, scheme:panel_class}) 
		});
		}, 1000)
	});
	
	// inline edit
	$('.editPanel').live('click', function(){
		$(this).toggle(password_prompt, close_editor).trigger('click');
		/*if ($(this).text() == 'done editing') {
			return open_editor;
		} else if ($(this).text() == 'edit panel') {
			return close_editor;
		}*/
	});
	
	$('.editable').live('dblclick', edit);
	
	// event details
	$('.toggle').live('click', function(){
		$(this).toggle(show_details, hide_details).trigger('click')
	});
	
});