jQuery.fn.uniform = function(settings) {
  settings = jQuery.extend({
    valid_class    : 'valid',
    invalid_class  : 'invalid',
    focused_class  : 'focused',
    holder_class   : 'ctrlHolder',
    field_selector : 'input, select, textarea'
  }, settings);
  
  return this.each(function() {
    var form = jQuery(this);
    
    // Focus specific control holder
    var focusControlHolder = function(element) {
      var parent = element.parent();
      
      while(typeof(parent) == 'object') {
        if(parent) {
          if(parent[0] && (parent[0].className.indexOf(settings.holder_class) >= 0)) {
            parent.addClass(settings.focused_class);
            return;
          } // if
        } // if
        parent = jQuery(parent.parent());
      } // while
    };
    
    // Select form fields and attach them higlighter functionality
    form.find(settings.field_selector).focus(function() {
      form.find('.' + settings.focused_class).removeClass(settings.focused_class);
      focusControlHolder(jQuery(this));
    }).blur(function() {
      form.find('.' + settings.focused_class).removeClass(settings.focused_class);
    });
  });
};

// Calcular Edad
function displayage(date){

var temp = date.split("/")
yr = temp[2]
mon = temp[1]
day = temp[0]
unit = "years"
decimal = 0
round = "rounddown"

var one_day=1000*60*60*24
var one_month=1000*60*60*24*30
var one_year=1000*60*60*24*30*12

today=new Date()
var pastdate=new Date(yr, mon-1, day)

var countunit=unit
var decimals=decimal
var rounding=round

finalunit=(countunit=="days")? one_day : (countunit=="months")? one_month : one_year
decimals=(decimals<=0)? 1 : decimals*10

yearspast=today.getFullYear()-yr-1
tail=(today.getMonth()>mon-1 || today.getMonth()==mon-1 && today.getDate()>=day)? 1 : 0
pastdate.setFullYear(today.getFullYear())
pastdate2=new Date(today.getFullYear()-1, mon-1, day)
tail=(tail==1)? tail+Math.floor((today.getTime()-pastdate.getTime())/(finalunit)*decimals)/decimals : Math.floor((today.getTime()-pastdate2.getTime())/(finalunit)*decimals)/decimals
var age = parseFloat(yearspast+tail)
return age

}
// Calcular Edad

function validateField(f) {
	if ( $(f).val() != "" ) {
		$(f).parent().removeClass('error');
		return true;
	} else {
		$(f).parent().addClass('error');
		return false;
	}
}

function rmArray(array, item) {
	var i = 0;
	while (i < array.length) {
		if (array[i] == item) {
			array.splice(i, 1);
		} else {
			i++;
		}
	}
	return array;
}

// Auto set on page load...
$(document).ready(function() {
	
  	jQuery('form.uniForm').uniform();
	
	$('.uniForm').submit(function(){

			inpTotalCount = $('.uniForm input.required').length;
			inpCount = 0;
			chkTotalCount = $('.uniForm input:checkbox').length;
			chkCount = 0;
			txtTotalCount = $('.uniForm textarea.required').length;
			txtCount = 0;
			planJoven = true;
			fechaValid = true;

			$('.uniForm input.required').each(function(){

				if ( validateField($(this)) == true ) {
					inpCount = inpCount + 1;
				}

			});
			
			$('.uniForm textarea.required').each(function(){

				if ( validateField($(this)) == true ) {
					txtCount = txtCount + 1;
				}

			});
			
			$('.uniForm #servicio_contrato option:selected').each(function() {
				if ( $(this).val() == "Plan Joven" && $('.uniForm input#fecha').val() != "dd/mm/aaaa" ) {
					var age = displayage($('.uniForm input#fecha').val());
					if ( age > 25 ) {
						var text = "<br /><br />El <b>Plan Joven</b> solo se puede seleccionar si eres menor de 25 años.";
						$('.uniForm input#fecha').parent().addClass("error").append(text);
						planJoven = false;
					} else if ( age == false ) {
						$('.uniForm input#fecha').parent().addClass("error");
						planJoven = false;
					} else {
					}
				}
				
			});
			
			if ( $('.uniForm input#fecha').val() == "dd/mm/aaaa" ) {
				$('.uniForm input#fecha').parent().addClass("error");
				fechaValid = false;
			}
			
			$('.uniForm input:checkbox').each(function() {
				
				if ( !this.checked ) {
					$(this).parent().parent().parent().addClass("error");
				} else {
					chkCount = chkCount + 1;
				}
				
			});

			if ( inpTotalCount == inpCount && chkTotalCount == chkCount && txtTotalCount == txtCount && planJoven && fechaValid ) {
				return true;
			}
			
			return false;

		});

		$('.uniForm input.required').keydown(function(){

			validateField($(this));

		});
		
		$('.uniForm input#fecha').click(function() {
			if ( $(this).val() == "dd/mm/aaaa" ) {
				$(this).val("");
			}
		})
		
		$('.uniForm #servicio_contrato').change(function() {
			var val = $(this).val();
			if ( val == "Plan Joven" ) {
				$('.uniForm #ve_mas').hide();
				$('.uniForm .ve2').hide();
				$('.uniForm .ve3').hide();
				counter = 1;
			} else {
				if ( counter < 3 ) {
					$('.uniForm #ve_mas').show();
				}
			}
			
			// Agregar informacion al plan seleccionado
			var cla = $(':selected').attr("id");
			$('.uniForm .info_plan:visible').each(function() {
				$(this).hide();
			});
			$('.uniForm #info_'+cla).show();
			
		});
		
		if ( $('.uniForm span.plan_joven').length ) { // Si existe el span.plan_joven, significa que esta seleccionado ese plan
			
			// Avisamos que necesita tener menos de 25 años para contratar este plan
			var text = "<br /><br />El <b>Plan Joven</b> solo se puede seleccionar si eres menor de 25 años.";
			$('.uniForm input#fecha').parent().append(text);
			
			// Escondemos los vehiculos extra
			$('.uniForm #ve_mas').hide();
			$('.uniForm .ve2').hide();
			$('.uniForm .ve3').hide();
			
		}
		
		$('.uniForm input:checkbox').change(function() {
			$(this).parent().parent().parent().removeClass("error");
		});
		
		ve_max = 3; // Maximo numero de vehiculos
		counter = 1;
		
		$('.uniForm #ve_mas').click(function() {
			
			var id = counter + 1;
			
			$('.uniForm .ve'+id).slideDown('500');
			
			counter = id;
			
			if ( counter == ve_max ) {
				$('.uniForm #ve_mas').hide();
			}
			
			return false;
			
		});
		
		$('.uniForm button.back').click(function() {
			history.go(-1);
		});
		
		// Contact Form
		$('.uniForm #contactarlo_telefono').click(function() {
			var inVal = $('.uniForm label.tel').html();
			$('.uniForm label.tel').html("<em>*</em> "+inVal);
			$('.uniForm #telefono').addClass('required');
		});
		
		$('.uniForm .como_contact input').change(function() {
			if ( $(this).attr("id") != "contactarlo_telefono" ) {
				$('.uniForm label.tel').html("Telefono");
				$('.uniForm #telefono').removeClass('required').parent().removeClass('error');
			}
		});
	
});