/* Common JS file for the master controller */

/**
 * Function to route a link. Looks for custom function
 * based off of the given component and action.
 * This will attempt to look for a fn to handle an Ajax request if
 * Ajax is currently turned on.
 */
var oneroute = function(el, component, action, args, ajax) {
	// Check for all arguments
	if (!component || !action) {
		return false;
	}
	
	// Default ajax to 'yes'
	if (!ajax) {
		ajax = 'yes';
	}
	
	// Build string link
	var el_href = onecontroller_current_page_url + '/' + component + '/' + action;
	if (args.length > 0) {
		el_href += args;
	}
	
	// Append current_page_url to url (if independent output)
	if (onecontroller_output_method == 'independent') {
		if (el_href.indexOf('?') > -1) {
			el_href += '&onepage_url=' + onecontroller_current_page_url_encoded;
		}
		else {
			el_href += '?onepage_url=' + onecontroller_current_page_url_encoded;
		}
	}
	
	// If Javascript function to handle this component/action does not exist,
	// allow link to submit. Also, if onecontroller_use_ajax is set to false, allow
	// link to submit.
	var fn_found = false;
	var fn_name = "onecontroller_" + component + "_" + action;
	var eval_str = "if (window." + fn_name + ") {fn_found = true;}";
	eval(eval_str);
	
	// If no fn found, see if we want to do a basic ajax request, otherwise, let
	// the page link submit
	if (!fn_found) {
		if (onecontroller_use_ajax != 'no' && 
		    (
		      ajax == 'preferred' || 
		      (ajax == 'yes' && onecontroller_use_ajax == 'yes')
		    )
		   ) 
		{
			// Make Ajax request
			OneController.ajax_request(el_href, 'OneController.ajax_response_to_container');
			
			return false;
		}
		else {
			// Allow link to submit
			return true;
		}
	}
	
	// Clear focus on link
	var onecontroller_container = document.getElementById('one_controller_container');
	onecontroller_container.blur();
	
	// Call custom function and return its value
	return eval(fn_name + "(el, el_href, component, action, args, ajax);");
};


/**
 * Main OneController class to handle basic common functionality for the
 * Page Controller.
 */
OneController = function() {
	
	return {
		
		/**
		 * Parse the url query string into an associative array.
		 */
		parseargs: function(args) {
			var arguments = new Array();
			if (args.length > 0) {
				var args_array = args.split("&");
				
				// Get key and value for each argument
				for (var i = 0; i < args_array.length; i++) {
					// Split key/value for this arg
					var arg = args_array[i].split("=");
					var key = arg[0];
					
					// Add to argurments array
					arguments[key] = arg[1];
				}
			}
			
			return arguments;
		},
		
		/**
		 * Perform an Ajax request with the given parameters.
		 * 
		 * @param ajax_url       url to use in ajax request
		 * @param callback_fn    name of fn to load during callback
		 * @param set_form       ID of form to attach to Ajax request
		 * @param file_upload    True, if the set_form is submitting a file upload
		 */
		ajax_request: function(ajax_url, callback_fn, set_form, file_upload) {
			// Make sure all of the yui js files have loaded
			if (typeof YAHOO == "undefined") {
				// Attempt to load yui files if we haven't already attempted
				if (!onecontroller_loading_yui) {
					for (var i = 0; i < onecontroller_js_files.length; i++) {
						dynamic_load_file(onecontroller_js_files[i], 'js');
					}
					onecontroller_loading_yui = true;
				}
				
				// Wait .4 seconds and try again
				setTimeout(function() {
					ajax_request(ajax_url, callback_fn, set_form, file_upload);
				}, 400);
				return;
			}
			
			// Show ajax loading indicator
			OneController.show_ajax_loading();
			
			// Start arguments string to pass some basic info to this ajax call
			var arguments_str = '&onepage_url=' + onecontroller_current_page_url_encoded;
			
			// Append a var saying this is an ajax request
			arguments_str += '&output_method=ajax';
			
			// Attach form to request
			if (set_form) {
				if (!file_upload) {
					file_upload = false;
				}
				YAHOO.util.Connect.setForm(set_form, file_upload);
			}
			
			// Determin which separator (?, &) to use for appending ms argument
			if (ajax_url.indexOf('?') > -1) {
				var ms_separator = '&';
			}
			else {
				var ms_separator = '?';
			}
			
			// Load viewboard content
			var connectionObject = YAHOO.util.Connect.asyncRequest(
				'POST',
				ajax_url
					+ ms_separator + 'ms=' + new Date().getTime(),
				{
					success: function(response) {eval(callback_fn + '(response);');},
					timout: onecontroller_ajax_timeout
				},
				arguments_str
			);
		},
		
		/**
		 * Default function to handle a controller Ajax request. Prints the responseText
		 * of this request to the main one_controller_container.
		 */
		ajax_response_to_container: function(request) {
			document.getElementById('one_controller_container').innerHTML = request.responseText;
		},
		
		/**
		 * Dynamically loads a file of type 'type' (js/css) anytime during 
		 * program execution.
		 * 
		 * @param String  url   URL of file to load
		 * @param String  type  Type of file being loaded [js, css]
		 */
		dynamic_load_file: function(url, type) {
			if (type == 'js') {
		  		var e = document.createElement("script");
		  		e.type = "text/javascript";
		  		e.src = url;
			}
			else if (type == 'css') {
		  		var e = document.createElement("link");
		  		e.type = "text/css";
		  		e.rel = "stylesheet";
		  		e.href = url;
			}
			else { return; }
			
			// Append file to header
			document.getElementsByTagName("head")[0].appendChild(e);
		},
		
		/**
		 * Show loading indicator usually displayed while performing an Ajax
		 * request.
		 */
		show_ajax_loading: function() {
			var newtext = "<div id='onecontrollerajaxcontainer' style='width:100%;margin-top:2px;position:absolute;text-align:center;'><img src='/resources/images/admin/indicator.gif' style='width:25px;margin:0 auto;' /></div>";
			document.getElementById('one_controller_container').innerHTML = newtext + document.getElementById('one_controller_container').innerHTML;
		}
	
	};
	
}();
