// Function to add keyboard navigation
function add_keyboard_navigation() {
    $('#nav a').focus( function() {
        $(this).parents('li').addClass('hover');
    });
    $('#nav a').blur( function() {
        $(this).parents('li').removeClass('hover');
    });
}

// Function to add form placeholders (assumes one input and one label per .field)
function add_form_placeholders(s) {
    var f = $( s + ' input[type="text"]' );
    var p = $( s + ' input[type="password"]' );
    var l = $( s + ' label' );
    var c = 'placeholder';
    var w = 'Password';
    f.each( function() {
        var t = $(this).siblings('label').first().text();
        $(this).addClass(c);
        $(this).val(t);
        $(this).focus( function() {
            $(this).removeClass(c);
            if( $(this).val() === t ) {
                $(this).val('');
            }
        });
        $(this).blur( function() {
            if( $(this).val() === '' || $(this).val() === t ) {
                $(this).val(t);
                $(this).addClass(c);
            }
        });
    });
    p.each( function() {
        $(this).after( '<input type="text" value="' + w + '" class="' + c + '" />' );
        var pt = $(this).parent();
        var wd = $(this);
        var tx = pt.find('input[type="text"]');
        wd.hide();
        tx.focus( function() {
            tx.hide();
            wd.show();
            wd.focus();
        });
        wd.blur( function() {
            if( wd.val() === '' ) {
                wd.hide();
                tx.show();
            }
        });
    });
    l.hide();
}

// Function to add tab navigation
function add_tab_navigation() {
    var s = $('.tabbed #main .section');
    if( s.length > 0 ) {
        var c = 'active';
        var a = $('#tabnav a');
        s.first().nextAll().hide();
        a.first().addClass(c);
        a.css({
            'position': 'relative',
            'z-index': '10'
        });
        a.click( function(e) {
            var h = $(this).attr('href');
            var y = $('#main').css('height'); // height adjust
            $('#main').css( 'height', y ); // height adjust
            s.css({
                'position': 'absolute',
                'width': '657px'
            });
            s.filter(':visible').fadeOut();
            $(h).fadeIn( '', function() {
                s.css({
                    'position': 'static'
                });
                $('#main').css( 'height', 'auto' ); // height adjust
            });
            a.removeClass(c);
            $(this).addClass(c);
            e.preventDefault();
        });
    }
}

// Function to add home page banner cycle
function add_cycle() {
    var b = $('#home-banner');
    if( b.length > 0 ) {
        b.cycle();
    }
}

// Function to add plan lightbox
function add_plan_effect() {
    if( $('#virtual-tour-plan').length > 0 ) {
        $('#virtual-tour-plan').fancybox({
            'type': 'iframe',
            'width': 1050,
            'height': 1150
        });
    }
}

