//Nav
var revert_timer = null;
var default_id = null;
var active_id = null;

//Dashlet
var was_modified = false;

$(function()
{
	$(".dashlet-col").sortable({	connectWith: ['.dashlet-col'],
									placeholder: 'dashlet-drop-helper',
									handle: '.dashlet-header',
									opacity: 0.7
							  });

	$(".dashlet-header-minmax").click(function()
	{
		$(this).toggleClass("dashlet-header-minimised");
		$(this).parents(".dashlet:first").find(".dashlet-content").slideToggle('slow');
	});

	$(".date-picker").datepicker( { dateFormat : 'dd/mm/yy' } );

	$(".dashlet-header-refresh").click(function()
	{

		dashlet_id = $(this).parents(".dashlet:first").attr('id');
		//alert(dashlet_id);
		refresh_dashlet(dashlet_id);
		return false;

	});


	active_id = find_active_nav();

	//Ensure we got a navigation item or just force it to the first one
	if (active_id == false) active_id = 0;


	default_id = active_id;

	$("#azure-nav-main li a").hover(function()
	{

		//Dont want to process subnav. Trace back to nav parent [azure-nav-main li ul li a]
		if ($(this).parents().eq(3).attr('id') == "azure-nav-main")  return;

		clearInterval(revert_timer);

		nav_id = nav_from_id($(this).attr("id"));

		//alert($(this).parents().eq(3).attr('id'));

		//If we havnt managed to come back onto active menu item then shut down active
		if (nav_id != active_id)
		{
			//$('#nav-main-item-' + active_id).removeClass('azure-temp-nav');
			$('#nav-sub-menu-' + active_id).css('border-top', 'none');
			$('#nav-sub-menu-' + active_id).stop();
			$('#nav-sub-menu-' + active_id).css('display', 'none');
			$('#nav-sub-menu-' + active_id).css('opacity', '1.0');
			$('#nav-sub-menu-' + nav_id).fadeIn('normal');
			//$('#nav-sub-menu-' + nav_id).css('border-top', '1px dashed #525252');
			//$(this).addClass('azure-temp-nav');
			active_id = nav_id;
		}

	}, function()
	{

		//Dont want to process subnav. Trace back to nav parent [azure-nav-main li ul li a]
		if ($(this).parents().eq(3).attr('id') == "azure-nav-main")  return;

		nav_id = nav_from_id($(this).attr("id"));

		revert_timer = setInterval("revert_nav()", 3000);

	});

	$("#azure-nav-main li ul").hover(function()
	{

		clearInterval(revert_timer);

	}, function()
	{

		revert_timer = setInterval("revert_nav()", 3000);

	});


	//Sort out any message boxes
	hook_message_boxes();

	//Sort out tables
	beautify_azure_tables();

	//Slap any filter bars
	init_filter_bars();

	//Orm render pagination
	hook_pagination();

	//Sort out confirm links
	hook_confirm_anchors();

	//Sort out collapsable module boxes
	hook_module_boxes();


});

var dashlet_stack = new Array();
var processing_dashlet_stack = false;
var dashlet_initial_load = false;

function process_dashlet_stack()
{

	//Were doing a dashlet load / refresh
	processing_dashlet_stack = true;
	//Get the next available dashlet
	dashlet_info = dashlet_stack.shift();
	dashlet_id = dashlet_info[0];
	was_modified = dashlet_info[1];
	if (!dashlet_initial_load)
	{
		was_modified = false;
		dashlet_initial_load = true;
	}
	//Work out the target container given the dashlet id
	target_container = '#' + dashlet_id + '-content';
	//Obtain the dashlet load url based the refresh button
	dashlet_url = $('#' + dashlet_id + '-refresh').attr('href');

	$("#" + dashlet_id + "-refresh").fadeOut('slow', function() { $(this).fadeIn('normal') });
	//alert(dashlet_id + "-refresh");

	//Construct our ajax request and handlers
	 $.ajax({	type: "POST",
				url: dashlet_url,
				ifModified: was_modified,
				data: "dashlet_id="+dashlet_id,
				success: 	function(msg)
							{
								//alert('setting markup');
								$(target_container).html(msg);
								if (!was_modified) was_modified = true;
								if (dashlet_stack.length == 0) processing_dashlet_stack = false;
								else process_dashlet_stack();
							},
				error: 		function (XMLHttpRequest, textStatus, errorThrown)
							{
								//alert(textStatus);
								if (dashlet_stack.length == 0) processing_dashlet_stack = false;
								else process_dashlet_stack();
								//null, "timeout", "error", "notmodified", "parsererror"
							}
			});

}

function refresh_dashlet(dashlet_id)
{
	dashlet_stack.push(new Array(dashlet_id, false));
	if (processing_dashlet_stack == false) process_dashlet_stack();
}

