/**
 * ws_dataform jscripts
 * $Revision: 2244 $ | $Date: 2010-06-16 22:04:44 +0200 (wo, 16 jun 2010) $
 * $URL $
 */
/**
changelog
02-01-2006
	[add]	Focus handling
16-03-2006
	[add]	Set focus to first field
	[fix]	no focusstyle for readonly, hidden or disabled fields
13-10-2006
	[chn]	button submit script now ws_dataform_submit(), Param order changed, formname now default 0,
		useful in case of 1 form.
23-10-2006
	[add]	Capslock detection
26-10-2006
	[add] 	add_event_handler(), change_source()
02-11-2006
	[fix]	window.external.AutoCompleteSaveForm() requires an object
08-11-2006
	[fix]	SetFocus() anmd SetBlur() wrong element, Due to eventhandlers, new function _evt_element();
31-12-2006
	[add]	show(), hide(), showHide()
16-04-2006
	[fix]	added add_load_event() and shifted set_focus_handler() to the window-onload handler
11-06-2006
	[chn]	Add jQuery	attachValueToggle(), valueToggle(), formSubmit().
13-07-2007
	[fix]	try/catch for focus handler
	[fix]	return false for formSubmit() to prevent default action.
10-10-2007
	[fix]	chaned to preventDefault() in formSubmit(). Renamed formSubmit() to attachFormSubmit().
22-10-2007
	[chn]	added testvalue for valueToggle
02-02-2009
	[chn]	removed @ (attribute) form jquery statement. Was deprecated since version 2.0
29-06-2009
	[add]	attachCopyPostToGet()
	[chn]	refactored addQuerystringArgument()
26-10-2009
	[chn]	reversed controller / target in attachValueToggle.
26-01-2009	
	[chn]	changed attachCopyPostToGet() to blur event because due autofill onchange not allways fires
21-04-2010
	[chn]	Added callback option to attachFormSubmit();
04-05-2010
	[fix]	get form in id basis and not name basis (IE-overlap).
*/


/**
 * Change source for an related image
 */
function change_source(evt)
{
	var el 			= _evt_element(evt);
	var target_el 	= document.images[el.getAttribute('related')];
	var source		= el.value;
	var base		= target_el.getAttribute('base');
	target_el.src 	= base + source;
};

/**
 * toggle visiblity
 */
function showHide(element_id) {
       var element = document.getElementById(element_id);

       if (element.style.visibility == 'hidden' || element.style.visibility == '') {
              element.style.visibility= 'visible';
       } else {
              element.style.visibility = 'hidden';
       }
	return true;
};

/**
 * show element
 */
function show(element_id) {
       var element = document.getElementById(element_id);
       element.style.visibility= 'visible';
       return true;
};

/**
 * hide element
 */
function hide(element_id) {
	var element = document.getElementById(element_id);
	element.style.visibility = 'hidden';

       	return true;
};
/**
 * Change an Url querystring 
 * Key/Value pair is added or replaced. Empty values are deleted
 * @param url
 * @param name
 * @param value
 * @return modified Url
 */
function addQuerystringArgument(url, name, value){
	var rexp = new RegExp(name+'=[^&]*','gi');
	//Replace argument value
	if(url.match(rexp)){
		if(value==''){
			return url.replace(rexp, '');
		} else {
			return url.replace(rexp, name+'='+value);
		}	
	} else {
		if(value== ''){
			return url;
		} else {	
			var qa = url.indexOf('?')==-1 ? '?' : '&';
			return  url+qa+name+'='+value;
		}	
	}
}

/**
 *===================jquery.dataform.js =============================
 * Jquery plugins
 *===================================================================
 */

/**
 * Show or hide an element depending on a value from another jQ element
 * @param jQ controler element
 * @param Map	Options Key/value pairs:
 * 		 effect (string) = show or hide animation effect : slide|fade,
 *		 onvalue (bool)  = show when met (true) else when not met (false)
 *	     test (string)   = value to test.
 */
jQuery.fn.valueToggle = function(jQ, options)
{
	var settings = jQuery.extend({effect: 'show', onvalue: true, test: null}, options);

	var el 	= jQ[0]; 
	var t 	= el.type ;
	var tag = el.tagName.toLowerCase();
	var s	= false; /*status*/
	var h	= this[0].style.display == 'none' ;

	if(t=='checkbox' || t =='radio'){
		s =  el.checked;
	} else if (t == 'text' || t == 'password' || tag == 'textarea' || tag=='select') {
		if(settings.test){
			s =  el.value == settings.test;
		} else {
			s =  el.value != '';
		}
	}
	/* reverse behavior */
	if(settings.onvalue==false) {
		s = !s;
	}

	if(s && h ) {
		if(settings.effect=='slide'){
			this.slideDown();
		} else if(settings.effect =='fade' ) {
			this.fadeIn();
		} else {
			this.show();
		}
	} else if (!s && !h){
		if(settings.effect=='slide'){
			this.slideUp();
		} else if(settings.effect =='fade' ) {
			this.fadeOut();
		} else {
			this.hide();
		}
	}
	return this;
};

