
// Rewritten form handling
/**
 * Wrapper to allow "value in [array]" statements
 * Wraps the array in an object-literal
 * Use: "value in oc([array])"
 *
 */

function oc(a){
    var o = {};
    for(var i=0;i<a.length;i++){
    o[a[i]]='';
    }
  return o;
};

function string_to_array(string){
  var ret_array = Array();
  for(i=0; i<string.length; i++){
    ret_array[i] = string.charAt(i);
  }
  return ret_array;
};
    
function fpn(value){
        var f = string_to_array(value);
        var k1 = (11 - (((3 * f[0]) + (7 * f[1]) + (6 * f[2]) + (1 * f[3]) + (8 * f[4]) + (9 * f[5]) + (4 * f[6]) + (5 * f[7]) + (2 * f[8])) % 11))%11;
        var k2 = (11 - (((5 * f[0]) + (4 * f[1]) + (3 * f[2]) + (2 * f[3]) + (7 * f[4]) + (6 * f[5]) + (5 * f[6]) + (4 * f[7]) + (3 * f[8]) + (2 * k1)) % 11))%11;
        if(k1 ==11){k1=0};
        if(k1!=f[9] || k2 != f[10]){
            return false;
        }
        return true;
    };

function lanebelop(value){
		var belop = parseInt(value);
		return !(belop < 10000 || belop > 350000 || isNaN(belop));
}

function niceButtons() {
/* Pene knapper */
	// Add Forrige
	$('#custom-forrige').remove();
	$('#prev:not(:hidden)').parent().append('<span id="custom-forrige" class="custom-button">Forrige</span>');
	$('#prev:not(:hidden)').hide();
	$('#custom-forrige').mousedown(function(){
		$(this).addClass('active');
	}).mouseup(function(){
		$(this).removeClass('active');
	}).mouseover(function(){
		$(this).addClass('hover');
	}).mouseout(function(){
		$(this).removeClass('hover');
	}).click(function(){
		$('#prev').click();
	});
	// Add neste
	$('#custom-neste').remove();
	$('#next:not(:hidden)').parent().append('<span id="custom-neste" class="custom-button" tabindex="0">Neste</span>');
	$('#next:not(:hidden)').hide();
	$('#custom-neste').mousedown(function(){
		$(this).addClass('active');
	}).mouseup(function(){
		$(this).removeClass('active');
	}).mouseover(function(){
		$(this).addClass('hover');
	}).mouseout(function(){
		$(this).removeClass('hover');
	}).click(function(){
		$('#next').click();
		this.blur();
	}).keypress(function(event){
		if (event.keyCode == '13') {
     		$('#next').click();
			this.blur();
   		}
	});
	// Add fullfør
	$('#custom-fullfor').remove();
	$('#complete:not(:hidden)').parent().append('<span id="custom-fullfor" class="custom-button" tabindex="0">Fullfør</span>');
	$('#complete:not(:hidden)').hide();
	$('#custom-fullfor').mousedown(function(){
		$(this).addClass('active');
	}).mouseup(function(){
		$(this).removeClass('active');
	}).mouseover(function(){
		$(this).addClass('hover');
	}).mouseout(function(){
		$(this).removeClass('hover');
	}).click(function(){
		$('#complete').click();
	}).keypress(function(event){
		if (event.keyCode == '13') {
     		$('#complete').click();
   		}
	});
};

 var create_repeat_manager = function($wrapper){
    
    var init = function(){
        _update_lines();
       
        $wrapper.after("<input type='button' id='addline' value='Legg til ny linje'>")
        $wrapper.next().click(_add_line);
        var counter = 0;
        $wrapper.children().each(function(){
            var $this = $(this);
            if($this.find('.button-container').length != 0){
                var $container = $this.find('.button-container');
            }else{
                var $container = $this;
            }
        	if(counter < 3){
        		$container.append("<input type='button' value='Fjern' style='visibility:hidden'>")
        		counter++;
        		return;
        	}
            $container.append("<input type='button' value='Fjern'>")
            $container.last().click(function(){
               $this.addClass('hidden');
               _update_lines();
            });
        });
    }
  
    var _update_lines = function(){
        $wrapper.children('div.hidden').each(_hide_line);
        $wrapper.children('div:not(.hidden)').each(_show_line);
    };
  
    var _hide_line = function(){
        $(this).find('input:not(:button), select, textarea').each(function(){
            $(this).attr({'disabled': true});
            $(this).addClass('inhiddenline');
            $('#' + $(this).attr('id') + '-errormessage').remove();
            this.value = '';
        });
        $(this).hide();
    };
  
    var _show_line = function(){
        $(this).show()
        	   .find('input, select, textarea')
               .filter(':not(.dependent)')
               .removeAttr('disabled')
               .removeClass('inhiddenline');
    };
  
    var _add_line = function(){
        $wrapper.children('.hidden').first().removeClass('hidden').find('.inhiddenline').removeClass('inhiddenline');
        _update_lines();
    };
  
    init();
}

