/*
 *
 * jqForm
 * by Piotr Łojewski piotr.l@aginus.pl
 * na podstawie: jqTransform
 * by mathieu vilaplana mvilaplana@dfc-e.com
 * Designer ghyslain armand garmand@dfc-e.com
 *
 *
 * Version 0.1 26.01.2010
 ******************************************** */
 
(function($){
		  
	/***************************
	  Labels
	***************************/
	var jqFormGetLabel = function(objfield){
		var selfForm = $(objfield.get(0).form);
		var oLabel = objfield.next();
		if(!oLabel.is('label')) {
			oLabel = objfield.prev();
/*			if(oLabel.is('label')){
				var inputname = objfield.attr('id');
				if(inputname){
					oLabel = selfForm.find('label[for="'+inputname+'"]');
				} 
			}*/
		}
		if(oLabel.is('label')){return oLabel.css('cursor','pointer');}
		return false;
	};
	
	/* Hide all open selects */
	var jqFormHideSelect = function(oTarget){
		var ulVisible = $('.jqFormSelect ul:visible');
		ulVisible.each(function(){
			var oSelect = $(this).parents(".jqFormSelect:first").find("select").get(0);
			//do not hide if click on the label object associated to the select
			if( !(oTarget && oSelect.oLabel && oSelect.oLabel.get(0) == oTarget.get(0)) ){$(this).hide();}
		});
	};
	/* Check for an external click */
	var jqFormCheckExternalClick = function(event) {
		if ($(event.target).parents('.jqFormSelect').length === 0) { jqFormHideSelect($(event.target)); }
	};

	/* Apply document listener */
	var jqFormAddDocumentListener = function (){
		$(document).mousedown(jqFormCheckExternalClick);
	};	
			
	/* Add a new handler for the reset action */
	var jqFormReset = function(f){
		var sel;
		$('.jqFormSelect select', f).each(function(){sel = (this.selectedIndex<0) ? 0 : this.selectedIndex; $('ul', $(this).parent()).each(function(){$('a:eq('+ sel +')', this).click();});});
		$('a.jqFormCheckbox, a.jqFormRadio', f).removeClass('jqFormChecked');
		$('input:checkbox, input:radio', f).each(function(){if(this.checked){$('a', $(this).parent()).addClass('jqFormChecked');}});
	};
	
		  
	/***************************
	  Inputy textowe
	 ***************************/
	$.fn.jqFormInputText = function(){
		return this.each(function(){
			var $input = $(this);
			
			var oLabel = jqFormGetLabel($(this));
			oLabel && oLabel.bind('click',function(){$input.focus();});
			
			$input.wrap('<div class="jqFormInputText"><div class="jqFormInputTextCenter"></div></div>');
			$input.parent().before('<div class="jqFormInputTextLeft"></div>');
			$input.parent().after('<div class="jqFormInputTextRight"></div>');

			var wrapper = $input.parent().parent();

			$input
				.focus(function(){wrapper.addClass("jqFormInputText-focus");})
				.blur(function(){wrapper.removeClass("jqFormInputText-focus");})
				.hover(function(){wrapper.addClass("jqFormInputText-hover");},function(){wrapper.removeClass("jqFormInputText-hover");})
			;
			
			var inputSize=$input.width();
			wrapper.css('width',inputSize + 12 + 'px');
	
		});
	};
	
	
	/***************************
	  Textarea
	 ***************************/
	$.fn.jqFormTextarea = function(){
		return this.each(function(){
			var textarea = $(this);
			
			oLabel = jqFormGetLabel(textarea);
			oLabel && oLabel.click(function(){textarea.focus();});
			
			textarea.wrap('<div class="jqFormTextarea"><div class="jqFormTextareaCenter"></div></div>');
			textarea.parent().before('<div class="jqFormTextareaLeft"></div>');
			textarea.parent().after('<div class="jqFormTextareaRight"></div>');

			var wrapper = textarea.parent().parent();

			textarea
				.focus(function(){wrapper.addClass("jqFormTextarea-focus");})
				.blur(function(){wrapper.removeClass("jqFormTextarea-focus");})
				.hover(function(){wrapper.addClass("jqFormTextarea-hover");},function(){wrapper.removeClass("jqFormTextarea-hover");})
			;
			
			var textareaSize=textarea.width();
			wrapper.css('width',textareaSize + 12 + 'px');
	
		});
	};
	
	
	/***************************
	  Buttony
	 ***************************/
	$.fn.jqFormInputButton = function(){
		return this.each(function(){
			var button = $(this);
			
			button.wrap('<div class="jqFormInputButton"><div class="jqFormInputButtonCenter"></div></div>');
			button.parent().before('<div class="jqFormInputButtonLeft"></div>');
			button.parent().after('<div class="jqFormInputButtonRight"></div>');

			var wrapper = button.parent().parent();

			button
				.hover(function(){wrapper.addClass("jqFormInputButton-hover");},function(){wrapper.removeClass('jqFormInputButton-hover')})
				.mousedown(function(){wrapper.addClass("jqFormInputButton-focus");})
				.mouseup(function(){wrapper.removeClass("jqFormInputButton-focus");})
			;
			
			var buttonSize=button.width();
			wrapper.css('width',buttonSize + 12 + 'px');
	
		});
	};
	
	
	/***************************
	  Select 
	 ***************************/
	 
	$.fn.jqFormSelect = function(){
		return this.each(function(index){
			var $select = $(this);

			if($select.hasClass('jqFormHidden')) {return;}
			if($select.attr('multiple')) {return;}
			
			var oLabel = jqFormGetLabel($select);

			/* First thing we do is Wrap it */
			var $wrapper = $select
				.addClass('jqFormHidden')
				.wrap('<div class="jqFormSelect"></div>')
				.parent()
				.css({zIndex: 10-index})
			;
			
			/* Now add the html for the select */
			$wrapper.prepend('<div><span></span><a href="#" class="jqFormSelectOpen"></a></div><ul></ul>');
			var $ul = $('ul', $wrapper).css('width',$select.width()).hide();
			/* Now we add the options */
			$('option', this).each(function(i){
				var oLi = $('<li><a href="#" index="'+ i +'">'+ $(this).html() +'</a></li>');
				$ul.append(oLi);
			});
			
			/* Add click handler to the a */
			$ul.find('a').click(function(){
					$('a.selected', $wrapper).removeClass('selected');
					$(this).addClass('selected');	
					/* Fire the onchange event */
					if ($select[0].selectedIndex != $(this).attr('index') && $select[0].onchange) { $select[0].selectedIndex = $(this).attr('index'); $select[0].onchange(); }
					$select[0].selectedIndex = $(this).attr('index');
					$('span:eq(0)', $wrapper).html($(this).html());
					$ul.hide();
					return false;
			});
			/* Set the default */
			$('a:eq('+ this.selectedIndex +')', $ul).click();
			$('span:first', $wrapper).click(function(){$("a.jqFormSelectOpen",$wrapper).trigger('click');});
			oLabel && oLabel.click(function(){$("a.jqFormSelectOpen",$wrapper).trigger('click');});
			this.oLabel = oLabel;
			
			/* Apply the click handler to the Open */
			var oLinkOpen = $('a.jqFormSelectOpen', $wrapper)
				.click(function(){
					//Check if box is already open to still allow toggle, but close all other selects
					if( $ul.css('display') == 'none' ) {jqFormHideSelect();} 
					if($select.attr('disabled')){return false;}

					$ul.slideToggle('fast', function(){					
						var offSet = ($('a.selected', $ul).offset().top - $ul.offset().top);
						$ul.animate({scrollTop: offSet});
					});
					return false;
				})
			;

			// Set the new width
			var iSelectWidth = $select.outerWidth();
			var oSpan = $('span:first',$wrapper);
			var newWidth = (iSelectWidth > oSpan.innerWidth())?iSelectWidth+oLinkOpen.outerWidth():$wrapper.width();
			$wrapper.css('width',newWidth);
			$ul.css('width',newWidth-2);
			oSpan.css({width:iSelectWidth});
		
			// Calculate the height if necessary, less elements that the default height
			//show the ul to calculate the block, if ul is not displayed li height value is 0
			$ul.css({display:'block',visibility:'hidden'});
			var iSelectHeight = ($('li',$ul).length)*($('li:first',$ul).height());//+1 else bug ff
			(iSelectHeight < $ul.height()) && $ul.css({height:iSelectHeight,'overflow':'hidden'});//hidden else bug with ff
			$ul.css({display:'none',visibility:'visible'});
			
		});
	};
	

	/***************************
	  Checkboxy
	 ***************************/	
	$.fn.jqFormCheckBox = function(){
		return this.each(function(){
			if($(this).hasClass('jqFormHidden')) {return;}

			var $input = $(this);
			var inputSelf = this;
			
			var oLabel=jqFormGetLabel($input);
			oLabel && oLabel.click(function(){aLink.trigger('click');});
			
			var aLink = $('<a href="#" class="jqFormCheckbox"></a>');
			//wrap and add the link
			$input.addClass('jqFormHidden').wrap('<span class="jqFormCheckboxWrapper"></span>').parent().prepend(aLink);
			//on change, change the class of the link
			$input.change(function(){
				this.checked && aLink.addClass('jqFormChecked') || aLink.removeClass('jqFormChecked');
				return true;
			});
			// Click Handler, trigger the click and change event on the input
			aLink.click(function(){
				//do nothing if the original input is disabled
				if($input.attr('disabled')){return false;}
				//trigger the envents on the input object
				$input.trigger('click').trigger("change");	
				return false;
			});

			// set the default state
			this.checked && aLink.addClass('jqFormChecked');
		});
	};
	
	
	/***************************
	  Radio 
	 ***************************/	
	$.fn.jqFormRadio = function(){
		return this.each(function(){
			if($(this).hasClass('jqFormHidden')) {return;}

			var $input = $(this);
			var inputSelf = this;

			oLabel = jqFormGetLabel($input);
			oLabel && oLabel.click(function(){aLink.trigger('click');});

			var aLink = $('<a href="#" class="jqFormRadio" rel="'+ this.name +'"></a>');
			$input.addClass('jqFormHidden').wrap('<span class="jqFormRadioWrapper"></span>').parent().prepend(aLink);
			
			$input.change(function(){
				inputSelf.checked && aLink.addClass('jqFormChecked') || aLink.removeClass('jqFormChecked');
				return true;
			});
			// Click Handler
			aLink.click(function(){
				if($input.attr('disabled')){return false;}
				$input.trigger('click').trigger('change');
	
				// uncheck all others of same name input radio elements
				$('input[name="'+$input.attr('name')+'"]',inputSelf.form).not($input).each(function(){
					$(this).attr('type')=='radio' && $(this).trigger('change');
				});
	
				return false;					
			});
			// set the default state
			inputSelf.checked && aLink.addClass('jqFormChecked');
		});
	};
	
	$.fn.jqPLForm = function(options){

		 return this.each(function(){
			var selfForm = $(this);

			$('input:text, input:password', this).jqFormInputText();
			$('input:submit, input:reset, input[type="button"]', this).jqFormInputButton();
			$('textarea', this).jqFormTextarea();
			$('input:checkbox', this).jqFormCheckBox();
			$('input:radio', this).jqFormRadio();

			if ( $('select', this).jqFormSelect().length > 0 ){jqFormAddDocumentListener();}
			selfForm.bind('reset',function(){var action = function(){jqFormReset(this);}; window.setTimeout(action, 10);});
			
		});
				
	};

})(jQuery);