var numRows = 0;
var callback = null;

$(document).ready(function() {

    $('#searchbar').data('baseurl', 'http://www.provu.co.uk/');

    $('#instructions').hide();

    var instructions = function(firstload) {
        if (firstload != 1) {
            return;
        }
        $.fancybox(
            $('#instructions').html(),
            {
                'autoDimensions'	: true,
                /*'width'         	: 'auto',
                'height'        	: 'auto',*/
                'transitionIn'	: 'none',
                'transitionOut'	: 'none'
            }
    )};

    // Show instructions on page load
    instructions(firstload);

    $('#intro').append(' It is also useful to familiarise yourself with the <a href="#instructions">instructions</a>.');
    $('a[href=#instructions]').click(function(event) {
        instructions(true);
        event.preventDefault();
    });


    numRows = $('#NumRows').val();

    applyFancybox = function() {
        $('.fancybox').fancybox({
            'width'		: '90%',
            'height'	: '90%',
            'autoScale'	: true,
            'transitionIn'	: 'elastic',
            'transitionOut'	: 'elastic',
            'type'		: 'iframe',
            'onStart': function (links, index) {
                self = $(links[index]);
                if (self.attr('trigger')) self.trigger(self.attr('trigger'));
            }
        });
    };
    applyFancybox();

    $('#rma-container form').submit(function() {
        if (numRows == 0) {
            alert('No RMAs to process.');
        }

        $('#NumRows').val(numRows);

        var error = false;
        var focused = false;

        $('#details :input').each(function() {
            if ( $.trim($(this).val()) == '' ) {
                $(this).addClass('error');

                if (!focused) {
                    focused = true;
                    $(this).focus();
                }

                error = true;
            } else {
                $(this).removeClass('error');
            }
        });

        // Validate each RMA line
        $('#rma-lines div').each(function() {
            $(':input', $(this)).each(function() {
                if ($(this).attr('type') == 'radio') {
                    return;
                }
                //var name = $(this).attr('name').replace(/(.*)\[\d+\]/, "$1");

                if ( $.trim($(this).val()) == '' ) {
                    $(this).addClass('error');

                    if (!focused) {
                        focused = true;
                        $(this).focus();
                    }

                    error = true;
                } else {
                    $(this).removeClass('error');
                }
            });
        });

        if ($('input[name=agree]:checked').length == 0) {
            $('#agreeError').text('You must first read and agree to the Returns Policy.').addClass('error').fadeIn('slow');
            error = true;
        } else {
            $('#agreeError').fadeOut('fast');
        }

        if (error) {
            return false;
        } else {
            // could do ajax post in future
            return true;
        }

        return false;
    });



    $('#less-rows').remove();

    $('#more-rows').click(function (event) {

        var $newRow = $('#rma-lines div:nth-child(1)');

        if ($newRow.length == 0) {
            return false;
        }

        var rowText = $newRow.html().replace(/0/g, numRows);
        var $row = $('<div/>').addClass('hidden').html(rowText);

        $('.trash', $row).removeClass('hidden');

        $('ul:last', $row).remove(); // remove error list
        $(':input', $row).removeClass('error');

        $(':text', $row).val('');
        $('textarea', $row).val('');

        $(':input', $row)
            .removeAttr('checked')
            .removeAttr('selected');

        $(':radio:eq(0)', $row).attr('checked', 'checked');

        $('a[href="serial.html"]', $row).attr('trigger', 'click.serial');

        $row.appendTo('#rma-lines').slideDown('slow');
        applyFancybox();

        $('html,body').animate({scrollTop: $(this).offset().top}, {duration: 'slow', easing: 'swing'});

        numRows++;

        event.preventDefault();
        return false;
    });



    $('#rma-lines div').each(function(i) {
        $(this).prepend('<a class="trash" rel="'+i+'"><img src="imgs/delete_icon.gif" alt="delete this row"/></a>');
    });


    $('.trash').live('click', function(event) {
        var item = $(this).attr('rel');
        $(this).parent().slideUp('slow', function () {
            if (item != 0) {
                $(this).remove();
            }

            numRows--;
        });

        event.preventDefault();
    }).first().addClass('hidden');


    $('a[href="serial.html"]').live('click.serial', function() {
        $input = $(this).siblings(':input');

        callback = function() {
            $input.val('NOSERIAL');
            $.fancybox.close();
        };
    }).attr('trigger', 'click.serial');

});