function stack_dashlet(dashlet_id, refresh)
{
	dashlet_stack.push(new Array(dashlet_id, true));
	real_refresh = refresh * 1000;
	setTimeout("stack_dashlet('" + dashlet_id + "', " + refresh + ")", real_refresh);
	if (processing_dashlet_stack == false) process_dashlet_stack();
}

function hook_module_boxes()
{

	//Hide any boxes initially
	$('.cpico-collapsable').hide();

	//Set toggles on the boxes
	$('.cpico-toggle').click(function()
							 {
								 //Sort out button image
								 if ($(this).hasClass('cpico-toggle-off')) $(this).removeClass('cpico-toggle-off');
								 else $(this).addClass('cpico-toggle-off');
								 //Slide the content
								 $(this).parents().children('.cpico-collapsable').slideToggle('fast');
								 return false;
							 });

}


function hook_confirm_anchors()
{
	$(".confirm-link").bind('click', function(e)
							 		{
										 e.preventDefault();

										 var orig_loc = $(this).attr('href');

										 jConfirm($(this).attr('rel'),
												  $(this).attr('title'),
												  function(r)
												  {
													  	if (r) window.location = orig_loc;
													  	return false;
												  });
									 });
}



function hook_message_boxes()
{

	$('#message-box-control a').click( 	function()
										{
											$('#message-box-content').slideToggle("fast");
											$('#message-box-hide').toggle();
											$('#message-box-show').toggle();
											return false;
										});

}

function beautify_azure_tables()
{

	$(".azure-sortable").sortable({	handle: '.azure-drag-handle',
									scroll: true,
									containment: '#azure-page-outer',
									cursor: 'move',
									opacity: 0.7});


	$(".azure-stripable tr").hover( function()
	{
		if ((!$(this).hasClass('azure-table-header')) && (!$(this).hasClass('no-stripe')))
		{
			$(this).addClass('azure-table-row-hover');
		}
	},
	function()
	{
		if ($(this).hasClass('azure-table-row-hover')) $(this).removeClass('azure-table-row-hover');
	});

	//Zebra stripe the table on odd cells excluding the header
	$(".azure-zebra tr:nth-child(even)").addClass('azure-table-row-alt');

	//Remove the last row bottom border
	//$(".azure-table tbody tr:last-child").css('border-bottom', 'none');
}


function find_active_nav()
{

	if ($('.active-menu').size() == 0) return false

	var dummy = $('.active-menu').attr("id").split("nav-sub-menu-");
	return dummy[1];

}


function revert_nav()
{

	clearInterval(revert_timer);

	if (active_id != default_id)
	{

		$('#nav-sub-menu-' + active_id).fadeOut('slow', function()
		{
			$('#nav-sub-menu-' + default_id).css('display', 'none');
			$('#nav-sub-menu-' + default_id).css('opacity', '1.0');
			$('#nav-sub-menu-' + default_id).fadeIn('slow');
			//$('#nav-main-item-' + active_id).removeClass('azure-temp-nav');
			//$('#nav-sub-menu-' + active_id).css('border-top', 'none');
			active_id = default_id;
		});

	}

}

function nav_from_id(id)
{
	var dummy = id.split("nav-main-item-");
	return dummy[1];
}

var active_filters = new Array();
var default_filters = new Array();
var filter_revert_timers = new Array();

function split_last_dash(id)
{
	var dummy = id.split("-");
	return dummy[dummy.length-1];
}

function find_table(id)
{
	var dummy = id.split("-");
	return dummy[dummy.length-2];
}

function find_bar(id)
{
	var dummy = id.split("-");
	return dummy[dummy.length-1];
}

function init_filter_bars()
{

	$('.filter-bar-select').each(function()
							     {
									 this_val = $(this).val();
									 this_id = split_last_dash($(this).attr('id'));
									 active_filters[this_id] = this_val;
								 	 default_filters[this_id] = this_val;
								 });

	$('.filter-bars ul').css('display', 'none');
	$('.filter-bars').each(	function()
						  	{
								this_table = split_last_dash($(this).attr('id'));
								active_bar = '#filter-bar-' + this_table + '-' + active_filters[this_table];
						  		$(active_bar).css('display', 'block');
						  	});

	$('.filter-bars ul').css('opacity', '1.0');

	$('.filter-bar-select').change( function() { change_filter_menu(split_last_dash($(this).attr('id')), $(this).val()); });

	$('.filter-bars a').click(function()
							 {
								 table = find_table($(this).parents().eq(1).attr('id'));
								 $('#filter-table-' + table).val(table);
								 $('#filter-column-' + table).val($(this).html());
								 $('#filter-form-' + table).submit();
							 });

	$('.filter-bars').hover(function()
							{
								this_table = split_last_dash($(this).attr('id'));
								clearTimeout(filter_revert_timers[this_table]);
							},
							function()
							{
								this_table = split_last_dash($(this).attr('id'));
								if (active_filters[this_table] != default_filters[this_table]) filter_revert_timers[this_table] = setTimeout(function(){change_filter_menu(this_table, default_filters[this_table]);}, 10000);
							});

}



