//dynamiclist_init = function () {};
jQuery(document).ready(
	function() {
		myBehaviors = new oAjaxAttacher(
			'#listings',					//linksource
			'#itemView',		//inktarget
			'#main',						//responseFilter,
			'.messages',					//submitResponseFilter
			[], //Preserve ids as classes
			[collapseAutoAttach, activeselectAutoAttach, uploadAutoAttach,dynamiclist_init],	//external js callbacks
			".messages:contains('updated'), .messages:contains('created'), .messages:contains('deleted')", //triggers
			archiveTrigger,		//triggercallback
			"Loading...",	//loading text,
			{'formLink' : '#main', 'listing' : '#itemView', 'listing active' : '#itemView'}, //specific filters(value) for links with classes(key)
			{0:'external'}	//exclude these classes from ajax loads
		);
		myBehaviors.linkTarget = jQuery(myBehaviors.linkTarget);
		myBehaviors.linkSource = jQuery(myBehaviors.linkSource);
		attachLinksToTarget(myBehaviors.linkSource, myBehaviors);
		
	}
);

function doNothing() {
	return;
}
var archiveTrigger = function (scope, oOptions) {
	var urlHalves = String(document.location).split('?');
	jQuery.ajax({
		oOptions : oOptions,
		url: location.href,//'/archive',
		data: urlHalves[1],
		dataType:"html",
		complete: function(res, status) {
			jQuery("#listings").html('Loading...');
			if ( status == "success" || status == "notmodified" ) {
				var responseText = res.responseText;
			
				//Hide the link target to our manipulations to it do not look messy.
				jQuery("#listings").hide();
				
				//Store the response in a temporary jQuery object so we can more easily operate on it
				var temp = jQuery("<div/>").prepend(responseText.replace(/<script(.|\s)*?\/script>/g, ""));
							
							
				//Filter the html response by the designated responseFilter.  If that element is not found, simply inject all the HTML
				if(jQuery('#listings', temp).length) {
					jQuery("#listings").html(jQuery('#listings', temp).html());
				}
				else {
					jQuery("#listings").html(temp.html());
				}
					
				
				jQuery("#listings").show("fast");
				attachLinksToTarget(jQuery("#listings"), this.oOptions);	
			}
			else {
				jQuery("#listings").html("Error loading page, please try again later.")
			}
		}
	});
}


var aaLinkId;
var aaSubmitId;
oAjaxAttacher = function (linkSource, linkTarget, responseFilter, submitResponseFilter, idsToClasses, jsResponseCallbacks, responseTriggers, triggerHandler, loadingHTML, specificFilters, excludeClasses) { 
	this.linkSource = linkSource;
	this.linkTarget = linkTarget;
	this.responseFilter = responseFilter;
	this.submitResponseFilter = submitResponseFilter;
	this.idsToClasses = idsToClasses;
	this.jsResponseCallbacks = jsResponseCallbacks;
	this.responseTriggers = responseTriggers;
	this.triggerHandler = triggerHandler;
	this.loadingHTML = loadingHTML;
	this.specificFilters = specificFilters;
	this.excludeClasses = excludeClasses;
};

