$(function () {
    
    $('#proceedButton').click(function (event) {
        $('#checkOutForm').submit();
        event.preventDefault();
    });
    
    
    $('.button.remove').click(function(event) {
        $(this).closest('.cartItem').remove();
        
        //$.get($(this).attr('href'), {count: $('.cartItem').length});
        
        //if ($('.cartItem').length > 0) {
          //  event.preventDefault();
        //} 
        
    });
    
    
    $('.sendAllToSelf').click(function (event) {
        $('input[name=recipient_name[]]').val($('#customerName').val() + ' ' + $('#customerSurname').val());
        $('input[name=recipient_address[]]').val($('#customerAddress').val());
        $('input[name=recipient_postal_code[]]').val($('#customerPostalCode').val());
        $('input[name=recipient_postal_city[]]').val($('#customerPostalCity').val());
        $('input[name=recipient_email[]]').val($('#customerEmail').val());
        event.preventDefault();
    });
    
    $('.sendToSelf').click(function (event) {
        $(this).closest('fieldset').find('input[name=recipient_name[]]').val($('#customerName').val() + ' ' + $('#customerSurname').val());
        $(this).closest('fieldset').find('input[name=recipient_address[]]').val($('#customerAddress').val());
        $(this).closest('fieldset').find('input[name=recipient_postal_code[]]').val($('#customerPostalCode').val());
        $(this).closest('fieldset').find('input[name=recipient_postal_city[]]').val($('#customerPostalCity').val());
        $(this).closest('fieldset').find('input[name=recipient_email[]]').val($('#customerEmail').val());
        event.preventDefault();
    });
    
    // Disable error messages
    jQuery.validator.messages.required = '';
    jQuery.validator.messages.email = '';
    jQuery.validator.messages.digits = '';
    jQuery.validator.messages.rangelength = '';
    
    $.validator.addMethod("noSpecialChars", function(value, element) {
	      return this.optional(element) || /^[a-z0-9æøå \_\-.,\?!]+$/i.test(value);	      
	  }, 'Spesialtegn ikke tillatt');
    
    
    $('#checkOutForm').validate({
        rules: {
            postnr: {
                rangelength:[4, 4]
            }
        },
        invalidHandler: function (e, validator) {
            var errors = validator.numberOfInvalids();
            if (errors) {
                var message = 'Ooops! Det ser ut som noe mangler eller er fylt ut feil. Ta en titt og prøv igjen';
                $('#formErrorMessage').html(message).show();
            } else {
                $('#formErrorMessage').hide();
            }
        },
        submitHandler: function (form) {
            
            $("#formErrorMessage").hide();
            
            if ($(form).hasClass('step1')) {
                $('#checkOutForm').addClass('step2').removeClass('step1');
                $('h1').text('2. Oppsummering');
                // Update the progress bar
                $('#checkOutProgress li').removeClass('active');
                $('#checkOutProgress li:eq(1)').addClass('active');
                // Disable the input fields
                $('#checkOutForm input:not([name=edit[]])').attr('disabled', 'disabled');
                $('#checkOutForm textarea').attr('disabled', 'disabled');
                // Hide empty textareas
                $('#checkOutForm textarea').each(function () {
                    if ($(this).val() == '') {
                        $(this).parent().hide();
                    }
                });
                $('#proceedButton span').text('Gå til betaling');
            } else {
                // The input fields need to be enabled before POST
                $('#checkOutForm input, #checkOutForm textarea').removeAttr('disabled');
                
                numOfOrderLines = $('[name=recipient_name[]]').length;
                
                orderString = '';
                for (i = 0; i < numOfOrderLines; i++) {
                    
                    projectNum = $('[name=project_num[]]')[i].value;
                    productType = $('[name=product_type[]]')[i].value;
                    productVariant = $('[name=product_variant[]]')[i].value;
                    productPrice = $('[name=product_price[]]')[i].value;
                    
                    recipientName = $('[name=recipient_name[]]')[i].value;
                    recipientName = recipientName.replace(/[:\;]/g,'');
                    
                    recipientEmail = $('[name=recipient_email[]]')[i].value.length != 0 ? $('[name=recipient_email[]]')[i].value : '999';
                    
                    recipientAddress = $('[name=recipient_address[]]')[i].value;
                    recipientAddress = recipientAddress.replace(/[:\;]/g,'');
                    
                    recipientPostalCode = $('[name=recipient_postal_code[]]')[i].value;
                    
                    recipientPostalCity = $('[name=recipient_postal_city[]]')[i].value;
                    recipientPostalCity = recipientPostalCity.replace(/[:\;]/g,'');
                    
                    recipient = new Array(recipientName, recipientAddress, recipientPostalCode, recipientPostalCity).join(' ');
                    
                    comment = $('[name=recipient_message[]]')[i].value;
                    comment = comment.replace(/[:\;]/g,'');
                    
                    orderString += new Array(productPrice, productType, projectNum, productVariant, recipient, comment, recipientEmail).join(';');
                    
                    if (i < (numOfOrderLines - 1)) {
                        orderString += '|';
                    }
                }
                
                $('#orderString').val(orderString);
                
                // Cookie for plugin
                var today = new Date();
                var expiry = new Date(today.getTime() + 365 * 24 * 60 * 60 * 1000);
                var identifier = 'shopidentifier=' + (1234567890 + Math.floor(Math.random()*10000+1));
                identifier += ';expires=' + expiry.toGMTString() + ';path=/';
                document.cookie = identifier;
                var shopdata = 'shopdata=' + encodeURIComponent($('[name=kjop]').val());
                shopdata += ';expires=' + expiry.toGMTString() + ';path=/';
                document.cookie = shopdata;
                var customeremail = 'shopcustomeremail=' + encodeURIComponent($('[name=customer_email]').val());
                customeremail += ';expires=' + expiry.toGMTString() + ';path=/';
                document.cookie = customeremail;
                var customername = 'shopcustomername=' + encodeURIComponent($('[name=fornavn]').val() + ' ' + $('[name=etternavn]').val());
                customername += ';expires=' + expiry.toGMTString() + ';path=/';
                document.cookie = customername;
                
               form.submit();
            }
        }
    });
    
    $('.edit').click(function (event) {
        $('#checkOutForm').addClass('step1').removeClass('step2');
        $('h1').text('1. Utsendelsesdetaljer');
        // Update the progress bar
        $('#checkOutProgress li').removeClass('active');
        $('#checkOutProgress li:eq(0)').addClass('active');
        // Enable the input fields
        $('#checkOutForm input, #checkOutForm textarea').removeAttr('disabled');
        //$('#checkOutForm textarea').removeAttr('disabled');
        $('#checkOutForm fieldset').show();
        $('#proceedButton span').text('Gå til oppsummering');
        event.preventDefault();
    });
});
