$(document).ready(function() {

    /*	Dialog defaults	*/
    $.ui.dialog.defaults.width = 460;
    $.ui.dialog.defaults.modal = true;
    $.ui.dialog.defaults.bgiframe = true;
    $.ui.dialog.defaults.zIndex = 9999;
    $.ui.dialog.defaults.resizable = false;
    $.ui.dialog.defaults.draggable = false;
    $.ui.dialog.defaults.open = function() {
        $('.ui-widget-overlay').css({ opacity: 0 }).animate({ opacity: 0.8 });
    };

    /**
    * Extend number to be certain chars long by adding a specified character
    * 
    * @param {String} l	expected length of string to be returned
    * @param {String} p	fill character to prepend to string
    */
    String.prototype.prelongate = function(l, p) {
        p = p || 0;
        return (!!l && this.length < l)
			? new Array(l - this.length + 1).join(p) + this
			: this.toString();
    };


    /* Stripes table tr in content-block(s) (only not on XForms) */
    if ($('#XFormPanel').attr('id') === undefined) {
        $("#content .content-block table tr").mouseover(function() { $(this).addClass("over"); }).mouseout(function() { $(this).removeClass("over"); });
        $("#content .content-block table tr:even").addClass("alt");
    }

    /* XForms preparations */
    $("#innerXFormPanel input:radio").addClass("checkbox");
    $("#innerXFormPanel input:checkbox").addClass("checkbox");
    /* Wrap a span around the XForms submit button
       and give it the correct class in order to style it as all other buttons */
    //$("#innerXFormPanel input:submit").wrap("<span><span>").parent().addClass("input formsubmit");
    $("#innerXFormPanel input:submit").wrap("<span><span>").parent().addClass("input");
    $("#innerXFormPanel input:submit").addClass("btn");

    if (/msie|MSIE 6/.test(navigator.userAgent) || /msie|MSIE 7/.test(navigator.userAgent)) {
        $(function() {
            var zIndexNumber = 1000;
            $('.contentRow').find('div:not(.loginBtn)').each(function() {
                $(this).css('zIndex', zIndexNumber);
                zIndexNumber -= 10;
            });
        });
    }
    //Foldy list items
    $(".foldy .foldy-content").css({ display: 'none' });
    //	have to attach click event to <a> tag, so #.# doesn't add to page url... so ugly!
    $(".foldy h3 a").click(function(e) {
        e.preventDefault();
        $(this).parent()
			.next('.foldy-content')
				.slideToggle("slow")
			.end()
			.toggleClass("foldy-up");

    });

    // Table sorting on company administration
    $("#companies-table").tablesorter();
    $("#companies-under-creation-table").tablesorter();

    /* Load Spinner Lightbox */
    if (/msie|MSIE 6/.test(navigator.userAgent) || /msie|MSIE 7/.test(navigator.userAgent)) {
        $(".loadspinner").click(function() {
            $('#aspnetForm').submit();
            $('#spinner-overlay').expose({ api: true }).load();
            setTimeout(function() {
                $('#spinner-overlay').hide().show();
            }, 100);
        });
    }
    else if (/msie|MSIE 8/.test(navigator.userAgent)) {
        $(".loadspinner").click(function() {
            $('#aspnetForm').submit();
            $('#spinner-overlay').expose({ api: true }).load();
            setTimeout(function() {
                $('#spinner-overlay').hide().show();
            }, 100);
        });
    }
    else {
        $(".loadspinner").click(function() {
            $('#spinner-overlay').expose({ api: true }).load();
            $('#spinner-overlay').fadeIn('3500');
        });
    }

    /* Loginbox */
    $(".loginbox").hide();
    $(".loginBtn").mouseout(function() {
        var el = $(this);
        this.t = setTimeout(function() {
            el.find('.loginbox').hide()
        }, 50);
    }).mouseover(function() {
        clearTimeout(this.t);
    });
    /* toggle dropdown */
    $(".loginBtn .login-btn").click(function(e) {
        $(this).next('.loginbox').slideToggle("250");
        $(this).parents(".ss-center").css({ 'overflow': 'visible' });
    });

    /* Adds focus to input field  */
    $('input:text, textarea, select')
		.ieFocus(); // ONLY do focus javascript for ieshits, modern browsers support :focus

    /* Site Search */
    $('.sitesearch input')
		.focus(function() {
		    if (this.value == this.defaultValue) {
		        this.value = '';
		    }
		}).blur(function() {
		    if ($.trim(this.value) == '') {
		        this.value = (this.defaultValue ? this.defaultValue : '');
		    }
		});

    /*	add class disabled to disabled inputs	*/
    $('[disabled="disabled"]').data('disabled', true).addClass('disabled');

    /*	Alternate content - disabling inputs in hidden section	*/
    (function() {
        var update = function(e) {
            $(this).find('option').each(function() {
                var className = $(this).attr('value');
                $('.altcontent-' + className)
					.hide()
					.find(':input')
						.attr('disabled', 'disabled');
            });
            var className = $(this).val();
            $('.altcontent-' + className)
				.show()
				.find(':input')
            //	do not enable elements that were disabled on load
					.filter(function() {
					    return ($(this).data('disabled') != true);
					})
						.removeAttr('disabled');
        };
        $('.altcontent-switch')
			.change(update)
			.trigger('change');
    })();

    /* Resize text */
    $('.tt-resize').toggle(function() {
        $(".content-block *").addClass('large');
    }, function() {
        $(".content-block *").removeClass('large');
    });

    /* Print */
    $(".tt-print").click(function() {
        window.print();
    }
	);

    /*	lightbox response	*/
    if ($('#lightbox-feedback.show').length > 0) {
        $('#lightbox-feedback.show')
			.dialog()
			.find('input.btn')
				.click(function(e) {
				    e.preventDefault();
				    $('#lightbox-feedback.show').dialog('close')
				})
				.focus();

    }

    /* Toggle Lightbox and Expose script */
    if (/msie|MSIE 6/.test(navigator.userAgent) || /msie|MSIE 7/.test(navigator.userAgent)) {
        $(".tt-mail").click(function() {
            $('#overlay').show();
            $('.overlay-shadow').show();
            $('.content-block fieldset :input').addClass('ignore'); /* for validating - so the form in the lightbox submits */
        });

        $(".close").click(function() {
            $('.overlay-shadow').css('background', 'none');
            $('#overlay').fadeOut('5500');
            $('.content-block fieldset :input').removeClass('ignore'); /* for validating - so the form in the lightbox submits */
        });

    }

    else if (/msie|MSIE 8/.test(navigator.userAgent)) {
        $(".tt-mail").click(function() {
            $('#overlay').expose({ api: true }).load();
            $('#overlay').show();
            $('.overlay-shadow').show();
            $('.content-block fieldset :input').addClass('ignore'); /* for validating - so the form in the lightbox submits */
        });

        $(".close").click(function() {
            $('.overlay-shadow').css('background', 'none');
            $('#overlay').fadeOut('2500');
            $('#overlay').expose().close();
            $('.content-block fieldset :input').removeClass('ignore'); /* for validating - so the form in the lightbox submits */
        });
    }

    else {
        $(".tt-mail").click(function() {
            $('#overlay').expose({ api: true }).load();
            $('#overlay').fadeIn('3500');
            $('.overlay-shadow').show();
            $('.content-block fieldset :input').addClass('ignore'); /* for validating - so the form in the lightbox submits */
        });

        $(".close").click(function() {
            $('#overlay').fadeOut('3500');
            $('#overlay').expose().close();
            $('.content-block fieldset :input').removeClass('ignore'); /* for validating - so the form in the lightbox submits */
        });
    }
    $.validator.setDefaults({
        ignore: ':hidden, .ignore' /* only validate visible input fields */
    });

    // Do not alter SubmitHandler when on XForms
    if ($('#XFormPanel').attr('id') === undefined) {
        $("#aspnetForm").validate({
            submitHandler: function(form) {
                /*	attach a callback function to the asp form element
                * 	use this callback to cancel standard postback,
                *   pass control to other scripts and allow for ajax handling
                */
                if (typeof form.callback == 'function') {
                    form.callback();
                }
                else form.submit();
            }
        });
    }

    jQuery('select[name=fieldset-choice]').change(function() {
        var fieldsetName = $(this).val();
        $('fieldset[id]').hide().filter('#' + fieldsetName).show();
    });

    // We need to hide all fieldsets except the first:
    $('fieldset[id]').hide().filter('#f1').show();

    // submit on span inputs
    $('.formsubmit').click(function(e) {
        e.preventDefault();
        $('#aspnetForm').submit();
    }
	);

    // activete tip a friend when clicking send button in overlay content
    $('.overlay-content #sendtip').click(function() {
        $('.overlay-content #sendTip').val('True');
        //$('#aspnetForm').submit();
    }
	);

    // Ingen email
    $("#noemail").css({
        display: $('#form-kvittering').is(':checked') ? 'none' : 'block'
    });
    $("#form-kvittering").click(function() {
        //	disabled animation in ie due compatibility issues in ie8/7
        if ($(this).is(':checked')) $('#noemail').hide('v' == '\v' ? '' : 'slow');
        else $("#noemail").show('v' == '\v' ? '' : 'slow');
    });


    /* Form validation */
    $("#form-cpr").each(function() {
        $(this).rules("add", {
            required: true,
            cpr: true,
            cpralder18: true,
            cpralder75: true,
            messages: {
                required: "Skriv din f&#248;dselsdag (ddmm&#229;&#229;) efterfulgt af 4 cifre (fx 0105641212).",
                cpr: "Skriv din f&#248;dselsdag (ddmm&#229;&#229;) efterfulgt af 4 cifre (fx 0105641212).",
                cpralder18: "Du skal v&#230;re fyldt 18 &#229;r for at kunne indbetale.",
                cpralder75: "Du skal v&#230;re under 74 &#229;r og 11 m&#229;neder for at kunne indbetale."
            }
        });
    });

    $("#medl-cpr").each(function() {
        $(this).rules("add", {
            required: true,
            cprsyntax: true,
            messages: {
                required: "Skriv din f&#248;dselsdag (ddmm&#229;&#229;) efterfulgt af 4 cifre (fx 010564-1212).",
                cprsyntax: "Skriv din f&#248;dselsdag (ddmm&#229;&#229;) efterfulgt af 4 cifre (fx 010564-1212)."
            }
        });
    });

    $("#form-email, #medl-email, #virk-email, #orga-email, #andet-email").each(function() {
        $(this).rules("add", {
            required: true,
            email: true,
            messages: {
                required: "Emailadressen skal indeholde et @ og et punktum.",
                email: "Emailadressen skal indeholde et @ og et punktum."
            }
        });
    });

    $("#form-act-samtyk, #form-act-arbejdsdygtighed, #form-act-korrekte, #form-act-frivillig-indbetaling, .mustaccept").each(function() {
        $(this).rules("add", {
            required: true,
            messages: {
                required: "Betingelserne skal accepteres for at kunne forts&#230;tte."
            }
        });
    });

    jQuery.validator.addMethod("max80chr",
			function(value, element, params) {
			    return (value.length < 80);
			}, "Udfyld venligst mindre end 80 karakterer");

    jQuery.validator.addClassRules("max80chr", {
        maxlength: 80
    });

    // Add ean number validation method
    if ($('#form-eanno').length > 0) {
        jQuery.validator.addMethod("eannumber", function(value, element, params) {
            return this.optional(element) || /^\d{13}$/.test(value);
        }, "ean-number is not correct");

        $('#form-eanno').rules('add', {
            eannumber: true,
            messages: {
                eannumber: "Indtast venligst et 13-cifret tal i feltet"
            }
        });
    }

    //	konto nr validation and 0 prefixer
    if ($('#form-AccountNo').length > 0) {
        jQuery.validator.addMethod("kontonr",
			function(value, element, params) {
			    return (/^\d{2,10}$/.test(value) && parseInt(value, 10) != 0); //	have to use 2nd param for parseInt to make sure value is interpreted as base-10
			}, "Indtast venligst tal p&#229; mellem 2 og 10 cifre");

        //	auto add zeros for shorter acc numbers and validate
        $('#form-AccountNo').bind('change focus blur', function() {
            if ($(this).val().length > 1) {
                $(this).val($(this).val().prelongate(10, 0));
            }
        }).rules('add', {
            kontonr: true,
            messages: {
                kontonr: "Indtast venligst tal p&#229; mellem 2 og 10 cifre"
            }
        });
    };

    if ($('#form-RegNo').length > 0) {
        jQuery.validator.addMethod("regnr",
			function(value, element, params) {
			    return (/^\d{3,4}$/.test(value));
			}, 'Reg nr validation failed');

        $('#form-RegNo').bind('change focus blur', function() {
            if ($(this).val().length > 2) {
                $(this).val($(this).val().prelongate(4, 0));
            }
        }).rules('add', {
            regnr: true,
            messages: {
                regnr: "Indtast venligst tal p&#229; mellem 3 og 4  cifre"
            }
        });
    };

    jQuery.validator.addMethod("atleastonechb", function(value, element, params) {
        return $('input.atleastonechb:checked').length > 0;

    }, 'At least one health service must be selected.');

    $('input.atleastonechb').each(function() {
        $(this).rules('add', {
            atleastonechb: true,
            messages: {
                atleastonechb: 'Der skal v&#230;lges mindst et produkt.'
            }
        });
    });
    if (document.getElementById("applicationContent")) {
        App.subsidyApplication.init();
    }
});

var App = {
    subsidyApplication: {
        toggleUnknownFields: function() {
            $(".showExtras").each(function() {
                var checked = $(this).find('input:checked');

                if (checked.length == 1) {
                    var checkedId = "_tb" + checked.attr("id").split("_cb")[1],
					inputEle = $("input[id$=" + checkedId + "]");
                    inputEle.attr("disabled", "disabled");
                    $(this).next(".extraField").css("display", "block");
                }
            })
            $(".showExtras").click(function(e) {
                var ele = $(e.target),
					checker = ele.is(":checked"),
					inputId = "_tb" + $(e.target).attr("id").split("_cb")[1],
					inputEle = $("input[id$=" + inputId + "]");
                if (e.target.type == "checkbox" && checker === true) {
                    inputEle.attr("disabled", "disabled");
                    ele.parent().next(".extraField").css("display", "block");
                } else {
                    inputEle.attr("disabled", "");
                    ele.parent().next(".extraField").hide();
                }
            });
        },
        init: function() {
            $.datepicker.setDefaults($.datepicker.regional['da']);
            $(".datePicker").datepicker({ dateFormat: 'dd-mm-yy', firstDay: 1 });
            App.subsidyApplication.toggleUnknownFields();
        }
    }
}

