// dependencies:
// * ajax.js:
  /*extern sajax_init_object, sajax_do_call */
// * wikibits.js:
  /*extern hookEvent, jsMsg */

// These should have been initialized in the generated js
if( typeof wgAjaxRequestPage === "undefined" || !wgAjaxRequestPage ) {
	wgAjaxRequestPage = {
		sendingMsg: "Submitting...",
		sentMsg: "Thank you!"
	};
}

wgAjaxRequestPage.supported = true; // supported on current page and by browser
wgAjaxRequestPage.inprogress = false; // ajax request in progress
wgAjaxRequestPage.timeoutID = null; // see wgAjaxRequestPage.ajaxCall

wgAjaxRequestPage.ajaxCall = function() {
	if( !wgAjaxRequestPage.supported ) {
		return true;
	} else if( wgAjaxRequestPage.inprogress ) {
		return false;
	}
	if( !wfSupportsAjax() ) {
		// Lazy initialization so we don't toss up
		// ActiveX warnings on initial page load
		// for IE 6 users with security settings.
		wgAjaxRequestPage.supported = false;
		return true;
	}
	var submit = document.getElementById("requestpage_improve_button");
	if( !submit ) {
		return false;
	}
	wgAjaxRequestPage.inprogress = true;
	submit.disabled = "disabled";
	submit.value = wgAjaxRequestPage.sendingMsg;
	// Send!
	var args = [];
	args.push(wgPageName);
	sajax_do_call( "RequestPage::AjaxRequest", args, wgAjaxRequestPage.processResult );
	// If the request isn't done in 10 seconds, allow user to try again
	wgAjaxRequestPage.timeoutID = window.setTimeout(
		function() { wgAjaxRequestPage.inprogress = false; wgAjaxRequestPage.unlockForm(); },
		10000
	);
	return false;
};

wgAjaxRequestPage.unlockForm = function() {
	var submit = document.getElementById("requestpage_improve_button");
	if( !submit ) {
		return false;
	}
	submit.disabled = "";
};

wgAjaxRequestPage.processResult = function(request) {
	if( !wgAjaxRequestPage.supported ) {
		return;
	}
	var response = request.responseText;
	if( msg = response.substr(7) ) {
		jsMsg( msg, 'requestpage' );
		window.scroll(0,0);
	}
	wgAjaxRequestPage.inprogress = false;
	if( wgAjaxRequestPage.timeoutID ) {
		window.clearTimeout(wgAjaxRequestPage.timeoutID);
	}
	var submit = document.getElementById("requestpage_improve_button");
	if( submit ) {
		submit.value = wgAjaxRequestPage.sentMsg;
	}
};

wgAjaxRequestPage.onLoad = function() {
	var submit = document.getElementById("requestpage_improve_button");
	if( submit ) {
		submit.onclick = wgAjaxRequestPage.ajaxCall;
	}
};

hookEvent("load", wgAjaxRequestPage.onLoad);