var create_dependency_manager = function(dep_array) {
    var _add_dependency = function(){
        var $target     = $(this[0]);
        var triggers    = this[1];
        var condition   = this[2];
        $(triggers).each(function(){
            _check_dependency($target, condition);
            $(this).change(function(){_check_dependency($target, condition)});
        });
    };
    var remove_error_message = function(target_id){
            $('#'+target_id+'-errormessage').remove();  
    };
    
    var _check_dependency = function($target, condition){
        if(eval(condition)){
            $target.show()
            $target.find('input, select, textarea')
                   .removeClass('dependent')
                   .filter(':not(.inhiddenline)')
                   .removeAttr('disabled');
        }else{
            $target.hide();
            $target.find('input, select, textarea').each(function(){
	            $(this).addClass('dependent')
	            	   .filter(':not(.inhiddenline)')
	                   .attr('disabled', true);
	            $(this).val('');
                remove_error_message(this.id);
            })
        }
    };
    $(dep_array).each(_add_dependency);
};

var create_validation_manager = function(val_array){
    var validation_functions = ['fpn', 'lanebelop'];
    var _add_validation = function(){
        var $target             = $(this[0]);
        var rule                = eval(this[1]);
        var mandatory           = this[2];
        var validation_message  = this[3];
        var mandatory_message   = this[4];
        $target.change(function(){
        	disable_empty_repeats();
        	if(!$target.is(':disabled')){
            	validate_field($target, rule, mandatory, validation_message, mandatory_message);
            }
        	$('.empty_line').find('input, select, textarea').filter(':not(.dependent)').removeAttr('disabled');
        	$('.empty_line').removeClass('empty_line');
        });
    };
    
    var validate_field = function($target, rule, mandatory, validation_message, mandatory_message){
        var target_value = $target.val();
        var target_id = $target.attr('id');
        if(mandatory && target_value == ""){
            toggle_error_message(target_id, mandatory_message, true);
            return;
        }else{
            toggle_error_message(target_id, mandatory_message, false);
        }
        if(!mandatory && target_value == ""){
            toggle_error_message(target_id, mandatory_message, false);
            return;
        }
        if(rule == "no"){
            
        }else if(rule in oc(validation_functions)){
            var func = eval(rule); //Rule is a function name
            toggle_error_message(target_id, validation_message, !func(target_value));
        }else{
            toggle_error_message(target_id, validation_message, !rule.test(target_value));
        }
    };
    
    var toggle_error_message = function(target_id, message, on){
        if(on){
            if($('#'+target_id+'-errormessage').length == 0){
                $('#error_transcript').append('<li id="'+target_id+'-errormessage">'+message+'</li>');
            }
        }else{
            $('#'+target_id+'-errormessage').remove();  
        }
    };
    
    var disable_empty_repeats = function(){
    	$('.repeatwrap > div:not(:hidden)').each(function(){
    		var $form_elements = $(this).find('input:not(:button), select, textarea');
    		var is_empty = true;
    		$form_elements.each(function(){
    			if($(this).val() != ''){
    				is_empty = false;
    			}
    		});
    		if(is_empty){
	    		$(this).addClass('empty_line');
	    	}
    	});
    	$('.empty_line').find('input, select, textarea').each(function(){
    		$target = $(this);
	    	$target.attr('disabled', 'disabled');
	    	toggle_error_message($target.attr('id'), '', false);
	    });
    };
    
    var trigger_validations = function($root_element){
        $('#error_transcript').children().remove();
        disable_empty_repeats();
        $root_element.find('input, select, textarea').filter(':not(:disabled)').filter(':not(:hidden)').trigger('change');
        $('.empty_line').find('input, select, textarea').filter(':not(.dependent)').removeAttr('disabled');
        $('.empty_line').removeClass('empty_line');
        var errors = $('#error_transcript').children().length;
        if(errors != 0){
            return false;
        }
        return true;
    }

    
    $(val_array).each(_add_validation);
    
    return {
        trigger_validations : trigger_validations,
        disable_empty_repeats : disable_empty_repeats
    }
}

