GENTICS.PortletReload = {};

GENTICS.checkConfirmValue = false;
GENTICS.confirmValue = 
GENTICS.confirm = function (msg) {
	GENTICS.checkConfirmValue = true;
	GENTICS.confirmValue = confirm(msg);
}

/**
 * On DOM ready, remove previously added event listeners
 * and add them again.
 */
GENTICS.PortletReload.create = function() {
	jQuery().ready(function() {
		jQuery("a.ajaxReloadUrl").unbind("click", GENTICS.PortletReload.aClickFunction);
		jQuery("form.ajaxReloadUrl").unbind("submit");
		GENTICS.PortletReload.replaceAjaxReloadUrls();

		// post processing
		// attachEventHandler();
	});
}

/**
 * Replace links (<a href>) and forms (<form>) actions by AJAX calls
 * Only replace links for portlets where reloading is enabled
 * (class "gentics-portletreload")
 */
GENTICS.PortletReload.replaceAjaxReloadUrls = function() {
	// for each portlet
	jQuery(".gentics-portletreload").each(function() {
		var aMatcher = "";
		var formMatcher = "";
		// if replace-all is set, replace all "a" and "form" elements
		if (jQuery(this).hasClass("gentics-portletreload-replace-all")) {
			aMatcher = "a";
			formMatcher = "form";
		} else {
			// if replace-all not set, only replace "a" and "form" elements that have the
			// defined css class
			// get a list of all classes that start with "gentics-portletreload-classes-"
			var classes = jQuery.grep(jQuery(jQuery(this).attr("class").split(" ")), function(elem) {
				return elem.substr(0, "gentics-portletreload-classes-".length) == "gentics-portletreload-classes-"; 
			});
			jQuery(classes).each(function() { 
				var class_str = this.substring("gentics-portletreload-classes-".length);
				aMatcher += ",a." + class_str;
				formMatcher += ",form." + class_str;
			});
			aMatcher = aMatcher.substring(1);
			formMatcher = formMatcher.substring(1);
		}

		// if replace for "a" elements is enabled, set click function
		if (jQuery(this).hasClass("gentics-portletreload-replace-link")) {
			jQuery(this).find(aMatcher).each(function(){
				if (!jQuery(this).hasClass("gentics-portletreload-dontreplace-link")){
					jQuery(this).click(GENTICS.PortletReload.aClickFunction);
				}
			});
		}
		// if replace for "form" elements is enabled, set submit function
		if (jQuery(this).hasClass("gentics-portletreload-replace-form")) {
			jQuery(this).find(formMatcher).each(function(){
				jQuery(this).bind("submit", function(){ GENTICS.addInProcessIndicator(); });
			});
			jQuery(this).find(formMatcher).ajaxForm({
				success: function(data) {
					data = eval("(" + data + ")");
					GENTICS.processResult(data);
				},
				data: {
					"gentics.rl": "true"
				}
			});
		}
	});
	if (GENTICS.DragDrop) {
		GENTICS.DragDrop.create();
	}
}

/**
 * Instead of a page refresh, send the URL as AJAX and append
 * the "gentics.rl" parameter to trigger JSON response
 */
GENTICS.PortletReload.aClickFunction = function() {
	// "this" is the current url, use it to fetch the data
	var send = true;
	if (GENTICS.checkConfirmValue && !GENTICS.confirmValue) {
		send = false;
	}
	if (send){
		GENTICS.addInProcessIndicator();
		jQuery.getJSON(this.href, {"gentics.rl": "true"}, function(data) {
			GENTICS.processResult(data);
		});
	}
	GENTICS.checkConfirmValue = false;
	return false;
}

/**
 * Replace portlet with returned data
 * data.portletPosition: the position where the portlet has to be placed
 * data.portletPositionIndex: the index within the position where the portlet
 *                            has to be placed
 * data.portletContent: the new HTML content for the portlet
 */
GENTICS.PortletReload.renderPortlet = function(data) {
	if (GENTICS.inprogress) {
		// user drags a portlet - do nothing for now.
		// (TODO: maybe set a timeout so the action can be done later?)
		GENTICS.forceReload = true;
		return false;
	}
	var existingPortlet = jQuery("[class*='gentics-portletreload-position-" + data.portletPosition + "'] [class*='gentics-portlet']:eq(" + data.portletPositionIndex + ")");
	if (existingPortlet.length > 0) {
		existingPortlet.replaceWith(data.portletContent);
	} else {
		jQuery("[class*='gentics-portletreload-position-" + data.portletPosition + "']").append(data.portletContent);
	}
	// re-attach all event handlers
	GENTICS.PortletReload.replaceAjaxReloadUrls();
	
	// post processing
	attachEventHandler();
}

