/*
	Registration ajax validation
*/


	new function($) {
		$.fn.setCursorPosition = function( pos ) {
			if ( $( this ).get( 0 ).setSelectionRange ) {
				$( this ).get( 0 ).setSelectionRange( pos, pos );
			} else if ( $( this ).get( 0 ).createTextRange ) {
				var range = $( this ).get( 0 ).createTextRange();
				range.collapse( true );
				range.moveEnd( 'character', pos );
				range.moveStart( 'character', pos );
				range.select();
			}
		}
	}( jQuery );


	//does simple client side validation
	function clientValidation( fieldname, rules ) {
		var minval = 0; 		//default display of 
		var maxval = 1000;
		var errors = [];

		$( '#counter_' + fieldname ).text( '' );

		for ( var r = 0; r < rules.length; r++ ) {
			switch( rules[ r ].rule ) {
				case "client_minlength":
					minval = rules[ r ].value;
					$( '#textMinMax_' + fieldname ).toggle( $( '#' + rules[ r ].field ).val().length < minval );
					$( '#charsRemaining_' + fieldname ).toggle( currentLength >= minval );
					break;
				;
				case "client_maxlength":
					maxval = rules[ r ].value;
					//add a maxlength function handler to this
					
					currentLength = $( '#' + rules[ r ].field ).val().length;
					
					$( '#charsRemaining_' + fieldname + ' span' ).text( maxval - currentLength );
					
					if ( currentLength <= maxval ) {
						$( '#textareaProgressbar')
							.css( 'background-color', '#5fbbde' )	//Set the background of the progressbar to blue
							.animate( { 'width': ( currentLength * 100 )/maxval + '%' }, 1 );
					}
					
					if ( currentLength == maxval )
						$( '#textareaProgressbar').css( 'background-color', 'red' );
					
					/*					
					if ( $( '#' + rules[ r ].field ).val().length > rules[ r ].value ) {
						var message = {
							'message': rules[ r ].errortext,
							'value': rules[ r ].value - $( '#' + rules[ r ].field ).val().length
						}
						errors[ errors.length ] = message;
					}
					*/
					break;
				;
			}
		}
		
		// should we show the value left?
		// set the max length		
		$( '#' + fieldname ).attr( 'maxlength', maxval );
		var enteredItems = parseInt( $( '#' + fieldname ).val().length );
		//if we are over the value and the tag is a textarea
		var item = $( '#' + fieldname ); 
		

		if ( item[ 0 ].nodeName == "TEXTAREA" && enteredItems > maxval ) {
			$( '#charsRemaining_' + fieldname + ' span' ).text( 0 );
			$( item ).val( $( item ).val().substr( 0, maxval ) );
			$( item ).setCursorPosition( $( item ).val().length );
			$( item ).animate({ scrollTop: $( item ).height() }, 1 );
		}		
		
		showError( fieldname, errors, true );
	}

	//Validates fields on the server side via ajax
	function validateFields(name,fieldList){
		var fieldList = fieldList;
		//we have a named form ::registerForm
		var params = $('form[id$=' + name + 'Form]').serializeArray();
			params[params.length] = {name:'fieldlist',value:fieldList};
		var handler = name;
		if ( handler != 'register' && handler != 'profile' ) {
			handler = 'Form';
		}
		$.post("/" + handler + "/validateField",
		          	$(params).filter(function(index){
				  	
					//We want to send the previousSection field
					if($(this).attr("name") == "previousSection"){
						return true;
					}
					if($(this).attr("name") == "fieldlist"){
						return true;
					}
					if($(this).attr("name") == "formName"){
						return true;
					}
					
					if(listFind(fieldList,$(this).attr("name"))){
						return true;
					}
					return false;
				  }),
                   function(data) {
						var clearFields = fieldList.split(",");
						for ( var i = 0; i < clearFields.length; ++i ) {
								$(".errors_" + clearFields[i]).each( function() {
									$(this).html("");
									$(this).hide();
								} );
						}
						if ( data.errors ) {
						 	var fields = {};
							//reset the errors for the fieldList
							//This is per field at any rate... we are only passing one field through
							for ( var e = 0; e < data.errorcollection.length; ++e ) {
								var erroritem = data.errorcollection[e];
								if ( !fields[erroritem.field] ) {
									fields[erroritem.field] = "";
								}	
								fields[erroritem.field] += '<div class="message warning"><p>' + erroritem.message +'</p></div>';
								
							}						
							
							for ( var key in fields ) {
								$(".errors_" + key).html(fields[key]);
								$(".errors_" + key).show();
							}
							
						}
					},
					"json"
               );
	}
	
	
function showError(field, messages, clear){
	var messageString = "";
	if(!clear){ clear = false; }
	if(!messages){ messages = []; }
	if(clear){ $(".errors_" + field).html("").hide(); }
	
	if(messages.length){
		for (var e = 0; e < messages.length; e++) {
			messageString += '<div class="message warning"><p>' + messages[e].message +'</p></div>';
		}
		$(".errors_" + field).html(messageString).show();
	}	
}
	
	
function listFind(list,item){
	var loopList = list.split(",");
	for(var i=0; i < loopList.length; i++){
		if(item == loopList[i]){
			return true;
		}		
	}
	return false;
}	
