/*
MamboOR - Open-Realty 2 Component for Mambo.
Author: Philip Vickers - www.codenza.co.nz
Copyright (C) 2005 Codenza Limited

This file is part of MamboOR.

MamboOR is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

MamboOR is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with MamboOR; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/
function sendFormToMambo(form, mamboURL) {

	if ( form.method.toLowerCase() == 'get' ) {
		var hex = formAsHex(form);

		// check whether there is already an openrealty query parameter...
		splitStr = mamboURL.split("openrealty=");
		if ( splitStr.length>1 ) {
			hex = splitStr[1] + ascii2Hex('&') + hex;
			if ( splitStr[0].charAt(splitStr[0].length-1)!='&' ) splitStr[0] += '&';
			mamboURL = splitStr[0]+'openrealty='+hex;
		}
		else if (mamboURL.indexOf("index.php?")>=0) {
			mamboURL = mamboURL+'&openrealty='+hex;
		}
		else { // SEF style
			mamboURL = mamboURL+'openrealty,'+hex+'/';
		}

		window.location=mamboURL;
		return false;
	}
	else {
		form.submit();
	}
	return false;
}

function formAsHex(form) {

	var query='';
	for ( var i=0; i<form.elements.length; i++ ) {

		if ( form.elements[i].type!=undefined && form.elements[i].type!="button") {
			var type = form.elements[i].type.toLowerCase();

			// Ensure the value field is populated as OR doesn't always do that...
			if ( type=="select-one" ) {
				var dropdown = form.elements[i];
				if ( dropdown.selectedIndex>0 && dropdown.value.length==0 ) {
					dropdown.options[dropdown.selectedIndex].value = dropdown.options[dropdown.selectedIndex].text;
				}
			}

			if ( form.elements[i].name!='' && form.elements[i].value!='' ) {
				if ( type=="checkbox" || type=="radio") {
					if ( form.elements[i].checked ) {
						if ( query.length>0 ) query+='&';
						query += form.elements[i].name + '=' + escape(form.elements[i].value);
					}
				}
				else {
					if ( query.length>0 ) query+='&';
					query += form.elements[i].name + '=' + escape(form.elements[i].value);
				}
			}
		}
	}
	return ascii2Hex(query);
}

function ascii2Hex( ascii ) {
	var hex='';
	for ( var i=0; i<ascii.length; i++) {
		hex+=ascii.charCodeAt(i).toString(16).toUpperCase();
	}
	return hex;
}

function debug(text) {
	var debug = false;
	if ( debug ) {
		alert(text);
	}
}
