﻿$(document).ready(function() { initializeEvents(); });

function initializeEvents() {
}

// Binds the click toggles to all expanders on page load and postbacks
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(initializePostback);

// Binds the click toggles to all expanders
function initializePostback() {
	bindExpanders();
	bindAutogrow();
	stripeTables();
}

function bindAutogrow()
{
	$("TEXTAREA.autogrowing").autogrow();
}

function bindExpanders() {
	// Unbind to prevent multiple bindings
	$('.expander > .header').unbind('click', expanderToggle);

	// Bind
	$('.expander > .header').click(expanderToggle);

	// Restore state
	$('.expander > .header').each(function() {
		var parent = $(this).parent();

		if(parent.attr('id') == null || parent.attr('id') == '')
			return;

		// Get the path to the element
		var path = parent.data('expander_path');

		if(path == null) {
			path = getElementPath(parent);
			parent.data('expander_path', path);
		}

		// Get the cookie
		var cookieName = "expander_" + path;
		var cookieValue = $.cookie(cookieName);

		if(cookieValue == 'expanded')
			parent.toggleClass('expanded');
	});
}

// Generate the path through HTML to the element
function getElementPath(element) {
	var path = element.parents().andSelf().map(function() {
		// Tag
		var pathElement = this.tagName;

		// ID
		if(this.id != null && this.id != '')
			pathElement += '#' + this.id;

		// Classes
		if(this.className != null && this.className != '')
			pathElement += '.' + String(this.className).replace(/ /g, '.');

		return pathElement;
	}).get().join('>');

	return path;
}

function expanderToggle() {
	var parent = $(this).parent();

	// Toggle expansion
	parent.children('.body').slideToggle('slow', function() {
		// IE7 has a bug where it will not display the body of the 
		// expander until something causes the page to re-layout.
		// Force a layout by making the text bold, then reverting it.
		setTimeout(function() { 
			var fw = parent.css("font-weight");
			parent.css("font-weight", "600");
			parent.css("font-weight", fw);
		}, 1);
	});
	
	parent.toggleClass('expanded');

	if(parent.attr('id') == null || parent.attr('id') == '')
		return;

	// Get the path to the element
	var path = parent.data('expander_path');

	if(path == null) {
		path = getElementPath(parent);
		parent.data('expander_path', path);
	}

	// Set or clear the cookie
	var cookieName = "expander_" + path;
	var cookieOpts = { expires: 2 };
	
	if(parent.hasClass('expanded'))
		$.cookie(cookieName, 'expanded', cookieOpts);
	else
		$.cookie(cookieName, null, cookieOpts);
}

function stripeTables() {
	// Stripe every other row
	$('table.autoStripe > tbody > tr:even').addClass('evenStripe');
	$('table.autoColumnStripe > tbody > tr > td:nth-child(2n)').addClass('evenColumnStripe');


	// Stripe every two rows
	createAutoStripe('autoDoubleStripe', 2);

	// Stripe every three rows
	createAutoStripe('autoTripleStripe', 3);
}

function createAutoStripe(className, rowInterval) {
	var baseQuery = 'table.' + className + ' tr:nth-child(' + String(rowInterval * 2) + 'n-';
	var baseQueryClose = ')';
	
	for(var i = 0; i < rowInterval; i++)
		$(baseQuery + String(i) + baseQueryClose).addClass('evenStripe');
}

function expandSingleResultExpander(parentElementId) {
	var resultExpanders = $('#' + parentElementId + ' .expander');

	if (resultExpanders.length == 1)
		resultExpanders.addClass('expanded');
}

function AutoSearch(containerId, textboxId, refreshButtonId, clearButtonId, defaultFocus) {
	var textbox = $('#' + textboxId);
	var refreshButton = $('#' + refreshButtonId);
	var clearButton = $('#' + clearButtonId);
	var refreshDelayTimer = null;

	Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function() { expandSingleResultExpander(containerId); });

	$(document).ready(function() {
		textbox.keyup(function(event) {
			if (refreshDelayTimer !== null)
				clearTimeout(refreshDelayTimer);

			refreshDelayTimer = setTimeout(function() {
				refreshButton.click();
			}, 250);
		});

		clearButton.click(function(event) {
			textbox.val('');
			textbox.keyup();
		});
		
		if(defaultFocus != false)
			textbox.focus();
	});
}

function FrameContentManager(pathBase) {
	if(pathBase[pathBase.length - 1] != '/')
		pathBase + '/';

	this._materialPath = pathBase + "Material.aspx";
	this._videoPath = pathBase + "Video.aspx";
}

FrameContentManager.prototype._materialPath = null;
FrameContentManager.prototype._videoPath= null;

FrameContentManager.prototype._invokeFrame = function(url, className) {
	$("body > iframe." + className).remove();
	$("<iframe src='" + url + "' frameborder='0' width='0' height='0' class='" + className + "'></iframe>").appendTo(document.body);
}

FrameContentManager.prototype.invokeVideo = function(id) {
	this._invokeFrame(this._videoPath + "?id=" + id + "&run=true", "videoFrame");
}

FrameContentManager.prototype.invokeMaterial = function(id) {
	this._invokeFrame(this._materialPath + "?id=" + id + "&run=true", "materialFrame");
}

function bindViewItemExpanders() {
	$(this).next('.actionContainer:first').slideToggle();
	$(this).closest('.ViewItemContainer').siblings('.ViewItemContainer').find('.actionContainer').slideUp();
}

function makeFixedTable(tableContainer) {
	var container = $(tableContainer);
	var table = container.children("table:first");

	// Save original column widths
	var columnWidths = new Array();
	table.find('thead tr th').each(function(idx, el) {
		columnWidths[idx] = $(el).width();
	});

	// Create new layout
	var fixedHead = $("<table class='fixedHead'></table>").prependTo(container);
	table.children("thead").appendTo(fixedHead);

	// Setup scrolling. It's functional, not value-based.
	container.scroll(function() {
		var x = container.scrollLeft;
		var y = container.scrollTop;
		
		fixedHead.scrollLeft = x;
		//		$(mainid + " ." + options.classColumn + " > .fixedTable")[0].scrollTop = y;
		//		$(mainid + " .fixedContainer > ." + options.classHeader)[0].scrollLeft = x;
		//		$(mainid + " .fixedContainer > ." + options.classFooter)[0].scrollLeft = x;


	});

	// Resize everything to be as it was
	fixedHead.find('thead tr th').each(function(idx, el) {
		$(el).width(columnWidths[idx]);
	});

	table.find('tbody tr td').each(function(idx, el) {
		$(el).width(columnWidths[idx]);
	});
}