/** 
 * RCSF Admin form object
 */
oRcsf.RegisterObject('Form');
var RCSF_Base_Form = 
{
	msExtends : 'RCSF_Base_Base'
	
	/**
	 * Gets values of each form element and stores these in an object
	 * 
	 * @param	Object	oForm	ref to form object
	 * @return	Object	o_data	all form values
	 * 
	 * TODO: combine with admin method to support all types of form elements
	 */
	,GetFormData : function(oForm) 
	{
		// Init
		var o_data = new Object();
		o_data.s_form_id = oForm.id;
		
		// Store each form element value
		Form.getElements(oForm).each(function(o_cur_el)
		{
			if (o_cur_el.id)
			{
				var a_id = o_cur_el.id.replace('a_' + oForm.id + '-', '').split('-');

				// Support radio buttons 
				if (o_cur_el.type.toLocaleLowerCase() == 'radio')
				{
					if (!o_cur_el.checked) return;
					a_id.pop();
				}
				RCSF_Base_Util.SetObjectElement(o_data, a_id, $F(o_cur_el.id));
			}
		});
		return o_data;
	}
	
	/**
	 * Shows error messages
	 * 
	 * @param	Object	oData	return object with errors
	 */
	,ShowFieldErrors : 	function(oData)
	{
		this.HideFieldErrors(oData);
		var o_error_msg = $$('#' + oData.s_form_id + ' .msg').first();
		if(o_error_msg) o_error_msg.update(oData.s_message);		
		for (var s in oData.a_errors)
		{	
			var o_error = $(s + '-error_msg');
			if (!o_error) var o_error = $('a_' + oData.s_form_id + '-' + s + '-error_msg');
			
			if (o_error)
			{
				o_error.show();
				o_error.update(oData.a_errors[s]['s_message']);
			}
		}
	}
		
	/**
	 * Hides all error messages
	 * 
	 * @param	Object	oData	[id] 
	 * 							[s_form_id]
	 * 					
	 */
	,HideFieldErrors : function(oData)
	{
		var s_id = (!Object.isUndefined(oData.id)) ? oData.id : oData.s_form_id;
		var o_error_msg = $$('#' + s_id + ' .msg').first();
		if (o_error_msg) o_error_msg.update('');
		$$('#' + s_id + ' .error_msg').each(function(oEl) { oEl.hide(); });
	}
		
	/**
	 * Shows
	 * 
	 * @param	Object	oForm	ref to form
	 * @param	Object	oData	return object with errors
	 */
	,ShowThanxMsg : 	function(oData)
	{
		// Show message
		var o_error_msg = $$('#' + oData.s_form_id + ' .msg').first();
		if(o_error_msg) o_error_msg.update(oData.s_message);
		
		// Clear form elements
		Form.getElements($(oData.s_form_id)).each(function(o_cur_el)
		{
			o_cur_el.clear();
		});
		
		this.RefreshCaptcha();
	}
	
	/**
	 * Hides form fieldsets
	 * 
	 * @param	Object	oData
	 */
	,HideFieldSets : function(oData)
	{
		$$('#' + oData.s_form_id + ' fieldset').each(function(oEl) { oEl.hide(); });
	}
		
	/**
	 * Refreshes a captcha image
	 * 
	 * TODO: maybe move to captcha module?
	 */
	,RefreshCaptcha : function()
	{				
		// Refresh captcha
		if ($('captcha'))
		{
			new Ajax.Request(
				 this.moModule.moCore.maPaths.a_url.s_root + 'txt/data/captcha/default/get_html' 
				 	+ '/s_key=' + $F('a_captcha-s_key')
				,{
					 method : 'get'
					,onSuccess: function(transport)
					{
						$('captcha').update(transport.responseText);
					}
				}
			);
		}
	}
	
	/**
	 *
	 */
	,OnCaptchaLoaded : function(oData)
	{
		$('captcha').innerHTML = oData.a_result.a_captcha.s_html;
	}
	
	/**
	 * Creates Datepickers
	 */
	,CreateDatePickers : function ()
	{
		// Check if there are any date time pickers to make
		var a_datetimepickers = new Array();
		var o_datetimepickers = document.getElementsByClassName('datetimepicker');
	
		for (var i=0; i < o_datetimepickers.length; i++) 
		{
			var i_datetimepicker_id = o_datetimepickers[i].id;
			Calendar.setup(
		    	{
		      	 inputField  : i_datetimepicker_id   // ID of the input field
		 	    ,ifFormat    : "%Y-%m-%d %H:%M:%S"    // the date format
		    	,button      : "trigger_"+i_datetimepicker_id       // ID of the button
		    	,showsTime 	: true
		    	}
		 	 );
		}
		
		// Check if there are any date pickers to make
		var a_datepickers = new Array();
		var o_datepickers = document.getElementsByClassName('datepicker');
	
		for (var i=0; i < o_datepickers.length; i++) 
		{
			var i_datepicker_id = o_datepickers[i].id;
			Calendar.setup(
		    	{
		      	inputField  : i_datepicker_id,   // ID of the input field
		 	    ifFormat    : "%Y-%m-%d",    // the date format
		    	button      : "trigger_"+i_datepicker_id        // ID of the button
		    	}
		 	 );
		}
	}
	
	/**
	 * Sets the target of the form
	 * 
	 * @param	Object	oForm	form object
	 * @param	Object	sTarget	target
	 */
	,SetTarget : function(oForm, sTarget) 
	{
		oForm.setAttribute('target', sTarget);
	}
	
	/* UPLOAD methods *********************************************************/
	
	/**
	 * Creates div with iframe for posting the upload to
	 * 
	 * @param	Object	oCallback	Callback
	 * @return	string	s_iframe 	id of iframe
	 */
	,CreateUploadIframe : function(oCallback) 
	{
		// Create div with iframe
		var s_iframe = 'iframe' + Math.floor(Math.random() * 99999);
		
		$$('body').first().insert(new Element('div').update('<iframe style="display:none" src="about:blank" id="' + s_iframe + '" name="'+ s_iframe +'" onload="oRcsf.moForm.OnUploaded(\'' + s_iframe + '\')"></iframe>'));
		var o_iframe = $(s_iframe);
		
		o_iframe.onComplete = function (result)
		{
			oCallback.o_scope[oCallback.s_complete_method](result);
		}
		return s_iframe;
	}
	/**
	 * Submits the form and thus starts uploading
	 * 
	 * this method will run optional onstart callback
	 * 
	 * @param	Object	oForm	form object
	 * @param	Object	oCallback	callback
	 * @return	mixed	callback start method or true
	 */
	,SubmitUpload : function(oForm, oCallback) 
	{
		this.SetTarget(oForm, this.CreateUploadIframe(oCallback));
		return (oCallback && typeof(oCallback.onStart) == 'function') ? oCallback.onStart() : true;
	}
	/**
	 * OnLoaded handler for the iframe
	 * 
	 * @param	String	sIframeId	id of the iframe
	 * @return	void
	 */
	,OnUploaded : function(sIframeId) 
	{
		var o_iframe = $(sIframeId);
		if (o_iframe.contentDocument) var o_document = o_iframe.contentDocument;
		else if (o_iframe.contentWindow) var o_document = o_iframe.contentWindow.document;
		else var o_document = window.frames[id].document;
				
		if (o_document.location.href == "about:blank") return;
		
		// if something goes wrong, it is probably because of this string strip tag
		o_iframe.onComplete(o_document.body.innerHTML.stripTags().evalJSON());
	}

	/**
	 * Sets focus to next form element if max allowed nr of chars has been typed
	 *
	 * Fired on a key event in an input
	 *
	 * @param   string	s_cid  	id of element being typed in
	 * @param   string	s_nid  	id of element to switch to
	 * @param   int     i_mc      max allowed chars in input field
	 *
	 */
	,TabInput : function(s_cid, s_nid, i_mc)
	{
		if($(s_cid) && $(s_nid) && $F(s_cid).length == i_mc) $(s_nid).focus();
	}
	
	/**
	 * Function to get all inputs in a document and provide them with mouseovers
	 */
   	,InitSubmitHovers : function()
   	{
   		$$('input[type="submit"]').each(function(o_el)
   		{
			if (o_el.className != 'idle')
			{
				o_el.onmouseover = function() { this.className = "highlight"; }
				o_el.onmouseout	= function() { this.className = "idle"; }
			}
		});
	}
	
	/**
	*
	*/
	,ReplaceCheckAndRadios : function() 
	{
		$$('input[type="checkbox"].replace','input[type="radio"].replace').each(function(oCheck)
		{
			if(Object.isUndefined(oCheck.id) || !Object.isString(oCheck.getAttribute('rel')))
				return alert("Checkbox replacement requires an id or rel on the checkbox");

			var new_checkbox = new Element('span',{id : 'checkbox-replace-' + oCheck.id});
			new_checkbox.style.display = 'block';
			new_checkbox.addClassName(oCheck.className);
			new_checkbox.style.height = Object.isString(oCheck.style.height) ? oCheck.style.height : oCheck.getHeight() + 'px';
			new_checkbox.style.width = Object.isString(oCheck.style.width) ? oCheck.style.width : oCheck.getWidth() + 'px';
			new_checkbox.style.background = 'url('+oCheck.getAttribute('rel')+')';
			oCheck.insert({'before' : new_checkbox})
			new_checkbox.observe('mousedown', oRcsf.moForm.PushCheckbox.bind(this,oCheck.id) );
			oCheck.hide();
			
			if($(oCheck.id).checked == true)
			{
				new_checkbox.style.backgroundPosition = '0px -'+new_checkbox.getHeight()+'px';
			}
		}.bind(this));
	}
	
	,PushCheckbox : function(sCheckId)
	{
		var span = $('checkbox-replace-' + sCheckId)

		// Check by name if this checkbox belongs to a group
		var a_checkboxes = $$("input[name='"+$(sCheckId).name+"'].replace");
		if(a_checkboxes.size() > 1 && $(sCheckId).type == 'radio')
		{
			a_checkboxes.each(function(oCheck){
				if(oCheck.id != $(sCheckId).id)				
				{
					oCheck.checked = false;
					$('checkbox-replace-' + oCheck.id).style.backgroundPosition = '0px 0px';
				}
			})
		}	
		if($(sCheckId).checked == true)
		{
			$(sCheckId).checked = false;
			span.style.backgroundPosition = '0px 0px';
		}
		else		
		{
			$(sCheckId).checked = true;
			span.style.backgroundPosition = '0px -'+span.getHeight()+'px';
		}
	}
	
	,ReplaceFileFields : function()
	{
		var fakeFileUpload = new Element('div',{'class' : 'fakefile'});
		fakeFileUpload.appendChild(document.createElement('input'));
		var o_image = new Element('img',{'align' : 'top'});
		fakeFileUpload.appendChild(o_image);
		$$('input[type=file]').each(function(o_input)
		{
			if (o_input.parentNode.className != 'fileinputs')
				o_input.wrap(new Element('div',{'class' : 'fileinputs'}));	
			o_input.className = 'file hidden';
			var o_clone = fakeFileUpload.cloneNode(true);
			o_input.parentNode.appendChild(o_clone);
			
			if(!Object.isUndefined(o_input.getAttribute('rel')))
				o_clone.getElementsByTagName('img')[0].src = o_input.getAttribute('rel');
			
			o_input.relatedElement = o_clone.getElementsByTagName('input')[0];
			o_input.onchange = o_input.onmouseout = function() {
				this.relatedElement.value = this.value;
			}
		}.bind(this));
	}
}
