/* 
 * Query Builder Javascript
 * Verions 2
 * April 17, 2009
 * 
 * This is a rewrite and better version of the Query Builder used for
 * the Metropoltan Knowledge Network.
 * 
 * URL: http://mkn.research.pdx.edu/
 * Contact: Ben Hartig
 * Email: bhartig@pdx.edu
 *
 * Usage: To activate the tool you will need to set a DOM element with the class
 * get_tool and have an id of the table data it is accessing.
 *
 * Requires: jQuery 1.3.x
 *           http://jquery.com/
 *
 */

$(function(){
	// Append the query builder wrapper and overlay so users are focused on the builder
	// instead of the page content
	$('body').append('<div id="qb_close_button" class="qb_close"></div><div id="qb_wrapper"></div><div id="qb_overlay" class="qb_close"></div>');
	
	// Build the wrapper for the query builder and the content for each instance of the class get_tool
	$('.get_tool').click(function () {
		// Get table name
		var table_name = $(this).attr('id');

		// Get the dimensions of the window and findout the size of the query builder wrapper
		var window_width = $(window).width();
		var window_height = $(window).height();
		
		var wrapper_top = (15 + (window_height * .015));
		var wrapper_left = -((window_width/2) - (window_width * .025));
		var wrapper_width = (window_width - (window_width * .05));
		var wrapper_height = (window_height - 30 - (window_height * .025));
		
		var button_top = 3 + (window_height * .015);
		var button_right = (window_width * .025) - 13;
		
		// Set up the blank query builder canvas for us to add in content for users to use
		var overlay = $('#qb_overlay');
		var wrapper = $('#qb_wrapper');
		var close_button = $('#qb_close_button');

		wrapper.empty();
		
		wrapper.css({
			'top' : wrapper_top,
			'margin-left' : wrapper_left,
			'width' : wrapper_width,
			'height' : wrapper_height
		});
		
		close_button.css({
			'top' : button_top,
			'right' : button_right
		});
		
		overlay.fadeIn('fast');
		close_button.fadeIn('fast');

		wrapper.append('<div id="qb_title_bar"><div id="qb_title"></div><div id="qb_title_buttons"><div id="qb_back">Reload</div><div id="qb_close" class="qb_close">Close</div></div></div>');
		wrapper.append('<form action="test.php" method="post" id="qb_form"></form>');
		var form = $('#qb_form');
		
		// Check if the table really is in the database
		jQuery.ajax({
			type: "GET",
			url: '/querybuilder/get.php?get=table_check&table=' + table_name,
			timeout: 1000,
			dataType: "text",
			success: function(data) {
				// Finally use the table name and recall the form
				if(data == "yes"){
					
					// Set the title of the form
					jQuery.ajax({
						type: "GET",
						url: '/querybuilder/get.php?get=table_name&table=' + table_name,
						timeout: 1000,
						dataType: "html",
						success: function(data) {
							$('#qb_title').text(data);
						}
					});
					
					// Get the options
					form.append('<div id="qb_options_bar"></div>');
					
					// Get the selects
					form.append('<div id="qb_panel"></div>');
					var panel = $('#qb_panel');
					var panel_height = wrapper_height - 275;
					panel.css({
						'height' : panel_height
					});
					
					// Get the select options that users can select for the form
					get_options(table_name);
					get_selects(table_name);
					
					form.append('<div id="qb_results"></div>');
					var results = $('#qb_results');
					var results_height = wrapper_height - 200;
					results.css({
						'height' : results_height
					});
					results.hide();
					
					// Make the Submit button
					form.append('<div id="qb_submit_bar"><input id="qb_submit" type="submit" value="Build Results →"/></div>');
					
				// If the table name is null or not defined we want to tell ther user that
				// they should close and try a different table for the tool
				} else {
					$('#qb_back').hide();
					$('#qb_title').text('Table ' + table_name + ' was not found.');
					wrapper.append('<div id="qb_error"><p>Table was not found in the database. <span class="qb_close qb_error_close">Close Query Builder</span></p></div>');
					var error_top = (window_height/2) - 75;
					var error_left = (window_width/2) - 175;
					var error = $('#qb_error');
					error.css({
						'margin-top' : error_top,
						'margin-left' : error_left
					});
				}
			},
			complete: function(data) {
				// Sumbit the form and get results
				$('#qb_submit').click(function () {
					
					// capture all the input values
					var inputs = [];
					$('select, input:checked, input:hidden').each(function() {
						inputs.push(this.name + '=' + this.value);
					});
					jQuery.ajax({
						type: "POST",
						data: inputs.join('&'),
						url: '/querybuilder/get.php?get=results',
						dataType: "html",
						success: function(data) {
							$('#qb_back').text("← Back");
							$('#qb_options_bar').hide().empty();
							$('#qb_panel').hide().empty();
							$('#qb_results').show().html(data);
							get_recent();
							$('tr:odd:has(td)').css('background-color', '#F3F1F4');
						}
					});
					return false;
				});
				
				// Reload the query builder
				$('#qb_back').click(function () {
					$('#qb_back').text("Reload");
					var type = '';
					var group = '';
					$('#qb_results').hide().empty();
					$('#qb_options_bar').show();
					$('#qb_panel').show();
					get_options(table_name, type, group);
					get_selects(table_name, type, group);
				});
				
				// Find all the close buttons so the user can close the builder when needed
				var close = $('.qb_close');
				close.click(function () {
					close_button.fadeOut('fast');
					wrapper.fadeOut('fast');
					overlay.fadeOut('slow');
					wrapper.children().remove();
				});
			}
		});
		
		wrapper.append('<div id="qb_recent_bar"></div>');
		get_recent();

		// Lets actually display the query builder now
		wrapper.fadeIn('slow');

	});
	
	// Generate the recent image bar and get the images the user has generated before
	function get_recent() {
		jQuery.ajax({
			type: "GET",
			url: '/querybuilder/get.php?get=recent_imgs',
			timeout: 1000,
			dataType: "html",
			success: function(data) {
				$('#qb_recent_bar').html(data);
				$('#qb_recent_bar a').each(function(){
					$(this).click(function(){
						$('#qb_back').text("← Back");
						$('#qb_options_bar').hide().empty();
						$('#qb_panel').hide().empty();
						$('#qb_results').show().empty();
						var url = $(this).attr('href');
						$('#qb_results').append("<img src=\"" + url + "\"/>")
						return false;
					});
				});
			}
		});
	}
	
	// Get the options that a user can chose from
	function get_options(table_name, type, group) {
		$('#qb_options_bar').children().remove();
		
		if(!type){
			var type = '';
		}
		
		if(!group){
			var group = '';
		}
		
		jQuery.ajax({
			type: "GET",
			url: '/querybuilder/get.php?get=get_form&table=' + table_name + '&type=' + type + '&group=' + group,
			timeout: 1000,
			dataType: "html",
			success: function(data) {
				$('#qb_options_bar').html(data);
			},
			complete: function(data) {
				// when the group value changes
				$('#group').change(function(){
					var type = $('#type').val();
					var group = $('#group').val();
					get_options(table_name, type, group);
					get_selects(table_name, type, group);
				});
				// when the type value changes
				$('#type').change(function(){
					var type = $('#type').val();
					var group = $('#group').val();
					get_options(table_name, type, group);
					get_selects(table_name, type, group);
				});
			}
		});
	}
	
	// Get the select options that a user can chose from
	function get_selects(table_name, type, group) {
		$('#qb_panel').children().remove();
		
		if(!type){
			var type = '';
		}
		
		if(!group){
			var group = '';
		}
		
		jQuery.ajax({
			type: "GET",
			url: '/querybuilder/get.php?get=get_options&table=' + table_name + '&type=' + type + '&group=' + group,
			timeout: 1000,
			dataType: "html",
			success: function(data) {
				$('#qb_panel').html(data);
			},
			complete: function(data) {
				// When complete lets make selecting checkboxes look pretty
				$('li:has(input)').each(function(){
					// if the click is on the li
					$(this).click(function(){
						var checked = $(this).find("input").attr('checked');
						if(checked){
							$(this).find("input").attr('checked', false);
							$(this).css('background-color','#fff');
						} else {
							$(this).find("input").attr('checked', true);
							$(this).css('background-color','#8abbff');
						}
					});
					
					// if the click is the actual checkbox
					$(this).find("input").click(function(){
						var checked = $(this).attr('checked');
						if(checked){
							$(this).attr('checked', false);
							$(this).parent().css('background-color','#fff');
						} else {
							$(this).attr('checked', true);
							$(this).parent().css('background-color','#8abbff');
						}
					});
				});
				
				// if the user uses the select all
				$('.select_all').each(function(){
					$(this).click(function(){
						if($(this).hasClass('all')){
							$(this).removeClass('all');
							$(this).css('color', '#000000');
							$(this).html("Select All");
							$(this).parent().parent().find("input").attr('checked', false);
							$(this).parent().parent().find("li:has(input)").css('background-color','#fff');
						} else {
							$(this).addClass('all');
							$(this).html("Select All &#10003;");
							$(this).css('color', '#009103');
							$(this).parent().parent().find("input").attr('checked', true);
							$(this).parent().parent().find("li:has(input)").css('background-color','#8abbff');
						}
					});
				});
				
				// if the type is a graph then we want to limit the checkbox selecting to 1.
				var type = $('#type').val();
				if(type == "graph"){
					$('.xy').each(function(){
						$(this).find("li:has(input)").click(function(){
							var count = $(this).parent().find("li:has(input:checked)").size();
							if(count > 1){
								$(this).find("input").attr('checked', false);
								$(this).css('background-color','#fff');
							}
						});
					});
				}
			}
		});
	}
	
	// On load lets set the tool tips
	$('.get_tool').each(function(){
		var which = $(this);
		var table_name = $(this).attr('id');			
		jQuery.ajax({
			type: "GET",
			url: '/querybuilder/get.php?get=table_name&table=' + table_name,
			dataType: "text",
			success: function(data) {
				var tip = "";
				if(data){
					tip = "<b>Click to generate your own table</b><br /><br />" + "Table: <b>" + table_name + "</b><br />Name: <b>" + data + "</b>";
				} else {
					tip = "Table Was Not Found";
				}
				which.attr("title", tip);
			},
			complete: function() {
				// When the person hovers over lets show the tool tip and hide when they leave
				which.qtip({
					show: 'mouseover',
					hide: 'mouseout',
					position: { target: 'mouse' },
					style: {
						'font-size': 11,
						name: 'dark'
					}
				});
			}
		});
    });
	
	// Find all the sidebars and reset their margins.
	var num_side = $('.image').size();
	var content_length = $('#content_body').height();
	var toc = $('.toc').height();
	var height_sides = 0;
	$('.image').each(function(){
		height_sides += $(this).height();
	});
	var margintemp = ((content_length - toc - height_sides)/num_side)/2;
	$('.image').each(function(){
		$(this).css("margin-top", margintemp);
		$(this).css("margin-bottom", margintemp);
	});
	
	// For the email registeration of the list serv lets do some ajaxy stuff.
	$('#registerform').submit(function(){
		var action = $('#registerform').attr('action');
		var form = $('#registerform');
		var inputs = [];
		$(':input', form).each(function(){
			inputs.push(this.name + '=' + this.value);
		});
		jQuery.ajax({
			data: inputs.join('&'),
			type: "POST",
			url: action,
			timeout: 10000,
			dataType: "html",
			success: function(data) {
				$('#register').empty();
				$('#register').html(data);
			}
		});
		return false;
	});
});