$(document).ready(function() {
	// *** CONFIGURATION *** //
	// What attribute to look for for handling divs; ideal default would be ID but that's been appropriated for CSS purposes in some areas of the site
	triggerAttribute = "handle"; // What attribute is set on the divs we need to manipulate
	
	// Which attributes carry meaningful data for interacting via AJAX
	validAttributes = new Array("category","year","weight","debug");
	
	// Default class on which to search for attributes
	//defaultClass = "article";
	
	// Should figure a more elegant way to do this:
	openDiv = "[handle='0'] ,[handle='1']"; // jQuery selector statement to identify the div to open by default
	
	// *** FUNCTIONS *** //
	// Check if a term is in the array args
	// (e.g. if('key' in in_array(parameters)) { ... }
	var in_array = function(args) {
		var object = {};
		//var array = (isArray(args)) ? args : parameters;
		for(var i=0;i < args.length; i++) {
			object[args[i]] = '';
		}
		return object;
	}

	// *** * *** //
	
	// Toggles divs with an animation so only one is visible at a time	
	toggleDivs = function(triggerAttribute,toggled) {
		if(toggleCount > 1) {
			$.each($("div[" + triggerAttribute + "][active='yes']"), function() {
				if(($(this).css("display")  == "none") && ($(this).attr(triggerAttribute) == toggled)) {
					$(this).show("normal");
					$(this).css({ "display" : "block" });
				} else if (($(this).css("display") == "block") && ($(this).attr(triggerAttribute) !== toggled)) {
					$(this).hide("normal");
					$(this).css({ "display" : "none" });
				}
			});
		} else {
			shownDiv = $("div[" + triggerAttribute + "][active='yes']");
			if(shownDiv.css("display") == "none") {
				shownDiv.show("normal");
				shownDiv.css({ "display" : "block"});
			} else {
				shownDiv.hide("normal");
				shownDiv.css({ "display" : "none" });
			}
		}
	}
	
	// Parse data:value pairs
	// Do we still need this?
	parseValues = function(parameters) {
		// The return is a collection of key/value pairs
		var queryStringDictionary = {};
		// Gets the query string, starts with '?'
		if (!parameters) {
			return {};
		}
		// '&' seperates key/value pairs
		var pairs = parameters.split("&");
		// Load the key/values of the return collection
		for (var i = 0; i < pairs.length; i++) {
			var keyValuePair = pairs[i].split("=");
			queryStringDictionary[keyValuePair[0]] = keyValuePair[1];
		}
		return queryStringDictionary;
	}
	
	getParameters = function(target,trigger,switchAttr) {
		queryParams = {};

		if(trigger == 'a') {
			var attrs = $("div[" + triggerAttribute + "='" + target + "'] a[switch='" + switchAttr + "']")[0].attributes;
			var masterParams = $("div[" + triggerAttribute + "='" + target + "']")[0].attributes;
			for (var i=0;i < attrs.length;i++) {
				if(attrs[i].nodeName in in_array(validAttributes)) {
					queryParams[attrs[i].nodeName] = attrs[i].nodeValue;
				}
			}
			for (var n=0;n<masterParams.length;n++) {
				if(!(masterParams[n].nodeName in in_array(attrs))) {
					//Do nothing since the logic doesn't work as expected here
				} else if (masterParams[n].nodeName in in_array(validAttributes)) {
					// Somehow the logic is operating backwards here!
					queryParams[masterParams[n].nodeName] = masterParams[n].nodeValue;
				}
			}
		//Normal operation not via subnavigation
		} else {
			var attrs = $("div[" + triggerAttribute + "='" + target + "']")[0].attributes;
			for (var i=0;i < attrs.length;i++) {
				if(attrs[i].nodeName in in_array(validAttributes)) {
					queryParams[attrs[i].nodeName] = attrs[i].nodeValue;
				}
			}
		}
	}
	
	loadContent = function(target,trigger,switchAttr) {
	// This will load content into a targeted (toggled) div, based on the defined triggerAttribute
	
	// Start building a set of parameters to pass via a jQuery load() request
	// 'status' will need to be determined programmatically at some point, along with other params
	
	//parsed = parseValues(parameters);
		getParameters(target,trigger,switchAttr);
		
		// If we're in admin, we need to tell our query target that we want special privileges and tell it to look in the right place for data
		if(location.pathname.substring(0,7) == "/admin/") {
			queryParams.edit = "y";
			dataSource = "../press-room/press-list.php";
		} else {
			dataSource = "./press-room/press-list.php";
		}
		
		/*
		for (var key in parsed) {
			//eval("queryParams." + key + " = 'parsed[' + " + key + " + ']'"); //parsed[" + key + "]");
			eval("queryParams." + key + " = '" + parsed[key] + "'");
			//queryParams.length++;
			printOut = queryParams[key] + "\n"; // DEBUG
		}
		*/
		queryParams.length = 0;
		
		// Assemble our parameters into an object that ultimately gets parsed as a jQuery function, since jQuery can't seem to evaluate variables within an object
		for(key in queryParams) {
			if(!queryParams.parsed) {
				queryParams.parsed = key + ": \'" + queryParams[key] + "\'";
				queryParams.length++;
			} else if ((key != 'length' ) && (key != 'parsed')) {
				queryParams.parsed = queryParams.parsed + ", " + key + ": \'" + queryParams[key] + "\'";
				queryParams.length++;
			}
		}
		
		// Wrap our parameters up as an object
		queryParams.parsed = "{ " + queryParams.parsed + " }";
		//alert(queryParams.parsed);
		
		// Build our jQuery load() parameters...
		loadProperties = "'" + dataSource + "', " + queryParams.parsed;
		
		//alert(loadProperties);
		
		//... and wrap it up into the jQuery we need to manipulate the page...
		//doThis = '$("div[' + triggerAttribute + '=\'' + target + '\']").load(' + loadProperties;
		//if(location.pathname.substring(0,7) == "/admin/") {
		//	doThis = doThis + ", function() { adminLinks('" + target + "'); }";
		//}


		var doThis = '$("div[' + triggerAttribute + '=\'' + target + '\']").load(' + loadProperties;
		doThis = doThis + ", function() { archiveLinks('" + target + "'); ";
		if(location.pathname.indexOf('/admin/') != -1) {
			doThis = doThis + "adminLinks('" + target + "');";
		}
		
		doThis = doThis + '} );';
		
		// Do it!
		eval(doThis);
		
		return false;
	}
	
	// *** INITIALIZE THE PAGE *** //
	// Show the div(s) with the attribute(s) defined as default options
	$(openDiv).show();
	$(openDiv).css({ display : "block" });
	
	// Find divs to do things with
	var divs = $("[" + triggerAttribute + "]");
	
	var activeDivs = $("div[" + triggerAttribute + "][active='yes']");
	toggleCount = activeDivs.length;
	//alert(toggleCount);
	
	/*
	$.each(divs, function() {
		var attrs = this.attributes;
		for (var i=0;i < attrs.length;i++) {
			if(attrs[i].nodeName in in_array(validAttributes)) {
				alert(attrs[i].nodeName + " is " + attrs[i].nodeValue);
			}
		}
	});
	*/

	// Add links for archives
	var archiveLinks = function(loaded) {
	// This adds functionality to the links in loaded content with an 'action' attribute
	// triggerAttribute is the attribute set in our config which tells us how to look for divs to manipulate
//		var $which = $(event.target);
//		if ($which.attr("switch") !== "undefined") {
//			var which = $which.attr("switch");
//			alert("Target type: " + $which.attr("switch"));
//		}

		$("div[" + triggerAttribute + "='" + loaded + "'] a[year]").click(function(e) {
			var $tgt = $(e.target);
				//alert($tgt.attr("switch"));
				var switchAttr = $tgt.attr("switch");
			loadContent(loaded,'a',switchAttr);
		});
	}


	// When page ready, load content into all divs with the 'category' attribute
	$.each($("div[" + triggerAttribute + "]"),function() {
		//query = triggerAttribute + "=" + $(this).attr(triggerAttribute);
		target = $(this).attr(triggerAttribute);
		loadContent(target,'div',''); 
	});
	
	// Attach a toggle action to each toggle anchor
	$("a.toggle").click(function() {
		// Ultimately we should find a way to dynamically point to the div to toggle, potentially through a config.js
		toggled = $(this).parent('div').parent("div").next("div").attr(triggerAttribute);
		
		toggleDivs(triggerAttribute,toggled);
		
	});
	
});

