(function($){
	Drupal.behaviors.ee_load_order_form = {
    	attach: function(context, settings) {
    		// add validations
    		var form = $("#planilla-de-descargue-node-form");
    		// create validation rules
    		var validate_rules = {
				'field_peso[und][0][value]': {
					number: true,
				},
				'field_agencia[und][0][target_id]': {
					required: true,
				},
				'field_furg_n[und]': {
					required: true,
				},
				// 'field_conductor[und][0][target_id]': {
				// 	required: true,
				// },
				'field_ciudad[und][0][target_id]': {
					required: true,
				},
				'field_unidades[und][0][value]': {
					required: true,
					number: true,
				},
				// 'field_peso[und][0][value]': {
				// 	required: true,
				// 	number: true,
				// },
				// 'field_capacidad[und][0][value]': {
				// 	required: true,
				// 	number: true,
				// },
				// 'field_total_gu_as[und][0][value]': {
				// 	required: true,
				// 	number: true,
				// },
			};
			// create validation messages
			var validate_messages = {
				'field_peso[und][0][value]': {
					number: "Este campo debe ser un numero valido.",
				},
				'field_agencia[und][0][target_id]': {
					required: "Este campo es requerido",
				},
				'field_furg_n[und]': {
					required: "Este campo es requerido",
				},
				// 'field_conductor[und][0][target_id]': {
				// 	required: "Este campo es requerido",
				// },
				'field_ciudad[und][0][target_id]': {
					required: "Este campo es requerido",
				},
				'field_unidades[und][0][value]': {
					required: "Este campo es requerido",
					number: "Este campo debe ser un numero valido",
				},
				// 'field_peso[und][0][value]': {
				// 	required: "Este campo es requerido",
				// 	number: "Este campo debe ser un numero valido",
				// },
				// 'field_capacidad[und][0][value]': {
				// 	required: "Este campo es requerido",
				// 	number: "Este campo debe ser un numero valido",
				// },
				// 'field_total_gu_as[und][0][value]': {
				// 	required: "Este campo es requerido",
				// 	number: "Este campo debe ser un numero valido",
				// },
			};

			// add validation rules to form
			form.validate({
				rules: validate_rules,
				messages: validate_messages,
		    });

    		// perform actions after ajax
    		$(document).ajaxComplete(function(event,xhr,settings){
    			// calculations after add ajax
    			if("extraData" in settings){
			        if("_triggering_element_name" in settings.extraData){
						if(settings.extraData._triggering_element_name == "field_uo_carga_manual_de_guias_add_more"){
							uoCalculateUnits();
							$("input[id*=field-uo-unidades-totales-und]").each(function(){
								$(this).rules("remove");
					            $(this).rules("add", {
					              	required: true,
					                number: true,
					                min: uoGetTotalUnits(this),
					                max: uoGetTotalUnits(this),
					                messages: {
					                  	required: "Este campo es requerido",
					                  	number: "Este campo solo debe contener numeros.",
					                  	min: "Las unidades ingresadas no coinciden con las unidades totales"
					                },
				                });
				            });

				            $("input[id*=field-uo-unidades-totales-und]").on('change',function(){
				    			uoCalculateUnits();
				    		});

				    		$("input[id*=field-uo-unidades-totales-und]").on('blur',function(){
				    			uoCalculateUnits();
				    		});

				    		$("input[id*=field-uo-unidades-totales-guia-und]").on('change',function(){
				    			uoCalculateUnits();
				    		});

				    		$("input[id*=field-uo-unidades-totales-guia-und]").on('blur',function(){
				    			uoCalculateUnits();
				    		});
						}
			    	}
				}

				// calculations after delete ajax
				if("extraData" in settings){
					if("_triggering_element_name" in settings.extraData){
						if(settings.extraData._triggering_element_value == "Eliminar"){
							uoCalculateUnits();
						}
					}
				}
    		});

    		// set actions for inputs in fieldcollection

    		$("input[id*=field-uo-unidades-totales-und]").on('change',function(){
    			uoCalculateUnits();
    		});

    		$("input[id*=field-uo-unidades-totales-und]").on('blur',function(){
    			uoCalculateUnits();
    		});

    		$("input[id*=field-uo-unidades-totales-guia-und]").on('change',function(){
    			uoCalculateUnits();
    		});

    		$("input[id*=field-uo-unidades-totales-guia-und]").on('blur',function(){
    			uoCalculateUnits();
    		});

    		$("input[id*=field-uo-unidades-totales-und]").each(function(){
				$(this).rules("remove");
	            $(this).rules("add", {
	              	required: true,
	                number: true,
	                min: uoGetTotalUnits(this),
	                max: uoGetTotalUnits(this),
	                messages: {
	                  	required: "Este campo es requerido",
	                  	number: "Este campo solo debe contener numeros.",
	                  	min: "Las unidades ingresadas no coinciden con las unidades totales",
	                  	max: "Las unidades ingresadas no coinciden con las unidades totales",
	                },
                });
            });

    		function uoGetTotalUnits(field){
    			field = $(field);
    			var u = parseInt(field.val());
    			var id = field.attr('id');
				var start = id.indexOf("unidades");
				var sString = id.substring(0,start);
				var eString = id.substring(start+16);
				var newId = sString+"unidades-totales-guia"+eString;
				var total = parseInt($("#"+newId).val());
    			if( total ){
    				return total;
    			} else {
    				return 0;
    			}
    		}

    		function getNumbers(inputString){
			    var regex=/\d+\.\d+|\.\d+|\d+/g, 
			        results = [],
			        n;

			    while(n = regex.exec(inputString)) {
			        results.push(parseFloat(n[0]));
			    }

			    return results;
			}

    		// helper function to calculate units and set total units value
    		function uoCalculateUnits(){
    			// declare variables
    			var rows = $("table[id^=field-uo-carga-manual-de-guias-values]").find("tbody>tr").length;
    			units = 0;
    			// loop through rows adding existing values
    			// edit-field-uo-carga-manual-de-guias-und-0-field-uo-unidades-totales-und-0-value
    			for (var i = 0; i < rows; i++) {
    				var j = parseInt($("[id^=edit-field-uo-carga-manual-de-guias-und-"+i+"-field-uo-unidades-totales-und]").val());
    				// var t = parseInt($("[id^=edit-field-uo-carga-manual-de-guias-und-"+i+"-field-uo-unidades-totales-guia-und]").val());
    				units = units + j;
    			}
    			// set max units
    			$("#edit-field-unidades-und-0-value").val(units);
    			// set amount of guides
    			$("#edit-field-total-gu-as-und-0-value").val(rows);
    		}

    	}
	}
})(jQuery);