attachLinksToTarget = function(scope,oOptions) {
	clickHandler = 
			function (event) {
				//custom stuff for jobcenter
				//var target = jQuery("#itemView");
				//target[0].parentNode = this.parentNode;
				jQuery("#itemView").remove();
				jQuery(this).after('<div id="itemView"></div>');
				
				//Don't attach to links with the href '#' as they obviously are performing some js function that we'll interfere with
				if(this.href == this.baseURI + "#" || this.onclick) {
					return false;
				}
				
				//Don't attach to links with a class in our exclusion list
				for(i in oOptions.excludeClasses) {
					if(this.className == oOptions.excludeClasses[i]) {
						return true;
					}
				}
				var checkId = this.id.split('_');
				if(checkId[0] == 'linkid') {
					aaLinkId = this.id;
				}
				
				event.data.targetLoading(event.data);
				
				var myEvent = function(){};
				myEvent.data = event.data;
				myEvent.currentTarget = function(){};
				var n;
				if(event.srcElement) {n = event.srcElement;}
				else if(event.currentTarget) {n = event.currentTarget;}
				else if(event.target) {n = event.target;}
				while (!n.className && n.tagName != "BODY") {
					n = n.parentNode;
				}
				myEvent.currentTarget.className = n.className;
//				var eventNonRefCopy = cloneObject(event);
				jQuery.ajax({
					oOptions: myEvent,
					url: this.href + "&js=1",
					dataType:"html",
					complete: function(res, status) {
						if ( status == "success" || status == "notmodified" ) { 
							var oOptions = this.oOptions;
							//this.oOptions.data = oOptions;
							var responseText = res.responseText;
							
							//Hide the link target to our manipulations to it do not look messy.
							this.oOptions.data.linkTarget.hide();
							
							//Store the response in a temporary jQuery object so we can more easily operate on it
							responseText = responseText.replace(/<script(.|\s)*?\/script>/g, "");
							var temp = jQuery("<div/>").prepend(responseText);
							responseText = undefined;
							delete responseText;
							if(jQuery(this.oOptions.data.responseTriggers, temp).length) {
								this.oOptions.data.triggerHandler(temp, this.oOptions);
							}
							/*
							//Store classes to be preserved
							var storeClasses = new Array;
							var tempIdStorage;
							if(this.oOptions.data.idsToClasses.length > 0) {
								for(var i in this.oOptions.data.idsToClasses) {
									tempIdStorage = jQuery(this.oOptions.data.idsToClasses[i], temp);
									if(tempIdStorage.length) {
										storeClasses.push(tempIdStorage.attr("class"));
									}
								}
							}
							*/
							//set the response filter to use
							if(this.oOptions.data.specificFilters[this.oOptions.currentTarget.className]) {
								var responseFilter = this.oOptions.data.specificFilters[this.oOptions.currentTarget.className];
							}
							else {
								var responseFilter = this.oOptions.data.responseFilter;
							}
							//Filter the html response by the designated responseFilter.  If that element is not found, simply inject all the HTML
							if(jQuery(responseFilter, temp).length) {
								//this.oOptions.data.linkTarget.html(jQuery(responseFilter, temp).html());
								jQuery("#itemView").html(jQuery(responseFilter, temp).html());
							}
							else {
								//this.oOptions.data.linkTarget.html(temp.html());
								gebi(this.oOptions.data.linkTarget[0].id).innerHTML = temp[0].innerHTML
							}
							temp = undefined;
							
							/*
							//preserve classes if any are stored
							if(storeClasses.length > 0) {
								//clear existing classes
								this.oOptions.data.linkTarget.attr({ "class" : ""});
								//add classes
								for(var i in storeClasses) {
									this.oOptions.data.linkTarget.addClass(storeClasses[i]);
								}
							}
							*/
							//call other js functions that may need to responsd to the new html
							for(var i in this.oOptions.data.jsResponseCallbacks) {
								this.oOptions.data.jsResponseCallbacks[i]();
							}
							//this.oOptions.data.linkTarget.show("fast");
							jQuery("#itemView").show("fast");
							attachLinksToTarget(jQuery("#itemView"), this.oOptions.data);	
							attachSubmitsToTarget(jQuery("#itemView"),this.oOptions.data);
						}
						else {
							this.oOptions.data.linkTarget.html("Error loading page, please try again later.")
						}
					}
				});
			return false;
			}
			jQuery("a", scope).bind("click", oOptions, clickHandler)
		
}
attachSubmitsToTarget = function(scope, oOptions) {
	//var responseFilter = (responseFilter == null) ? this.submitResponseFilter : responseFilter;
		
		submitHandler =	function (event) {
				//special case for the file attachment module: return true so it can do its thing
				if(this.id == 'attach') {
					return true;
				}
				aaSubmitId = this.id;
				//Add our op value to the form since drupal needs it
				jQuery(this).after('<input type="hidden" name="op" value="' + this.value +'">');
				jQuery(this.form).ajaxSubmit({ oOptions:event.data, success: 
					function (responseText, statusText, form, self) {
						
						if (statusText == "success") {
							//Hide the link target to our manipulations to it do not look messy.
							self.oOptions.linkTarget.hide();
							
							//Store the response in a temporary jQuery object so we can more easily operate on it
							var temp = jQuery("<div/>").prepend(responseText.replace(/<script(.|\s)*?\/script>/g, ""));
							responseText = undefined;
							delete responseText;
							if(jQuery(self.oOptions.responseTriggers, temp).length) {
								self.oOptions.triggerHandler(temp, self.oOptions);
							}
							
							//Store classes to be preserved
							var storeClasses = new Array;
							var tempIdStorage;
							if(self.oOptions.idsToClasses.length > 0) {
								for(var i in self.oOptions.idsToClasses) {
									tempIdStorage = jQuery(self.oOptions.idsToClasses[i], temp);
									if(tempIdStorage.length) {
										storeClasses.push(tempIdStorage.attr("class"));
									}
								}
							}
							//Filter the html response by the designated responseFilter.  If that element is not found, simply inject all the HTML
							if(jQuery(self.oOptions.submitResponseFilter, temp).length) {
								self.oOptions.linkTarget.html(jQuery(self.oOptions.submitResponseFilter, temp).html());
							}
							else if(jQuery(self.oOptions.responseFilter, temp).length) {
								self.oOptions.linkTarget.html(jQuery(self.oOptions.responseFilter, temp).html());
							}
							
							else {
								self.oOptions.linkTarget.html(temp.html());
							}
							temp = undefined;
							//preserve classes if any are stored
							if(storeClasses.length > 0) {
								//clear existing classes
								self.oOptions.linkTarget.attr({"class":""});
								//add classes
								for(var i in storeClasses) {
									self.oOptions.linkTarget.addClass(storeClasses[i]);
								}
							}
							
							//call other js functions that may need to responsd to the new html
							for(var i in self.oOptions.jsResponseCallbacks) {
								self.oOptions.jsResponseCallbacks[i]();
							}
							//self.oOptions.linkTarget.show("fast");
							attachLinksToTarget(jQuery("#itemView"));	
							attachSubmitsToTarget(jQuery("#itemView"));
							
						}
						else {
							self.oOptions.linkTarget.html("Error submitting form, please try again later.")
						}
					}
				});
				event.data.targetLoading(event.data);
				return false;
			}
		jQuery(":submit", scope).bind("click", oOptions, submitHandler)
		jQuery(":image", scope).bind("click", oOptions, submitHandler)
}

oAjaxAttacher.prototype.targetLoading = function(oOptions) {
	//this.linkTarget.html(oOptions.loadingHTML);
	gebi(this.linkTarget[0].id).innerHTML = oOptions.loadingHTML;
}