jQuery(function () {
    //$(document).ready(function(){

    /*global window */
    /*global $ */

    var hn = window.location.hostname;
    var schoolResults = new Array();
    var site = "";
    if (hn === "steve-pc") {
        site = "http://steve-pc/wordpress/wp-content/themes/Function_pdd/";
    }else {
        site = "http://www.discoverlabskills.org/wp-content/themes/Function_pdd/";
    }
    $('#formRegistrationDetails :text').each(function () {
        $(this).val('');
    });
    $("#cbRegNewschool").attr('checked', false);

    $('.rnded').corner();

    $("#formRegistrationDetails").submit(function () {return false;}); //disables hit return and submit...on some browsers!
    $("#formLS").submit(function(){return false;}); //disables hit return and submit...on some browsers!
    $('#fieldsSchool :text').attr('disabled',true);
    var v = $('#formRegistrationDetails').validate({

        rules: {
            first_name: {
                required: true
            },
            last_name: {
                required: true

            },
            position: {
                required: true
            },
            email: {
                required: true,
                email: true
            },
            email2: {
                required: true,
                email: true,
                equalTo: "#email"
            }
        },//endrules
        messages: {
            first_name: {
                required: "Please enter your first name"
            },

            last_name: {
                required: "Please enter your last name"

            },
            position: "Please enter your position at the school",
            email: {
                required: "Please enter your email address",
                email: "Please enter a valid email address"
            },
            email2: {
                required: "Please confirm your email address",
                equalTo: "Your email address does not match"
            }

        }

    });

    $("#searchResultTable")
        .tablesorter({widthFixed: true, widgets: ['zebra']})
        .tablesorterPager({container: $("#divPager")});

    $('#buttonRegNewschool').click(function () {
        var params = $('#formRegistrationDetails :input');
        params = params.serialize();

        if (v.form()) {
            $.getJSON(site + "newschool.php", params, processRequested);
        }
    });

    $("#cbRegNewschool").click(function () {

        // If checked
        if ($("#cbRegNewschool").is(":checked"))
        {
            if ($('#divLiveSearch').is(':visible')) {
                $('#divLiveSearch').fadeOut();
            }
            if ($('#divLSBox').is(':visible')) {
                $('#divLSBox').slideUp('fast');
            }


            if ($('#divForms').is(':hidden')){
                $('#divForms').fadeIn();
            }
            if ($('#divFormHelp').is(':visible')){
                $('#divFormHelp').fadeOut();
            }
            if ($('#divHelpBoxes').is(':visible')){
                $('#divHelpBoxes').fadeOut();
            }
            $('#fieldsSchool legend').html('Register this school');
            if ($('#divSearchResult').is(':visible')){
                $('#divSearchResult').fadeOut();
            }
            $('#fieldsSchool :text').each(function(){
                $(this).attr('disabled',false);
            });

            $('#buttonRegNewschool').css('display','inline');


            if ($('#registerButton').is(':visible')){
                $('#registerButton').hide();
            }
            $('#formRegistrationDetails :input').each(function(){
                this.val="";
            })

            if ($('#fieldsRegistered').is(':visible')){
                $('#fieldsRegistered').hide();
            }

            if ($('#fieldsPersonal').is(':hidden')){
                $('#fieldsPersonal').show();
            }
            $('#formRegistrationDetails :text').each(function () {
                $(this).val('');
            });

            if ($('#divNewschoolhelp').is(':hidden')){
                $('#divNewschoolhelp').show();
            }

        }
        else
        {
            if ($('#divHelpBoxes').is(':hidden')){
                $('#divHelpBoxes').fadeIn();
            }
            if ($('#divNewschoolhelp').is(':visible')){
                $('#divNewschoolhelp').hide();
            }
            $('#fieldsSchool legend').html('Register for this school');

            if ($('#divLiveSearch').is(':visible')){
                $('#divLiveSearch').fadeOut();
            }

            if ($('#divForms').is(':visible')){
                $('#divForms').fadeOut();
            }
            if ($('#divLSBox').is(':hidden')){
                $('#divLSBox').fadeIn();
            }

            $('#fieldsSchool :text').each(function () {
                $(this).attr('disabled',true);
            });

            if ($('#registerButton').is(':hidden')){
                $('#registerButton').show();
            }
        }
    });

    function processData(data){

        var schoolTable = "";
        var regstatus = "";



        $('#buttonRegNewschool').css('display','none');

        if (data === null) {

            $('#formRegistrationDetails :text').each(function () {
                $(this).val('');
            });

            if ($('#divForms').is(":visible")) {
                $('#divForms').fadeOut();
            }
            if ($('#divFormHelp').is(":visible")) {
                $('#divFormHelp').fadeOut();
            }

            if ($('#divSearchResult').is(":hidden")) {
                $('#divSearchResult').fadeOut();
            }
            if ($('#divResultTable').is(":hidden")) {
                $('#divResultTable').fadeOut();
            }
            if ($('#divPager').is(":hidden")) {
                $('#divPager').fadeOut();
            }

            schoolTable += "<tr class=\"school_name\" id=\"\">"
            schoolTable += "<td class=\"school_name\">Not Found</td>";
            schoolTable += "<td class=\"school_postcode\"></td>";
            schoolTable += "<td class=\"school_county\"></td>";
            schoolTable += "</tr>";

        }else{
            if ($('#divFormHelp').is(':hidden')) {
                $('#divFormHelp').fadeIn();
            }
            if ($('#divForms').is(':visible')) {
                $('#divForms').fadeOut();
            }

            if ($('#divSearchResult').is(":hidden")) {
                $('#divSearchResult').fadeIn();
            }
            if ($('#divResultTable').is(":hidden")) {
                $('#divResultTable').fadeIn();
            }
            if ($('#divPager').is(":hidden")) {
                $('#divPager').fadeIn();
            }

            $.each(data, function(i,school){
                for(var key in school){
                    if (school[key]==null){
                        school[key]="";
                    }
                }
                schoolResults[school.urn] = school;

                if (school.registered == true) {
                    regstatus="schoolRegisteredClass"
                }else {
                    regstatus="";
                }

                schoolTable += "<tr class=\"school_row \" id=\""+school.urn+"\">";
                schoolTable += "<td class=\"school_name "+regstatus+"\" >"+school.establishment_name+"</td>";
                schoolTable += "<td class=\"school_postcode "+regstatus+"\">"+school.postcode+"</td>";
                schoolTable += "<td class=\"school_county "+regstatus+"\">"+school.county+"</td>";
                schoolTable += "</tr>";
            });
        };

        $('#buttonRegNewschool').css('display', 'none');

        $('#searchResultTable tbody').html(schoolTable);
        setSchoolRows();
        $('#fieldsSchool :text').each(function () {
            $(this).attr('disabled', true);
        });


        $("#searchResultTable").trigger("update");
        $("#searchResultTable").trigger("appendCache");
        if ($('#buttonRegNewschool').is(":visible")) {
            $('#buttonRegNewschool').fadeOut();
        }

    };

    function setSchoolRows() {

        $('.school_row').hover(
            function () {
                $(this).find('td').addClass('hoverClass');
            },
            function () {
                $(this).find('td').removeClass('hoverClass');
            }
        );



        $('.school_row').click(function (event) {

            var school = schoolResults[event.target.parentNode.id];
            v.resetForm();

            if ($('#buttonRegNewschool').is(":visible")){
                $('#buttonRegNewschool').fadeOut();
            }
            if ($('#divForms').is(":hidden")){
                $('#divForms').fadeIn();
            }
            if ($('#divFormHelp').is(':visible')){
                $('#divFormHelp').hide();
            }

            $('#formRegistrationDetails :input[name=establishment_name]').val(school.establishment_name);
            $('#formRegistrationDetails :input[name=street]').val(school.street);
            $('#formRegistrationDetails :input[name=address_3]').val(school.address_3);
            $('#formRegistrationDetails :input[name=town]').val(school.town);
            $('#formRegistrationDetails :input[name=locality]').val(school.locality);
            $('#formRegistrationDetails :input[name=county]').val(school.county);
            $('#formRegistrationDetails :input[name=postcode]').val(school.postcode);
            $('#formRegistrationDetails :input[name=urn]').val(school.urn);

            $('#formRegistrationDetails :input[name=registered_initials]').val(school.initials);
            $('#formRegistrationDetails :input[name=regdate]').val(school.regdate);
            $('#formRegistrationDetails :input[name=regposition]').val(school.regposition);
            $('#formRegistrationDetails :input[name=confdate]').val(school.confdate);
            $('#fieldsSchool :text').each(function () {
                if ($(this).val()=='') {
                    $(this).parent().hide();

                }else {
                    $(this).parent().show();
                }

            });

            $('#fieldsSchool').removeClass('registered');
            $('#fieldsSchool').removeClass('selected');

            if (school.registered === true) {


                //$(this).find('td').removeClass('hoverClass');
                $('#searchResultTable').find('td').removeClass('schoolSelectedClass');
                //$('#searchResultTable').find('td').removeClass('schoolRegisteredClass');
                //$(this).find('td').addClass('schoolRegisteredClass');

                $('#fieldsSchool').addClass('registered');

                if ($('#fieldsPersonal').is(":visible")) {
                    $('#fieldsPersonal').fadeOut();
                }

                if ($('#fieldsRegistered').is(":hidden")) {
                    $('#fieldsRegistered').fadeIn();
                }

                if ($('#message').is(":visible")) {
                    $('#message').slideUp();
                }

            }else {
                $('#fieldsSchool').addClass('selected');

                $(this).find('td').removeClass('hoverClass');
                $('#searchResultTable').find('td').removeClass('schoolSelectedClass');
                //$('#searchResultTable').find('td').removeClass('schoolRegisteredClass');
                $(this).find('td').addClass('schoolSelectedClass');

                if ($('#fieldsPersonal').is(":hidden")) {
                    $('#fieldsPersonal').fadeIn();
                }
                if ($('#fieldsRegistered').is(":visible")) {
                    $('#fieldsRegistered').fadeOut();
                }

            }

        });

    };

    $('#registerButton').click(function () {
        var params = $('#formRegistrationDetails :input');
        params = params.serialize();

        if (v.form()) {
            $.getJSON(site+"requestStick.php",params,processRequested);
        }
    });


    $('#searchResultTable tbody tr').click(function () {
        $(this).removeClass('even');
    });

    function processRequested (data) {

        //        $('#divForms').fadeOut();
        //$('#forms').hide('slow');

        $('#divLivesearch').fadeOut();
        $('#topTitle').html("<h2>Registration Complete!</h2>")
        $('#divRequestResult').html("<p>"+data.text+"</p>");
        $('#divRequestResult').fadeIn();
    };

    $('#livesearch').keyup(
        function(){
            clearTimeout($.data(this, 'timer'));
            var wait = setTimeout(search, 250);
            $(this).data('timer', wait);

        });

    function search () {
        $.getJSON(site+"getschools.php","q=" + $('#livesearch').val(), processData);
    }


});
