function removeMe(e){
	if($('.att_field').length > 1){
		$(this).parent().remove();
	}else{
		$(this).prev().val('');
	}
	e.preventDefault();
}
function isInteger(s) {
  return (s.toString().search(/^-?[0-9]+$/) == 0);
}
function mergeObj(obj1, obj2){
	if(obj1 == {} || !obj1) return obj2;
	if(obj2 == {} || !obj2) return obj1;
	for(var i in obj2){ obj1[i] = obj2[i];}
	return obj1;
}
function not_empty(validate_ne, errors){
	var ret_errors = {};
	for(var key in validate_ne['input']){
		var inputName = key;
		var parentLvl; var element;
		if(isInteger(validate_ne['input'][key])){
			parentLvl = validate_ne['input'][key];
			element = $(':input[name="' + inputName + '"]');
		}else{
			parentLvl = validate_ne['input'][key]['parentLvl'];
			element = validate_ne['input'][key]['element'];
		}
		ret_errors[inputName] = checkError(element, parentLvl);
	}
	
	for(var key in validate_ne['textarea']){
		var inputName = key;
		var parentLvl; var element;
		if(isInteger(validate_ne['textarea'][key])){
			parentLvl = validate_ne['textarea'][key];
			element = $('textarea[name="' + inputName + '"]');
		}else{
			parentLvl = validate_ne['textarea'][key]['parentLvl'];
			element = validate_ne['textarea'][key]['element'];
		}
		ret_errors[inputName] = checkError(element, parentLvl);
	}
	
	return mergeObj(errors, ret_errors);
}
function checkError(element, parentLvl){
	var ret = (element.val()) ? ((element.val().length < 1) ? true : false): true;
	
	if(ret){
		var elToError = element;
		for(var i = parentLvl; i > 0; i--){
			elToError = elToError.parent();
		}
		elToError.addClass('error');
	}
	return ret;
}
function combineVals(className){
	var ret = [];
	$('.' + className).each(function(i){
		var ret_str = $(this).val();
		ret_str = ret_str.replace(/,/, '|');
		ret[ret.length] = ret_str;
	})
	return ret.join(',');
}
function prepareCsvVals(){
	var combineArr = [
		'unit_gen_unit','unit_prim_fuel','unit_back_fuel','unit_capacity','unit_opdate','unit_elifespan',
		'unit_max_available','unit_max_injected',	'unit_opdate_lifespan', 'unit_provide_reserve',
		
		'sch_date', 'sch_proposed_action',
		
		'perf_gen_unit', 'perf_reliability', 'perf_factor', 'perf_for', 'perf_af', 'perf_srf', 'perf_load_factor',
		
		'fin_gen_unit', 'fin_capacity', 'fin_capital_cost', 'fin_fixed_om', 'fin_var_om', 'fin_fuel', 'fin_credits', 'fin_avg_cost_capital', 'fin_discount_rate', 'fin_interest_rate',
		
		'con_gen_unit', 'con_oc', 'con_heatrate', 'con_consumption', 'con_msl'
	];
	jQuery.each(combineArr, function(){
		$(':input[name="data[LicenceGenCom][' + this + ']"]').val(combineVals(this));
	})
}
$(function(){
	$('#addMoreFile').click(function(e){
		$('.att_field:last').after($('.att_field:last').clone());
		$('.att_field:last a.removeMe').click(removeMe).prev().val('');
		e.preventDefault();
	});
	$('a.removeMe').click(removeMe);
	$('#LicenceGenComAddForm').submit(function(e){
		$('.error').removeClass('error');
		$('#error-msg').hide();
		
		var validate_ne = {
				'input':{
					'data[LicenceGenCom][name]' : 1,
					'data[LicenceGenCom][od_exempted_gen]' : 1,
					'data[LicenceGenCom][od_exempted_gas]' : 1,
					'data[LicenceGenCom][has_other_licence]' : 1,
					'data[LicenceGenCom][related_has_elicence]' : 1,
					'data[LicenceGenCom][related_has_glicence]' : 1,
					
					'data[LicenceGenCom][unit1_gen_unit]' : 0,  
					'data[LicenceGenCom][unit1_prim_fuel]': 0, 
					'data[LicenceGenCom][unit1_back_fuel]': 0, 
					'data[LicenceGenCom][unit1_capacity]' : 0, 
					'data[LicenceGenCom][unit1_opdate]' : 0, 
					'data[LicenceGenCom][unit1_elifespan]' : 0, 
					'data[LicenceGenCom][unit1_max_available]' : 0, 
					'data[LicenceGenCom][unit1_max_injected]' : 0,
					'data[LicenceGenCom][unit1_provide_reserve]' : 0,
					
					'data[LicenceGenCom][gas_supplier]' : 1,
					'data[LicenceGenCom][gas_amt]' : 1,
					'data[LicenceGenCom][gas_contract]' : 1,
					
					'data[LicenceGenCom][sch1_date]' : 0,
					'data[LicenceGenCom][sch1_proposed_action]' : 0,
					
					'data[LicenceGenCom][perf1_gen_unit]': 0,
					'data[LicenceGenCom][perf1_reliability]' : 0,
					'data[LicenceGenCom][perf1_factor]' : 0, 
					'data[LicenceGenCom][perf1_for]' : 0,
					'data[LicenceGenCom][perf1_af]' : 0,
					'data[LicenceGenCom][perf1_srf]' : 0,
					'data[LicenceGenCom][perf1_load_factor]' : 0,
					
					'data[LicenceGenCom][con1_gen_unit]': 0,
					'data[LicenceGenCom][con1_oc]' : 0,
					'data[LicenceGenCom][con1_heatrate]' :0,
					'data[LicenceGenCom][con1_consumption]' :0,
					'data[LicenceGenCom][con1_msl]':0,
					
					'data[LicenceGenCom][failed_before]' : 1,
					
					'data[LicenceGenCom][fin1_gen_unit]' : 0,
					'data[LicenceGenCom][fin1_capacity]' : 0,
					'data[LicenceGenCom][fin1_capital_cost]' : 0,
					'data[LicenceGenCom][fin1_fixed_om]' : 0,
					'data[LicenceGenCom][fin1_var_om]' : 0,
					'data[LicenceGenCom][fin1_fuel]' : 0,
					'data[LicenceGenCom][fin1_credits]' : 0,
					'data[LicenceGenCom][fin1_avg_cost_capital]' : 0,
					'data[LicenceGenCom][fin1_discount_rate]' : 0,
					'data[LicenceGenCom][fin1_interest_rate]' : 0,
					
					
					'data[LicenceGenCom][signature]': 1,
					'data[LicenceGenCom][app_name]' : 1,
					'data[LicenceGenCom][app_designation]' :1,
					'data[LicenceGenCom][app_ic]' : 1,
					'data[LicenceGenCom][app_company_name]':1,
					'data[Attachment][file][]' : {
						'parentLvl' : 1,
						'element' : $('.att_field:first').children('input') 
					}
				},
				'textarea':{
					'data[LicenceGenCom][experience_details]' : 1,
					'data[LicenceGenCom][sh_roles]' : 1,
					'data[LicenceGenCom][loc_plan_details]' : 1,
					'data[LicenceGenCom][fuel_sufficiency_proposal]':1,
					'data[LicenceGenCom][similar_installations_details]' : 1,
					'data[LicenceGenCom][suppliers_details]' : 1,
					'data[LicenceGenCom][env_impact_details]' : 1,
					'data[LicenceGenCom][gen_unit_details]' :1,
					'data[LicenceGenCom][dynamic_perf_details]':1,
					'data[LicenceGenCom][gen_unit_capability_details]' : 1
				}
		};
		var errors = not_empty(validate_ne);
		var s_validate_ne = {'textarea':{}};
		if(!errors['data[LicenceGenCom][od_exempted_gen]'] && $(':input[name="data[LicenceGenCom][od_exempted_gen]"]').val() == 1){
			s_validate_ne['textarea']['data[LicenceGenCom][od_exempted_gen_details]'] = 1;
		}
		if(!errors['data[LicenceGenCom][od_exempted_gas]'] && $(':input[name="data[LicenceGenCom][od_exempted_gas]"]').val() == 1){
			s_validate_ne['textarea']['data[LicenceGenCom][od_exempted_gas_details]'] = 1;
		}
		
		
		if(!errors['data[LicenceGenCom][has_other_licence]'] && $(':input[name="data[LicenceGenCom][has_other_licence]"]').val() == 1){
			s_validate_ne['textarea']['data[LicenceGenCom][other_licence_details]'] = 1;
		}
		if(
			!errors['data[LicenceGenCom][related_has_elicence]'] &&
			!errors['data[LicenceGenCom][related_has_glicence]'] &&
			(
				$(':input[name="data[LicenceGenCom][related_has_elicence]"]').val() == 1 ||
				$(':input[name="data[LicenceGenCom][related_has_glicence]"]').val() == 1
			)
		){
			s_validate_ne['textarea']['data[LicenceGenCom][related_details]'] = 1;
		}
		if(!errors['data[LicenceGenCom][failed_before]'] && $(':input[name="data[LicenceGenCom][failed_before]"]').val() == 1){
			s_validate_ne['textarea']['data[LicenceGenCom][failed_before_details]'] = 1;
		}
		errors = not_empty(s_validate_ne, errors);
		
		var ret = true;
		for(var key in errors){
			if(errors[key]){
				ret = false;
			}
		}
		if(!ret){
			$('#error-msg').show();
		}else{
			$('.formContainer input').attr('disabled', 'disabled');
			$('.formContainer textarea').attr('disabled', 'disabled');
			$('.formContainer select').attr('disabled', 'disabled');
			$('.formContainer').addClass('reviewContainer');
			$('.finalSubmit').show();
			$('a.removeMe').hide();
			$('#addMoreFile').hide();
			$('#nextStep').hide();
			prepareCsvVals();
		}
		$(document).scrollTo($('a[name="top"]'), 800);
		
		ret = ($(':input[name="reviewForm"]').val() == 1) && ret;
		if(ret){
			$('.formContainer input').removeAttr('disabled');
			$('.formContainer textarea').removeAttr('disabled');
			$('.formContainer select').removeAttr('disabled');
			return true;
		}
		return ret;
	});
	$('#editForm').click(function(){
		$('.formContainer input').removeAttr('disabled');
		$('.formContainer textarea').removeAttr('disabled');
		$('.formContainer select').removeAttr('disabled');
		$('.formContainer').removeClass('reviewContainer');
		$('.finalSubmit').hide();
		$('a.removeMe').show();
		$('#addMoreFile').show();
		$('#nextStep').show();
		$(':input[name="reviewForm"]').val(0);
		$(document).scrollTo($('a[name="top"]'), 800);
	});
	$('#submitForm').click(function(){
		$(':input[name="reviewForm"]').val(1);
	});
});