// Function to add map
function add_map() {
    var f = $('#contact-col-right');
    if( f.length > 0 ) {
        var c = $('<div id="contact-map"></div>');
        f.prepend(c);
        var l = new google.maps.LatLng( 53.9541448, -1.1040237 );
        var o = {
            zoom: 14,
            center: l,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var m = new google.maps.Map( document.getElementById('contact-map'), o );
        var k = new google.maps.Marker({
            position: l,
            title: 'Melton College'
        });
        k.setMap(m);
    }
}

// Function to add form error message
function add_error_message(m) {
    var e = $('#form-error');
    var f = $('#form-reminder');
    if( m === '' ) {
        e.remove();
        f.remove();
        $('label').removeClass('error');
    } else {
        if( e.length > 0 ) {
            e.text(m);
        } else {
            var p = $('<p class="error" id="form-error">' + m + '</p>');
            $('#error-placeholder').after(p);
            if( $('#form-reminder').length === 0 ) {
                var r = $('<p class="error" id="form-reminder">Some required fields are empty. Please check above for details.</p>');
                $('#error-reminder').after(r);
            }
        }
    }
}

// Function to validate form
function validate_form() {

    // Variables
    var e = [];
    var c = $('form input[type="text"], form textarea');

    // Validation
    c.each( function() {

        // Check non-empty
        if( $(this).hasClass('required') && $(this).val() === '' ) {
            e.push( $(this).siblings('input[type="hidden"].validation').first().val() );
            $(this).siblings('label').addClass('error');

        // Check valid number (including min and max values)
        } else if( $(this).hasClass('number') ) {
            if(
                ( isNaN( $(this).val() ) ) ||
                ( $(this).data('min') && $(this).val() < $(this).data('min') ) ||
                ( $(this).data('max') && $(this).val() > $(this).data('max') )
            ) {
                e.push( 'a valid ' + $(this).siblings('label').eq(0).text() );
                $(this).siblings('label').addClass('error');
            }

        // Check valid email
        } else if( $(this).hasClass('email') ) {
            var f = /^[^@]+@[^@.]+\.[^@]*\w\w$/;
            var a = /[\(\)<\>\,\;\:\\\"\[\]]/;
            if( (!f.test( $(this).val() )) || $(this).val().match(a) ) {
                e.push( 'a valid email address' );
                $(this).siblings('label').addClass('error');
            } else {
                $(this).siblings('label').removeClass('error');
            }

        // If is valid
        } else {
            $(this).siblings('label').removeClass('error');
        }

    });

    // If errors, write error message
    if( e.length > 0 ) {
        var m = 'Please enter ';
        m += e[0];
        if( e.length > 1 ) {
            if( e.length > 2 ) {
                for( var i = 1; i < ( e.length - 1 ); i++ ) {
                    m += ', ';
                    m += e[i];
                }
            }
            m += ' and ';
            m += e[e.length-1];
        }
        m += '.';
        add_error_message(m);
        return false;

    // If no validation errors, check age of applicant
    } else {
        var dat = $('#dob_day').val() + ' ' + $('#dob_month').val() + ' ' + $('#dob_year').val();
        var lim = $('#age-limit').val();
        var now = new Date();
        var thn = Date.parse(dat);
        if( now.getTime() - thn < ( lim * 31556926000 ) ) {
            add_error_message( 'You must be at least ' + lim + ' years old to apply' );
            return false;
        }
    }

}

// Function to validate checkbox input
function add_checkbox_validation() {
    var c = $('.confirm form input[type="checkbox"]');
    if( c.length > 0 ) {
        $('form').submit( function() {
            if( !c.is(':checked') ) {
                add_error_message('You must accept the terms and conditions before submitting your application form');
                return false;
            }
        });
        $('form').bind( 'reset', function() {
            add_error_message('');
        });
    }
}

// Function to add validation
function add_validation(s) {
    var f = $(s);
    if( f.length > 0 ) {
        f.submit( function() {
            return validate_form();
        });
        f.bind( 'reset', function() {
            add_error_message('');
        });
    }
}

// Function to add FAQ show/hide effect
function add_faq_show_hide() {
    var dt = $('.faq-list dt');
    if( dt.length > 0 ) {
        // hide individual answers
        $('.faq-list dd').hide();
        dt.each( function(i) {
            var txt = $(this).html();
            $(this).html( '<a href="#">' + txt + '</a>' );
            $(this).find('a').click( function(e) {
                $( 'dd:eq(' + i + ')' ).slideToggle( 200 );
                $(this).blur();
                e.preventDefault();
            });
        });
        // hide full sections
        var titles = $('.faq-title');
        $('.faq-list').hide();
        titles.each( function(j) {
            var txt = $(this).html();
            $(this).html( '<a href="#" class="inactive">' + txt + '</a>' );
            $(this).find('a').click( function(e) {
                $( '.faq-list:eq(' + j + ')' ).slideToggle( 200 );
                $( '.faq-list:eq(' + j + ') dd' ).hide();
                $(this).toggleClass('active inactive');
                $(this).blur();
                e.preventDefault();
            });
        });
    }
}

// Function to add gallery lightbox
function add_gallery_box() {
    var gallery = $('.gallery a');
    if( gallery.length > 0 ) {
        gallery.fancybox({
            'titlePosition': 'over'
        });
    }
}

function add_fancybox() {
	$('a.fancybox').fancybox({
		'titlePosition': 'over'
	});
}

// Function to check available dates
function add_date_check() {
    var app = $('#application-form');
    if(app.length > 0) {
        var courses = $('#course');
        var dates = $('#coursedates');
        var options = [];
        var check_dates = function() {
            dates.empty();
            for(var i = 0; i < options.length; i++) {
                if(courses.find('option:selected').val() === options[i].course) {
                    var elem = $('<option>');
                    elem.text(options[i].text);
                    elem.val(options[i].value);
                    dates.append(elem);
                }
            }
        };
        dates.find('option').each(function() {
            options.push({
                'text': $(this).text(),
                'value': $(this).val(),
                'course': $(this).data('course')
            });
        });
        courses.change(check_dates);
        check_dates();
    }
}

// Functions to run on load
$(document).ready( function() {
	add_fancybox();
    add_keyboard_navigation();
    add_tab_navigation();
    add_form_placeholders('#aside form');
    add_cycle();
    add_plan_effect();
    add_map();
    add_validation('#application-form');
    add_validation('#contact-form');
    add_checkbox_validation();
    add_faq_show_hide();
    add_gallery_box();
    add_date_check();
});

