$(document).ready(function() {
    if($('#topform2').length > 0) {
        var current_state = $('#movingtostate').attr('value');
        /**
         * Load all zip codes once HTML is ready.
         */
        $.post('/assets/inc/transactions/', {allzips: "yes"}, function(data) {
            data = data.split(',');
            $('input[name=zip]').autocomplete(data);
        });
        if(current_state != '0') {
            /**
             * Initial AJAX call if state is already selected
             */
            $.post('/assets/inc/transactions/', {state:current_state}, function(data) {
                data = data.split(',');
                $('input[name=movingtocity]').autocomplete(data, {cacheLength:1});
            });
            /*$.post('/inc/transactions/', {state:current_state, zips: "yes"}, function(data) {
                data = data.split(',');
                $('input[name=zip]').autocomplete(data);
            });*/
        }
        $('#movingtostate').change(function() {
            var state = $(this).attr('value');
            if(state == 'DC') {
                $('input[name=movingtocity]').val('Washington');
            }
            current_state = state;
            /**
             * AJAX call to fill list of city names according to state
             * called when value of state dropdown changes
             */
            $.post('/assets/inc/transactions/', {state: state}, function(data) {
                data = data.split(',');
                $('input[name=movingtocity]').autocomplete(data, {cacheLength:1});
            });
            /*$.post('/inc/transactions/', {state: state, zips: "yes"}, function(data) {
                data = data.split(',');
                $('input[name=zip]').autocomplete(data);
            });*/
        });
        $('#topform2 label').each(function() {
            var error = $(this).find('.error').html();
            if(error) {
                $('#topform2').addClass('has-errors');
                $(this).wTooltip({
                    content: error,
                    style: false,
                    className: 'error-tip',
                    offsetY: 20,
                    offsetX: -20
                })
                $(this).addClass('has-error');
                $(this).append('<img src="/assets/images/exclamation.png" alt="error" />')
            }
        });
        /**
         * Begin Calendar Functionality
         * The "Calendar Button" is inserted with an inline script in the main body of the home page,
         * and has an id="date-pick".  The image is /images/calendar.png.  The following code is triggered
         * from a click event on the calendar button, which was previously inserted.
         */
        	// initialise the "Select date" link
	$('#date-pick').datePicker(
            // associate the link with a date picker
            {
                createButton:false,
                startDate: '01/' + this_month + '/' + this_year,// dd/mm/yyyy
                endDate: '31/12/' + next_year // dd/mm/yyyy
            }
            ).bind(
            // when the link is clicked display the date picker
            'click',
            function()
            {
                updateSelects($(this).dpGetSelected()[0]);
                $(this).dpDisplay();
                return false;
            }
            ).bind(
            // when a date is selected update the SELECTs
            'dateSelected',
            function(e, selectedDate, $td, state)
            {
                updateSelects(selectedDate);
            }
            ).bind(
            'dpClosed',
            function(e, selected)
            {
                updateSelects(selected[0]);
            }
            );

        var updateSelects = function (selectedDate)
        {
            selectedDate = new Date(selectedDate);
            var selectedMonth = (selectedDate.getMonth()+1);
            if(selectedMonth < 10) selectedMonth = '0' + selectedMonth;
            var selectedDay = selectedDate.getDate();
            if(selectedDay < 10) selectedDay = '0' + selectedDay;
            $('#moveday option[value=' + selectedDay + ']').attr('selected', 'selected');
            $('#movemonth option[value=' + selectedMonth + ']').attr('selected', 'selected');
            $('#moveyear option[value=' + (selectedDate.getFullYear()) + ']').attr('selected', 'selected');
        }
        // listen for when the selects are changed and update the picker
        $('#moveday, #movemonth, #moveyear')
        .bind(
            'change',
            function()
            {
                /*var d = new Date(
                    $('#moveday').val(),
                    $('#movemonth').val(),
                    $('#moveyear').val()
                );*/
                var dString = $('#moveday').val() + '/' + $('#movemonth').val() +  '/' + $('#moveyear').val();
                $('#date-pick').dpSetSelected(dString);
            }
            );

        // default the position of the selects to today
        var today = new Date();
        updateSelects(today.getTime());

        // and update the datePicker to reflect it...
        $('#moveday').trigger('change');
    }
});