$(function(){
    $('#nav').show();
    $(".repeatwrap").each(function(){
        create_repeat_manager($(this));
    });
    // Initialiser avhengigheter og validering
    var Dep, Val;
    if(typeof valid_and_depend_json !== "undefined"){
        if(typeof valid_and_depend_json['depend'] !== "undefined"){
            Dep = create_dependency_manager(valid_and_depend_json['depend']);
        }
        if(typeof valid_and_depend_json['valid'] !== "undefined"){
            Val = create_validation_manager(valid_and_depend_json['valid']);
        }
    }
    $("form").submit(function(){
        if($('#next:not(:hidden)').length){
            $('#next').trigger('click');
            return false;
        }
        if(!Val.trigger_validations($("form"))){
        	return false;
        }
        Val.disable_empty_repeats();
        $('body').append('<div id="overlay"><div>Søknaden sendes<br><img src="pics/graphics/loader2.gif" alt="Sender…" /></div></div>');
        return true;
    });
    // Legg pŒ multipage funksjonalitet hvis det trengs
    if($('#tabs').length){ // Vi har tabs
        var $tabs = $('#tabs').tabs({
            show: function(event, ui) {
                var selected    = $(this).tabs('option', 'selected');
                var tab_length  = $(this).tabs('length');
                
                if(selected == 0){                  $('#prev').hide()}
                else{                               $('#prev').show()}
                
                if(selected == (tab_length - 1)){   $('#next').hide(); $('#complete').show()}
                else{                               $('#next').show(); $('#complete').hide()}
                
                // Funksjon som håndterer validering
            }
        });
        
        $('#tablist').hide();
        
        $('#complete').click(function(){
        	$('form').submit();
        	return false;
        });
        
        $('#next').click(function() {
            var selected = $tabs.tabs('option', 'selected');
            var $selected_tab = $("#tabs-"+(selected + 1));
            if(Val){
                if(!Val.trigger_validations($selected_tab)){
                    return false;
                }
            }
            
            var tab_length = $tabs.tabs('length');
            $tabs.tabs('select', (selected + 1) % tab_length);    
		    niceButtons();
            return false;
        });
        
        $('#prev').click(function(){
            var selected = $tabs.tabs('option', 'selected');
            var $selected_tab = $("#tabs-"+(selected + 1));
   		    $('#error_transcript').children().remove();
            var tab_length = $tabs.tabs('length');
            $tabs.tabs('select', (selected + tab_length - 1) % tab_length);
    		niceButtons();
            return false;
        });
    }

    $('.help img').each(function(){
        $(this).qtip({
                content: $(this).siblings('div'),
                position: {
                  corner: { target: 'rightTop', tooltip: 'leftTop'},
                  adjust: { x: 2, y: 0 }
                },
                show: {
                  when: {event: 'mouseover'},
                  effect: {type: 'fade', length: 0},
                  delay: 0
                },
                hide: {
                  when: {event: 'mouseout'},
                  effect: {type: 'fade', length: 0},
                  delay: 0
                },
                style: {
                    border:  { width: 0},
                    background: 'transparent',
                    padding: 0,
                    margin: 0
                }
        })
    });
    niceButtons();
});

