var aCheckedForms = new Array();

function SerializeForm( oF ) {
	var retval = {};
	$("input[type=radio]",oF).each( function() {
		if (this.checked)
			retval[this.name]=this.value;
	} );
	$("select",oF).each( function() {
		retval[this.name]=this.value;
	} );
	$("input[type=text]",oF).each( function() {
		retval[this.name]=this.value;
	} );
	$("input[type=password]",oF).each( function() {
		retval[this.name]=this.value;
	} );
	$("input[type=checkbox]",oF).each( function() {
		retval[this.name]=(this.checked) ? this.value : "";
	} );
	$("textarea",oF).each( function() {
		retval[this.name]=this.value;
	} );

	var ef = $(oF).data( "extra_callback" );
	if (ef) retval = ef( oF , retval );
	return retval;
}

function IsFormChanged( a , b ) {
	var i;
	// check for 
	for (i in a) if (typeof b[i]=="undefined") return true;
	for (i in b) if (typeof a[i]=="undefined") return true;
	for (i in a) if (a[i]!=b[i]) return true;
	return false;
}

function IsFormDirty( oF ) {
	return (IsFormChanged( $(oF).data( "original_data" ) , SerializeForm( oF ) ));
}

function ClearFormDirty( oF ) {
	$(oF).data( "original_data" , SerializeForm( oF ) );
}

function GlobalFormChangeChecker() {
	var i;
	if (!aCheckedForms.length) return;
	for (i in aCheckedForms) {
		var oF = aCheckedForms[i];
		if (IsFormChanged( $(oF).data( "original_data" ) , SerializeForm( oF ) ))
			return aJSLangDefs.Form_is_modified;
	}
}

function FormChangeWarning( oF , extra_callback ) {
	if (typeof oF == "undefined") return;
	if (!oF) return;
	var originalformdata = {};
	if (typeof extra_callback != "undefined")
		$(oF).data( "extra_callback" , extra_callback );
	originalformdata = SerializeForm( oF );
	$(oF).data( "original_data" , originalformdata );

	if (aCheckedForms.length==0) {
		$(window).bind("beforeunload",function() { return GlobalFormChangeChecker(); } );
	}
	aCheckedForms[aCheckedForms.length]=oF;
}

function SetObjectDirty( objid , dirty ) {
	$("#"+objid).data( "dirty" , dirty );
}

function ObjectDirtyChecker( objid ) {
	var o = $("#"+objid);
	var d = o.data( "dirty" );
	if (!d) return;
	return o.data( "extra_dirty_message" );
}

function ObjectChangeWarning( objid , extra_message , dirty_default ) {
	$("#"+objid).data( "extra_dirty_message" , extra_message );
	$("#"+objid).data( "dirty" , dirty_default );
	$(window).bind( "beforeunload",function() { return ObjectDirtyChecker( objid ); } );
}
