/**
* author: Vladimir Kornea
* copyright: Delivery Concepts LLC
* name: utilities.js
* version: 1.0
* abstract: Various general-purpose javascript utility functions
*/

/*
function registerEventHandler(element, eventName, handler);
Registers the function 'handler' to run when the event 'eventName' occurs on the element 'element'.
Note:
1) handler and element are objects while eventName is a string:
   registerEventHandler(window, 'load', initializeReportTables);
   registerEventHandler(window, 'scroll', scrollTable);
2) objects created in the HTML <body>, such as form inputs, do not exist when registerEventHandler()
   is called (from the <head>). To register events on such objects, do something like this:

registerEventHandler(window, 'load', registerEventHandlers);
function registerEventHandlers() {
	registerEventHandler(document.my_form_name_1.my_input_name_1, 'change', myFormSubmit);
	registerEventHandler(document.my_form_name_1.my_input_name_2, 'change', myFormSubmit);
	// etc
}
myFormSubmit() {
	// your event handling code
}
*/
function registerEventHandler(element, eventName, handler) {
	if (typeof element === 'object') {
		if (element.attachEvent) { // Internet Explorer
			element.attachEvent("on" + eventName, handler);
		}
		else if (element.addEventListener) { // Mozilla & Opera
			element.addEventListener(eventName, handler, false);
		}
	}
}

// vk - a PHP-like round function
function round(val, precision) {
	var multiple = 1;
	for (var i = precision; i > 0; i--) {
		multiple *= 10;
	}
	return Math.round(val * multiple) / multiple;
}

/**
 * buttonSubmit(buttonObject) by Vlad - Usage example:
 * <input type="button" value="Submit" onclick="buttonSubmit(this);">
 * It disables the button so it can't be double-clicked, changes its text to
 * 'Processing...', and submits the form to which the button belongs.
 * Note that it doesn't work if buttonObject has the id 'submit'
 */
function buttonSubmit(buttonObject) {
	buttonObject.disabled = true;
	buttonObject.value = "Processing...";
	buttonObject.form.submit();
}

/**
 * VK - usage example:
 * <a href="javascript:confirmClick('http://www.example.com', 'Are you sure?')">
 */
function confirmClick(url, message) {
	var answer = confirm(message);
	if(answer) {
		window.location = url;
	}
}

/* This one is only for the search page */
function confirmMerchantClick(url,message,href_text){
	sModal.create();
	var buttons = '<div class="button"><a onclick="sModal_close(); return false;" href="#" rel="friend">Go Back</a></div>';
	if (href_text !== null){
		href_text = href_text.replace(/\[DBQ\]/gi,'"');
		href_text = href_text.replace(/\[SQ\]/gi,"'");
	}
	href_text = href_text !== null ? href_text : 'href="' + url + '"';
	
	buttons += '<div style="float:left;">&nbsp; &nbsp;</div><div class="button"><a ' + href_text + '>Continue</a></div>';
	message += '<br /><br /><div class="clear"></div>' + buttons;
	sModal.populate(message);
	return false;
}

/*
ajax_request() accepts 2 or more arguments:
1st argument is the name of your custom-written javascript function ('handler')
	that will process the server's response once it is received.
2nd argument is the request you're sending to the server, formatted as a
	standard URL. Though it looks just like a GET request, the request will be
	made as POST since our server doesn't accept unencrypted GET requests.
3rd through Nth arguments are optional and will be passed through to your
	handler for your convenience.

Arguments will be passed to your handler in this order:
1st - The server's response to your request (always a string).
2nd - Your original request to the server (same as the second argument you
	passed to ajax_request()).
3rd, 4th, etc - Any other arguments you passed to ajax_request().

Example:
	ajax_request('example_request_handler', 'example.php?example=Y&test=Y', 'custom_1', custom_2);
	function example_request_handler(response, request, custom1, custom2) {
		// your code that does stuff based on response
	}
*/
function ajax_request(response_handler, request_url) {	//FIXME replace eval with jsonParse?
	//* set page and request variables based on request_url passed by user
	var page;
	var request;
	if (request_url.match(/\?/)) { // both path and variables provided; split in two
		var request_pieces = request_url.split(/\?/);
		page = request_pieces[0];
		request = request_pieces[1];
	} else if (request_url.match('=')) { // variables provided but path not; use path of current page
		page = location.href; // might need cleanup due to appended variables
		if (page.match(/\?/)) { // cleanup
			page = page.split(/\?/)[0];
		}
		request = request_url;
	} else if (request_url) { // path provided but no variables (that's fine, as unlikely as it is to be used)
		page = request_url;
		request = '';
	} else { // neither path nor variables provided... now we're getting silly; show an error
		alert("Error: neither page nor parameters provided for AJAX call.");
		return;
	}

	var passthrough_arguments = arguments; // the current arguments variable will be lost as soon as the scope changes
	var eval_string = "eval(response_handler)(data, request_url";
	for (var i = 2; i < passthrough_arguments.length; i++) {
		eval_string = eval_string + ", passthrough_arguments[" + i + "]";
	}
	eval_string = eval_string + ");";
	//eval(eval_string);

	$.ajax({
		type: 'POST',
		url: page,
		data: request,
		async: true,
		success: function(data, textStatus, jqXHR) {
			eval(eval_string);
		}
	});
	return;
}