function change_filter_menu(table, new_filter)
{

	clearTimeout(filter_revert_timers[table]);

	$('#filter-bar-select-' + table).attr('disabled', 'disabled');

	$('#filter-bar-' + table + '-' + active_filters[table])
	.fadeOut('slow',  function()
					  {
							if ((new_filter == default_filters[table]) && ($('#filter-bar-select-' + table).val() != new_filter)) $('#filter-bar-select-' + table).val(new_filter);
							$('#filter-bar-' + table + '-' + new_filter)
							.fadeIn('fast',  function()
											 {
												 active_filters[table] = new_filter;
												 $('#filter-bar-select-' + table).removeAttr('disabled');
												 if (active_filters[table] != default_filters[table])
												 {
													 filter_revert_timers[table] = setTimeout(function(){change_filter_menu(table, default_filters[table]);}, 10000);
												 }
											 });
					  });

}


function hook_pagination()
{

	$('.orm-render-limit').change(function()
								  {
									  $(this).parent('.orm-render-limit-form').submit();
								  });


	/*$('#pagination a').click(function()
							 {
								 $('#orm-render-page-num').val($(this).attr('rel'));
								 $('#orm-render-page').submit();
								 return false;
							 });*/
}

/************************* Excel JS ***********************/

$(function(){
	$('#partnership_tns').change(function()
	{
		var xmlhttp;
		if (window.XMLHttpRequest)
		{
			// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		}
		else if (window.ActiveXObject)
		{
			// code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		else
		{
			alert("Your browser does not support XMLHTTP!");
		}

		xmlhttp.onreadystatechange = function()
		{
			if(xmlhttp.readyState == 4)
			{
				//alert(xmlhttp.responseText);
				$('#family_tns').html(xmlhttp.responseText);
			}
		}

		xmlhttp.open("GET", "http://www.sunderlandssp.co.uk/survey/assets/phpexcel/Ajax/filter.php?partnership="+$('#partnership_tns :selected').val(),true);
		xmlhttp.send(null);

		var xmlhttp2;
		if (window.XMLHttpRequest)
		{
			// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp2 = new XMLHttpRequest();
		}
		else if (window.ActiveXObject)
		{
			// code for IE6, IE5
			xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");
		}
		else
		{
			alert("Your browser does not support XMLHTTP!");
		}

		xmlhttp2.onreadystatechange = function()
		{
			if(xmlhttp2.readyState == 4)
			{
				//alert(xmlhttp.responseText);
				$('#school_tns').html(xmlhttp2.responseText);
			}
		}

		xmlhttp2.open("GET", "http://www.sunderlandssp.co.uk/survey/assets/phpexcel/Ajax/filter.php?family=All Families",true);
		xmlhttp2.send(null);

		if ($('#partnership_tns :selected').val() == "All Partnerships")
		{
			$("#family_tns option[value='All Families']").attr('selected', 'selected');
			$('#family_tns').attr('disabled', 'disabled');
			$('#school_tns').attr('disabled', 'disabled');
		}
		else
		{
			$('#family_tns').removeAttr('disabled');
			$('#school_tns').attr('disabled', 'disabled');
		}
    })
})

$(function(){
	$('#family_tns').change(function()
	{
		if ($('#family_tns :selected').val() == "All Families")
		{
			$("#school_tns option[value='All Schools']").attr('selected', 'selected');
			$('#school_tns').attr('disabled', 'disabled');
		}
		else
		{
			$('#school_tns').removeAttr('disabled');
		}
		var xmlhttp;
		if (window.XMLHttpRequest)
		{
			// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		}
		else if (window.ActiveXObject)
		{
			// code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		else
		{
			alert("Your browser does not support XMLHTTP!");
		}

		xmlhttp.onreadystatechange = function()
		{
			if(xmlhttp.readyState == 4)
			{
				//alert(xmlhttp.responseText);
				$('#school_tns').html(xmlhttp.responseText);
			}
		}

		xmlhttp.open("GET", "http://www.sunderlandssp.co.uk/survey/assets/phpexcel/Ajax/filter.php?family="+$('#family_tns :selected').val(),true);
		xmlhttp.send(null);
    })
})

$(function(){
	$('#partnership').change(function()
	{
		var xmlhttp;
		if (window.XMLHttpRequest)
		{
			// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		}
		else if (window.ActiveXObject)
		{
			// code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		else
		{
			alert("Your browser does not support XMLHTTP!");
		}

		xmlhttp.onreadystatechange = function()
		{
			if(xmlhttp.readyState == 4)
			{
				//alert(xmlhttp.responseText);
				$('#family').html(xmlhttp.responseText);
			}
		}

		xmlhttp.open("GET", "http://www.sunderlandssp.co.uk/survey/assets/phpexcel/Ajax/filter.php?partnership="+$('#partnership :selected').val(),true);
		xmlhttp.send(null);

		var xmlhttp2;
		if (window.XMLHttpRequest)
		{
			// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp2 = new XMLHttpRequest();
		}
		else if (window.ActiveXObject)
		{
			// code for IE6, IE5
			xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");
		}
		else
		{
			alert("Your browser does not support XMLHTTP!");
		}

		xmlhttp2.onreadystatechange = function()
		{
			if(xmlhttp2.readyState == 4)
			{
				//alert(xmlhttp.responseText);
				$('#school').html(xmlhttp2.responseText);
			}
		}

		xmlhttp2.open("GET", "http://www.sunderlandssp.co.uk/survey/assets/phpexcel/Ajax/filter.php?family=All Families",true);
		xmlhttp2.send(null);

		if ($('#partnership :selected').val() == "All Partnerships")
		{
			$("#family option[value='All Families']").attr('selected', 'selected');
			$('#family').attr('disabled', 'disabled');
			$('#school').attr('disabled', 'disabled');
		}
		else
		{
			$('#family').removeAttr('disabled');
			$('#school').attr('disabled', 'disabled');
		}
    })
})

$(function(){
	$('#family').change(function()
	{
		if ($('#family :selected').val() == "All Families")
		{
			$("#school option[value='All Schools']").attr('selected', 'selected');
			$('#school').attr('disabled', 'disabled');
		}
		else
		{
			$('#school').removeAttr('disabled');
		}
		var xmlhttp;
		if (window.XMLHttpRequest)
		{
			// code for IE7+, Firefox, Chrome, Opera, Safari
			xmlhttp = new XMLHttpRequest();
		}
		else if (window.ActiveXObject)
		{
			// code for IE6, IE5
			xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		}
		else
		{
			alert("Your browser does not support XMLHTTP!");
		}

		xmlhttp.onreadystatechange = function()
		{
			if(xmlhttp.readyState == 4)
			{
				//alert(xmlhttp.responseText);
				$('#school').html(xmlhttp.responseText);
			}
		}

		xmlhttp.open("GET", "http://www.sunderlandssp.co.uk/survey/assets/phpexcel/Ajax/filter.php?family="+$('#family :selected').val(),true);
		xmlhttp.send(null);
    })
})

animating = false;
page = "/survey/admin/generate_excel";

$(function() {
	$("#submit_tns").live("click", function() {
		if (animating == true) {
			return false;
		}

		if (!validate_excel_tns()) {
			return false;
		}

		animating = true;

		$("#excel .result").hide();
		$("#excel .wait").show();

		form_data = {
			partnership_tns : $('#partnership_tns :selected').val(),
			family_tns : $('#family_tns :selected').val(),
			school_tns : $('#school_tns :selected').val(),
			submit_tns : 1
		}

		$("#excel").fadeIn(666, function() {
			$.post(page, form_data, function(data) {
				$("#excel-link").attr("href", data);

				$("#excel .wait").fadeOut(666, function() {
					$("#excel .result").fadeIn(666, function() {
						animating = false;
					});
				});
			});
		});
		return false;
	});

	$("#submit_all").live("click", function() {
		if (animating == true) {
			return false;
		}

		if (!validate_excel()) {
			return false;
		}

		animating = true;

		$("#excel .result").hide();
		$("#excel .wait").show();

		form_data = {
			partnership : $('#partnership :selected').val(),
			family : $('#family :selected').val(),
			school : $('#school :selected').val(),
			family_compare : $('#family_compare').is(':checked'),
			submit_all : 1
		}

		$("#excel").fadeIn(666, function() {
			$.post(page, form_data, function(data) {
				$("#excel-link").attr("href", data);

				$("#excel .wait").fadeOut(666, function() {
					$("#excel .result").fadeIn(666, function() {
						animating = false;
					});
				});
			});
		});
		return false;
	});
});


function validate_excel_tns()
{
	if ($('#partnership_tns :selected').val() == "All Partnerships" || $('#family_tns :selected').val() == "All Families")
	{
		$('.message-box-tns').fadeIn(666);
		return false;
	}
	else
	{
		$('.message-box-tns').hide();
		return true;
	}
}

function validate_excel()
{
	if ($('#partnership :selected').val() == "All Partnerships" || $('#family :selected').val() == "All Families")
	{
		$('.message-box-all').fadeIn(666);
		return false;
	}
	else
	{
		$('.message-box-all').hide();
		return true;
	}
}
