$(function () {

    // Show IE6 upgrade recommendation
    if ($.browser.msie && parseInt($.browser.version) <= 6) {
        $('body').append($(document.createElement('div')).attr('id', 'ie6-alert').html('Du har en eldre versjon av Internet Explorer. For best mulig opplevelse av dette nettstedet, anbefaler vi at du <a href="http://www.microsoft.com/Windows/internet-explorer/">oppdaterer til siste versjon</a>.').fadeIn(500).fadeOut(500).fadeIn(500));
    }
    
    // Functionality which require IE7+ or other
    if (!($.browser.msie && parseInt($.browser.version) <= 6)) {
        // IE6 does not support chained classes
        $(':input').torForms();
    }
    
    // Custom functions which triggers change event on form elements
    $.fn.disable = function () {
        return $(this).attr('disabled', 'disabled').change();
    }
    
    $.fn.enable = function () {
        return $(this).removeAttr('disabled').change();
    }
    
    $.fn.check = function () {
        return $(this).attr('checked', 'checked').change();
    }
    
    $.fn.uncheck = function () {
        return $(this).removeAttr('checked').change();
    }
    
    // Open external links in new window
    $('a[rel~=external]').click(function (e) {
        window.open(this.href);
        e.preventDefault();
    });
    
    // Submits form on submit button click
    $('form .button.submit').click(function (event) {
        $(this).closest('form').submit();
        event.preventDefault();
    });
    
    // Positions the main menu current indicator
    if ($('#main-menu li.current').length > 0) {
        var mainMenuCurrentBackgroundWidth = 197;
        var currentMenuItemPosition = $('#main-menu li.current:first').position();
        var currentMenuItemWidth = $('#main-menu li.current:first').width();
        var newLeft = (currentMenuItemPosition.left + (currentMenuItemWidth / 2)) - (mainMenuCurrentBackgroundWidth / 2);
        $('#main-menu').css('background-position', newLeft + 'px 25px');
    } else {
        $('#main-menu').css('background', 'none');
    }
    
    // Enables product list hovering
    $('#product-list li').hover(
        function () {
            $(this).addClass('hover');
        },
        function () {
            $(this).removeClass('hover');
        }
    );
    
    // Toggle faq answers
    $('#faq h3 a').click(function(e) {
        $(this).hasClass('active') ? $(this).removeClass('active') : $(this).addClass('active');
        $(this).parent().siblings('.answer').toggle();
        e.preventDefault();
    });
    
    $('#faq .related.faq').click(function (e) {
        $('#' + $(this).attr('rel') + ' .answer').toggle();
    });
    
    // Prevent user from selecting more than # of friends
    $('#fb-invite-list :checkbox').live('click', function(e) {
        if ($(this).closest('ul').find(':checked').length > 14) {
            alert('Du kan ikke velge flere enn 14 personer');
            e.preventDefault();
        }
    });
    
    
    
    // Override selection
    
    
    if ($('#planner .special-override').is(':checked')) {
        $('#planner .special-override').closest('ul').find(':checkbox:not(.special-override)').uncheck().disable();
    }
    
    
    $('#planner .special-override').click(function (e) {
        if ($(this).find(':checkbox').is(':checked')) {
            $(this).closest('ul').find(':checkbox:not(.special-override)').uncheck().disable();
        } else {
            $(this).closest('ul').find(':checkbox').enable();
        }
    });
    
    // Validator error messages
    jQuery.validator.messages.required = 'Påkrevd';
    jQuery.validator.messages.email = 'Ugyldig epost';
    
    // Planner step 1 form validation
    $('#planner #step1').validate({
        submitHandler: function (form) {
            //$('#step-1-values').val($('#step1').serialize());
            if ($(form).attr('action') == '#') {
                $('#step1 :input').each(function () {
                    if ($(this).is(':checked')) {
                        //$('#step2').append($(this).attr('name',($(this).attr('name') == 'planner-food[]' || $(this).attr('name') == 'planner-hectical[]' ? $(this).attr('value') : $(this).attr('name'))).hide());
                        // replaces form names and values for planner-food and planner-hectical (for update)
                        //$('#step2 .step1-values').append($(this).attr('name', ($(this).hasClass('planner-food') || $(this).hasClass('planner-hectical') ? $(this).attr('value') : $(this).attr('name'))).val(($(this).hasClass('planner-food') || $(this).hasClass('planner-hectical') ? 'true' : $(this).val())).hide());
                        
                        /*var newElement = $(this);
                        if (newElement.hasClass('planner-food') || newElement.hasClass('planner-hectical')) {
                        	var currentValue = newElement.attr('value');
                        	newElement.attr('name', currentValue);
                        	newElement.attr('value', 'true');
                        	
                        }
                        */
                        
                        
                        var newElement = $(document.createElement('input'));
                        
                        if ($(this).is(':checkbox')) {
                        	newElement.attr('type', 'checkbox');
                        }
                        else {
                        	newElement.attr('type', 'radio');
                        }
                        
                        if ($(this).hasClass('planner-food') || $(this).hasClass('planner-hectical')) {
                        	newElement.attr('name', $(this).attr('value'));
                        	newElement.attr('value', 'true');
                        }
                        else {
                        	newElement.attr('name', $(this).attr('name'));
                        	newElement.attr('value', $(this).val());
                        }
                        $('#step2 .step1-values').append(newElement.hide());
                        
                        //$('#step2 .step1-values').append($(this));
                        //$('#step2 .step1-values').append($(this).attr('name', $(this).hasClass('planner-food') || $(this).hasClass('planner-hectical') ? $(this).attr('value') : $(this).attr('name')).hide());
                        
                        newElement = $('#step2 .step1-values :input:last');
                        newElement.attr('checked', 'checked');
                        /*
                        if (newElement.hasClass('planner-food') || newElement.hasClass('planner-hectical')) {
                        	//var currentValue = newElement.attr('value');
                        	//newElement.attr('name', 'test');
                        	newElement.attr('name', newElement.val());
                        	newElement.attr('value', 'true');
                        	//newElement.attr('value', 'true');
                        	newElement.checked = true;
                        	
                        }
                        */
                        
                    }
                });
                $('#step1').hide();
                $('#step2').show();    
            }
            else {
                form.submit();
            }
        },
        invalidHandler: function (e, validator) {
            $('#step1 li.error').remove();
        },
        errorPlacement: function (error, element) {
            element.closest('ul').prepend('<li class="error">' + error.text() + '</li>');
        }
    });
    
    // Planner step 2 form validation
    //$('#planner #step2').validate();
    
    $('#planner #step2').validate({
        submitHandler: function (form) {
            form.submit();
        },
        highlight: function(element, errorClass) {
            $(element).closest('div').addClass(errorClass);
        },
        unhighlight: function(element, errorClass) {
            $(element).closest('div').removeClass(errorClass);
        },
        errorPlacement: function (error, element) {
            // no error message
        }
    });
    
    
    // Facebook friend list next/prev selection
    $('#fb-invite-list .next, #fb-invite-list .prev').click(function (event) {
        var prevButton = $('#fb-invite-list .prev');
        var nextButton = $('#fb-invite-list .next');
        var current = $('#fb-invite-list .item.current');
        current.removeClass('current');
        
        if ($(this).hasClass('next')) {
            var newCurrent = current.eq(-1).nextAll('.item:lt(15)');
        } else {
            var newCurrent = current.eq(0).prevAll('.item:lt(15)');
        }
        newCurrent.addClass('current');
        
        newCurrent.eq(-1).hasClass('first') ? prevButton.hide() : prevButton.show();
        newCurrent.eq(-1).hasClass('last') ? nextButton.hide() : nextButton.show();
        
        event.preventDefault();
    });
    
});
