/*
CMS Realty - Open-Realty 2 Component for Mambo.
Author: Philip Vickers - www.codenza.co.nz
Copyright (C) 2005 Codenza Limited

This file is part of CMS Realty.

CMS Realty 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.

CMS Realty 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 CMS Realty; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/
function sendFormToCMS(form, cmsURL) {
	if ( form.method.toLowerCase() == 'get' ) {

		// check whether there is already an openrealty query parameter...
		if (cmsURL.indexOf("index.php?")>=0) {
			cmsURL = cmsURL+'&'+formAsQueryString(form, false);
		}
		else { // SEF style
			cmsURL = cmsURL+'&'+formAsQueryString(form, false);
		}

		window.location=cmsURL;
		return false;
	}
	else {
		form.submit();
	}
	return false;
}

function formAsQueryString(form, sef) {
	var paramSeparator = "&";//sef ? "/" : "&";
	var valueSeparator = "=";//sef ? "," : "=";

	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+=paramSeparator;
						query += form.elements[i].name + valueSeparator + escape(form.elements[i].value);
					}
				}
				else if ( type=="select-multiple" ) {
					for ( var multiIndex=0; multiIndex<form.elements[i].options.length; multiIndex++ ) {
						var option = form.elements[i].options[multiIndex];
						if ( option.selected ) {
							if ( query.length>0 ) query+=paramSeparator;
							query += form.elements[i].name + valueSeparator + escape(option.value);
						}
					}
				}
				else {
					if ( query.length>0 ) query+=paramSeparator;
					query += form.elements[i].name + valueSeparator + escape(form.elements[i].value);
				}
			}
		}
	}
	if ( sef ) return "openrealty,"+ascii2Hex(query);
	else return query;
}

function ascii2Hex( ascii ) {
	var hex='';
	for ( var i=0; i<ascii.length; i++) {
		hex+=ascii.charCodeAt(i).toString(16).toUpperCase();
	}
	return hex;
}