/**
 * Attach valueSlideToggle behavior to an element,
 * slide show or hide sliding another jQ element depending on this value
 * @param target target element
 * @param Map	Options Key/value pairs: see valueToggle()
 */
jQuery.fn.attachValueToggle = function(target, options)
{
	//var target = this;
	target.valueToggle(this, {effect:"show", onvalue:options.onvalue} );
	$(this).bind('click', function(event){
		target.valueToggle($(this), {effect:options.effect, onvalue:options.onvalue, test:options.test} ); 
	});
	return $(this);
};

/**
 * Adding onfocus, onblur and capsdetect handlers to input fields
 * Sets focus to first input field
 * To the focused input the class="focus" is added
 */
jQuery.fn.attachFocusHandlers = function()
{
	var first = true;
	$("input.disableAutoComplete").attr("autocomplete", "off");
	$("input:visible", this).each( function() {
	 	if(this.readOnly || this.disabled || this.type == "image" || this.type == "reset" || this.type == "submit")
		return true;

		$(this).focus( 	function() 	{ $(this).addClass("focus"); });
		$(this).blur(	function()	{ $(this).removeClass("focus"); });
		if(this.type == 'password')	{ $(this).capsDetect(); };

		if(first) {
			try {this.focus(); } catch (ex) {};
			first = false;
   		};
	});
};


/**
 * formSubmit
 * add submit handler to an element click event, to submit forms with a specific action.
 * updates Post field 'ws_action' to transfer the action.
 * @param object options: action:string, formname:string
 */
jQuery.fn.attachFormSubmit = function(options)
{
	var settings = jQuery.extend({action:"_none", formname: false, event:'click', callback:''}, options);
	
	/**Wich form?*/
	if(settings.formname){
		myform = $("form#"+settings.formname);
	} else {
		var myform = this.parents("form");
	}

	$(this).bind(settings.event, function (event) {
		$("input[name=ws_action]", myform).val(settings.action);
		event.preventDefault();
		var callbackFunction = settings.callback; 
		if(!callbackFunction || callbackFunction(myform) !== false) {	
			
			//To make Autocompletion work in IE with a script submit
			if(window.external)
			window.external.AutoCompleteSaveForm(myform.attr('name'));
			
			myform.submit();
		}
		
	});
};

/**
 * Ad post as get parameter to action (location) of the form
 * adds this handler to an input field. Fielname=value is send
 * @param object options: event:string
 */
jQuery.fn.attachCopyPostToGet = function(options)
{
	var settings = jQuery.extend({event:'blur'}, options);
	var myform = this.parents("form");
	
	$(this).bind(settings.event, function (event) {
		var action = myform.attr("action");
		var name   = $(this).attr("name");
		if($(this).is('select')){
			var value  = $("option:selected", this).val();
		} else {
			var value  = $(this).val();
		}
		action = addQuerystringArgument(action, name, value); 
		//Set form action (url)
		myform.attr("action",action);
	});
};

/**
 * Send Get parameter to add it to location
 * add this handler to an input field. Fielname=value is send
 * @param object options: event:string
 */
jQuery.fn.attachSendGet = function(options)
{
	var settings = jQuery.extend({event:'change'}, options);

	$(this).bind(settings.event, function (event) {
		var loc    = window.location.href;
		var name   = $(this).attr("name");
		var value  = $(this).val();
		
		window.location = addQuerystringArgument(loc, name, value);
	});
};

/**
 * Detect capslock and appends a span element with id=capslock to an element
 */
jQuery.fn.capsDetect = function ()
{
	$(this).keypress( function(evt) {
		//what (case sensitive in good browsers) key was pressed
		var theKey = evt.which ? evt.which : ( evt.keyCode ? evt.keyCode : ( evt.charCode ? evt.charCode : 0 ) );
		//was the shift key was pressed
		var theShift = evt.shiftKey || ( evt.modifiers && ( evt.modifiers & 4 ) ); //bitWise AND
		//if upper case, check if shift is not pressed. if lower case, check if shift is pressed
		isCaps = ( theKey > 64 && theKey < 91 && !theShift ) || ( theKey > 96 && theKey < 123 && theShift ) ;
		$("#capslock").remove();
		if( isCaps)	$(this).after("<span id='capslock'>! Caps Lock</span>");
	});
};