$(document).ready(function (e) {

    $('#tools-state').change(function () {

        $('#tools-suburb').find('option').remove().end().append(BindSuburbState($(this).val())).selectmenu();

    });

    $('#filters-state').change(function () {

        $('#filters-suburb').find('option').remove().end().append(BindSuburbState($(this).val())).selectmenu();

    });

    // #####################
    // Tools
    // #####################

    /*
    $(document).mouseup(function (e) {
    if ($(e.target).parents('#tools').attr('id') == undefined) {
    hideTools();
    hideProfile();
    hideLogin();
    }
    });
    */

    //$('#wrapper-inner').click(function (e) { $('#profile .login').hide() });

    $('#childcare-tools div.popup').animate({ height: 0 }, 0);

    $('#profile div.profile').attr('data-height', $('#profile div.profile').height());

    $('#profile div.profile').animate({ height: 0 }, 0);
    $('#profile div.login').animate({ height: 0 }, 0);


    $('#childcare-tools a').attr('data-visible', '0');



    $('#childcare-tools a').click(function (e) {
        toggleTools();
    });





    $('#profile a').attr('data-visible', '0');



    $('#profile a.nav').click(function (e) {
        if ($('#profile').hasClass('selected')) {
            toggleProfile();
        }
        else {
            toggleLogin();
        }
    });

    // #####################
    // Filters
    // #####################

    $('select.customSelect').selectmenu({
        style: 'dropdown',
        width: 207
    });

    $('input.postcode').focus(function (e) {
        if ($(this).val() == 'Enter a postcode') {
            $(this).val('');
        }
        if ($(this).val() == 'Enter A Postcode') {
            $(this).val('');
        }
    }).blur(function (e) {

        if ($(this).val() == '') {
            $(this).val('Enter A Postcode');
        }
    });


    $("#aspnetForm").validationEngine({ promptPosition: "topRight", scroll: false });


    $('a.remove').click(function (e) {

        $.post(
            '/CMSTemplates/GoodStart/PageTemplates/Service.aspx?Type=RMC',
            {},
            function (data) {

                // success
                if (data.Message == "Success") {
                    setProfileCentreSet();
                    setTimeout(showTools, 500);
                }
                // fail
                else {

                }

            });
            
    });


    $('#login-submit-button').click(function (e) {

        // form validation
        if ($("#aspnetForm").validationEngine('validate')) {


            $.post(
            '/CMSTemplates/GoodStart/PageTemplates/Service.aspx?Type=Auth',
            { email: $('#login-username').val(), password: $('#login-password').val() },
            function (data) {

                // success
                if (data.Message == "Success") {
                    // memberType: 'other' | 'parent' | 'childcare'

                    setProfile(data.Data.Firstname, data.Data.Lastname, data.Data.Role, true, true);
                    setProfileCentreDetails(data.Data.CentreID, data.Data.CentreName, data.Data.CentreUrl);
                }
                // fail
                else {
                    var errorMessage = "We have no record of that username.<br>Please try again."; // if loginSuccess is false, this is where you can set an error message
                    $('#login-username').validationEngine('showPrompt', errorMessage, null, null, true);
                }

            });
        }

    });



    $('#logout-button').click(function (e) {

        $.post(
            '/CMSTemplates/GoodStart/PageTemplates/Service.aspx?Type=Logout',
            {},
            function (data) { window.location.href = '/'; },
            'json');


        hideProfile();

        $('#my-centre').hide();
        $('#job-form').show();


        $('#profile a.nav').html('Login');
        $('#profile').removeClass('selected');
    });

    $('#forgot-password-button').click(function (e) {

        // reset the forgotten password area

        $('#password-submit').show(0);
        $('#password-entry').show(0);
        $('#password-blurb').html('Simply enter in your email address below and we\'ll send you a reminder.');

        $('#login').fadeOut(250);
        $('#password').fadeIn(250);

        $('#aspnetForm').validationEngine('hideAll');
    });

    $('#password-cancel-button').click(function (e) {
        $('#login').fadeIn(250);
        $('#password').fadeOut(250);
        $('#aspnetForm').validationEngine('hideAll');
    });

    $('#password-submit-button').click(function (e) {


        if (validatePassword()) {


            $.post(
            '/CMSTemplates/GoodStart/PageTemplates/Service.aspx?Type=RESET',
            { email: $('#password-email').val() },
            function (data) {

                // success
                if (data.Message == "Success") {
                    $('#password-submit').hide(0);
                    $('#password-entry').hide(0);
                    $('#password-blurb').html('Thank you. Your new password has been emailed to the account entered.');

                    // reset form
                    $('#password-email').val('').css('background-position', '12px center');
                }
                // fail
                else {
                    $('#password-email').validationEngine('showPrompt', "We have no record of that username.<br>Please try again.", null, null, true);

                }

            });

        }

    });



    if ($('#login-username').val() != '') {
        $('#login-username').css('background-position', '-500px center');
    }

    $('#login-username').focus(function (e) {
        $(this).css('background-position', '-500px center');
    }).blur(function (e) {
        if ($(this).val() == '') {
            $(this).css('background-position', '12px center');
        }
    });

    if ($('#login-password').val() != '') {
        $('#login-password').css('background-position', '-500px center');
    }

    $('#login-password').focus(function (e) {
        $(this).css('background-position', '-500px center');
    }).blur(function (e) {
        if ($(this).val() == '') {
            $(this).css('background-position', '12px center');
        }
    });

    if ($('#password-email').val() != '') {
        $('#password-email').css('background-position', '-500px center');
    }

    $('#password-email').focus(function (e) {
        $(this).css('background-position', '-500px center');
    }).blur(function (e) {
        if ($(this).val() == '') {
            $(this).css('background-position', '12px center');
        }
    });

    if (window.location.href.toLowerCase().indexOf('#login') != -1) {
        showLogin();
    }

});




// tools
function toggleTools() {
    if ($('#childcare-tools a').attr('data-visible') == '0') {
        showTools();
    }
    else {
        hideTools();
    }
}

function hideTools() {
    $('#childcare-tools a').attr('data-visible', '0');
    $('#childcare-tools a').parent().children('div.popup').stop(true, true).animate({ height: 0 }, 250, 'easeInExpo', function () { $(this).css('display', 'none'); });
}

function showTools() {
    hideProfile();
    hideLogin();
    $('#childcare-tools a').attr('data-visible', '1');
    $('#childcare-tools a').parent().children('div.popup').css('display', 'block').stop(true, true).animate({ height: 358 }, 350, 'easeOutExpo');
}
// profile
function toggleProfile() {
    if ($('#profile.selected a').attr('data-visible') == '0') {
        showProfile();
    }
    else {
        hideProfile();
    }
}

function hideProfile() {
    $('#profile.selected a').attr('data-visible', '0');
    $('#profile.selected a').parent().children('div.profile').stop(true, true).animate({ height: 0 }, 250, 'easeInExpo', function () { $(this).css('display', 'none'); });
}

function showProfile() {
    hideTools();
    $('#profile.selected a').attr('data-visible', '1');
    $('#profile.selected a').parent().children('div.profile').css('display', 'block').stop(true, true).animate({ height: $('#profile div.profile').attr('data-height') }, 350, 'easeOutExpo');
}


// login
function toggleLogin() {
    if ($('#profile').not('.selected').children('a').attr('data-visible') == '0') {
        showLogin();
    }
    else {
        hideLogin();
    }
}

function hideLogin() {
    $('#aspnetForm').validationEngine('hideAll');

    $('#profile').not('.selected').children('a').attr('data-visible', '0');
    $('#profile').not('.selected').children('a').parent().children('div.login').stop(true, true).animate({ height: 0 }, 250, 'easeInExpo', function () { $(this).css('display', 'none'); });
}

function showLogin() {
    hideTools();
    $('#profile').not('.selected').children('a').attr('data-visible', '1');
    $('#profile').not('.selected').children('a').parent().children('div.login').css('display', 'block').stop(true, true).animate({ height: 285 }, 350, 'easeOutExpo');
}

function validatePassword() {
    var result = true;

    // email
    if ($('#password-email').val() == "") {
        result = false;
        $('#password-email').validationEngine('showPrompt', '* This field is required', null, null, true);
    }
    else {

        if ($('#password-email').val().search(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i) == -1) {
            result = false;
            $('#password-email').validationEngine('showPrompt', '* Invalid email addres', null, null, true);
        }
        else {
            $('#password-email').validationEngine('hide');
        }
    }

    return result;
}

function setProfileCentreSet() {
    $('#my-centre-selected').hide();
    $('#my-centre-unselected').show();
}

function setProfileCentreDetails(centreID, centreName, centreUrl) {

    if (centreID == "0") {
        setProfileCentreSet();
    }
    else {
        $('#cct-centre-name').html(centreName);
        $('#cct-visit-centre-page').attr('href', centreUrl + '/overview');
        $('#cct-book-a-tour').attr('href', centreUrl + '/overview#book-a-tour');
        $('#cct-contact-us').attr('href', '/contact-us?centreId=' + centreID);
        $('#my-centre-selected').show();
        $('#my-centre-unselected').hide();
    }
}

function setProfile(firstName, lastName, memberType, showAlert, centreSelected) {
    hideLogin();

    $('#profile').addClass('selected');
    $('#profile a.nav').html(firstName);
    $('#profile span').html(firstName + ' ' + lastName);


    showAlert = false;
    // job alert
    if (!showAlert) {
        $('#job-alerts').css('display', 'none');
    }
    else {
        $('#job-alerts').css('display', 'block');
    }

    // tools
    if (memberType == 'parent') {
        if (centreSelected) {
            // show the links
            $('#wrapper-outer').removeClass().addClass('parent-centre');
        }
        else {
            // show text
            $('#wrapper-outer').removeClass().addClass('parent');
        }
    }
    else {
        $('#wrapper-outer').removeClass();
    }

    $('#aspnetForm').validationEngine('hideAll');

    // clear the form
    $('#login-username').val('').css('background-position', '12px center');
    $('#login-password').val('').css('background-position', '12px center');

}

function BindSuburbState(state) {

    if (state == 'NSW') {
        return '<option>albury</option><option>anna bay</option><option>ashfield</option><option>ashmont</option><option>ballina</option><option>bankstown</option><option>bathurst</option><option>berowra</option><option>blacktown</option><option>blue haven</option><option>bondi junction</option><option>broadmeadow</option><option>brookvale</option><option>byron bay</option><option>cameron park</option><option>carlton</option><option>cessnock</option><option>coffs harbour</option><option>corowa</option><option>cowra</option><option>cromer</option><option>dapto</option><option>deniliquin</option><option>dubbo</option><option>estella</option><option>fairfield heights</option><option>forbes</option><option>gateshead</option><option>glendale</option><option>glenfield park</option><option>glenwood</option><option>goonellabah</option><option>goulburn</option><option>grafton</option><option>green point</option><option>griffith</option><option>gunnedah</option><option>haberfield</option><option>hassall grove</option><option>hoxton park</option><option>hurstville</option><option>jerrabomberra</option><option>junee</option><option>kanahooka</option><option>kellyville</option><option>kellyville ridge</option><option>kelso</option><option>kensington</option><option>kincumber</option><option>kooringal</option><option>lake munmorah</option><option>lane cove</option><option>lavington</option><option>leeton</option><option>lennox head</option><option>mangerton</option><option>marrickville</option><option>menai</option><option>merrylands</option><option>miranda</option><option>moama</option><option>mona vale</option><option>moonee beach</option><option>moree</option><option>mosman</option><option>muswellbrook</option><option>narellan vale</option><option>narwee</option><option>nelson bay</option><option>new lambton</option><option>north ryde</option><option>north sydney</option><option>oakhurst</option><option>orange</option><option>parramatta</option><option>pendle hill</option><option>plumpton</option><option>port macquarie</option><option>prairiewood</option><option>quakers hill</option><option>rutherford</option><option>seven hills</option><option>south hurstville</option><option>south nowra</option><option>st leonards</option><option>tamworth</option><option>tamworth south</option><option>taree</option><option>tatton</option><option>thornton</option><option>thurgoona</option><option>toongabbie</option><option>toormina</option><option>tuggerah</option><option>tumbi umbi</option><option>tweed heads south</option><option>wagga wagga</option><option>wentworthville</option><option>west kempsey</option><option>west pymble</option><option>west ryde</option><option>willoughby</option><option>woodcroft</option><option>woongarrah</option><option>woy woy</option><option>yass</option><option>young</option>';
    }

    if (state == 'VIC') {
        return '<option>alfredton</option><option>altona</option><option>aspendale gardens</option><option>bairnsdale</option><option>ballarat</option><option>bayswater north</option><option>beaumaris</option><option>belgrave heights</option><option>bendigo</option><option>bentleigh east</option><option>berwick</option><option>blackburn</option><option>blackburn south</option><option>boronia</option><option>box hill</option><option>braybrook</option><option>brighton</option><option>brighton east</option><option>brunswick west</option><option>bundoora</option><option>burnside</option><option>carnegie</option><option>carrum downs</option><option>chadstone</option><option>chelsea heights</option><option>cheltenham</option><option>clayton</option><option>clifton hill</option><option>coburg</option><option>craigieburn</option><option>croydon</option><option>croydon south</option><option>dandenong</option><option>deer park</option><option>delacombe</option><option>dennington</option><option>derrimut</option><option>doncaster east</option><option>drouin</option><option>drysdale</option><option>east bentleigh</option><option>echuca</option><option>eltham</option><option>elwood</option><option>endeavour hills</option><option>epping</option><option>euroa</option><option>ferntree gully</option><option>flemington</option><option>forest hill</option><option>frankston</option><option>frankston south</option><option>geelong</option><option>geelong east</option><option>glen huntly</option><option>glenroy</option><option>golden square</option><option>greensborough</option><option>greenvale</option><option>grovedale</option><option>hampton park</option><option>heidelberg</option><option>hillside</option><option>hoppers crossing</option><option>horsham</option><option>ivanhoe</option><option>kangaroo flat</option><option>kealba</option><option>kurunjang</option><option>kyneton</option><option>langwarrin</option><option>lara</option><option>lynbrook</option><option>mckinnon</option><option>meadow heights</option><option>melbourne</option><option>melton</option><option>mentone</option><option>mildura</option><option>mill park</option><option>mont albert</option><option>montrose</option><option>moonee ponds</option><option>mooroolbark</option><option>morwell</option><option>mount clear</option><option>mount helen</option><option>mount martha</option><option>mount waverley</option><option>narre warren</option><option>narre warren south</option><option>new gisborne</option><option>newtown</option><option>noble park</option><option>numurkah</option><option>oakleigh</option><option>oakleigh south</option><option>pakenham</option><option>pascoe vale</option><option>point cook</option><option>portland</option><option>preston</option><option>reservoir</option><option>richmond east</option><option>riddells creek</option><option>ringwood</option><option>rosanna</option><option>rosebud</option><option>rowville</option><option>roxburgh park</option><option>seymour</option><option>shepparton</option><option>springvale</option><option>strathfieldsaye</option><option>sunbury</option><option>swan hill</option><option>sydenham</option><option>tarneit</option><option>taylors hill</option><option>thornbury</option><option>torquay</option><option>traralgon</option><option>vermont</option><option>wangaratta</option><option>wantirna</option><option>wantirna south</option><option>warragul</option><option>warrnambool</option><option>werribee</option><option>west melton</option><option>wodonga</option><option>woodend</option><option>yarrawonga</option>';
    }

    if (state == 'QLD') {
        return '<option>aitkenvale</option><option>albany creek</option><option>alexandra hills</option><option>algester</option><option>andergrove</option><option>annandale</option><option>ashgrove</option><option>ashmore</option><option>aspley</option><option>banksia beach</option><option>beachmere</option><option>beaudesert</option><option>beenleigh</option><option>bellbird park</option><option>belmont</option><option>benowa</option><option>bongaree</option><option>boonah</option><option>boondall</option><option>booval</option><option>boronia heights</option><option>bowen</option><option>bracken ridge</option><option>bray park</option><option>brighton</option><option>brinsmead</option><option>brisbane</option><option>brookwater</option><option>browns plains</option><option>buddina</option><option>buderim</option><option>bundaberg</option><option>burleigh waters</option><option>burpengary</option><option>caboolture</option><option>cairns</option><option>calamvale</option><option>caloundra</option><option>camira</option><option>capalaba</option><option>carina</option><option>carindale</option><option>carrara</option><option>churchill</option><option>clayfield</option><option>collingwood park</option><option>coopers plains</option><option>coorparoo</option><option>cranbrook</option><option>crestmead</option><option>currumbin</option><option>currumbin waters</option><option>daisy hill</option><option>dalby</option><option>deception bay</option><option>deeragun</option><option>douglas</option><option>dundowran</option><option>east brisbane</option><option>edmonton</option><option>eight mile plains</option><option>eimeo</option><option>emerald</option><option>eumundi</option><option>fernvale</option><option>forest lake</option><option>fortitude valley</option><option>gatton</option><option>gladstone</option><option>glass house mountains</option><option>goodna</option><option>gracemere</option><option>gympie</option><option>harristown</option><option>hawthorne</option><option>heatley</option><option>helensvale</option><option>hendra</option><option>hermit park</option><option>hervey bay</option><option>highfields</option><option>hyde park</option><option>idalia</option><option>indooroopilly</option><option>innisfail</option><option>isle of capri</option><option>jimboomba</option><option>jindalee</option><option>jones hill</option><option>kallangur</option><option>kanimbla</option><option>kedron</option><option>kelso</option><option>kenmore</option><option>kin kora</option><option>kingaroy</option><option>kirwan</option><option>kuluin</option><option>labrador</option><option>little mountain</option><option>logan village</option><option>loganlea</option><option>mackay</option><option>maleny</option><option>mango hill</option><option>manoora</option><option>manunda</option><option>maryborough</option><option>mcdowall</option><option>middle park</option><option>middle ridge</option><option>mooroobool</option><option>morayfield</option><option>morningside</option><option>mossman</option><option>mount isa</option><option>mount louisa</option><option>mount pleasant</option><option>mount sheridan</option><option>mount warren park</option><option>mt sheridan</option><option>mudgeeraba</option><option>murarrie</option><option>murrumba downs</option><option>nambour</option><option>narangba</option><option>nerang</option><option>new auckland</option><option>noosaville</option><option>north ipswich</option><option>north lakes</option><option>north mackay</option><option>north tamborine</option><option>nundah</option><option>ormeau</option><option>oxenford</option><option>oxley</option><option>pacific paradise</option><option>pacific pines</option><option>parkwood</option><option>petrie</option><option>pialba</option><option>pimpama</option><option>point vernon</option><option>proserpine</option><option>pullenvale</option><option>raceview</option><option>red hill</option><option>redbank plains</option><option>redcliffe</option><option>redland bay</option><option>richlands</option><option>riverside gardens</option><option>robertson</option><option>robina</option><option>rockhampton</option><option>roma</option><option>rothwell</option><option>rural view</option><option>shailer park</option><option>sinnamon park</option><option>slacks creek</option><option>south innisfail</option><option>stafford</option><option>stafford heights</option><option>tallai</option><option>tallebudgera</option><option>tannum sands</option><option>tarragindi</option><option>thorneside</option><option>toowoomba</option><option>trinity beach</option><option>upper coomera</option><option>upper mount gravatt</option><option>varsity lakes</option><option>virginia</option><option>walkerston</option><option>warner</option><option>warwick</option><option>waterford west</option><option>wavell heights</option><option>west mackay</option><option>wishart</option><option>woodford</option><option>woree</option><option>wynnum west</option><option>yamanto</option>';
    }

    if (state == 'ACT') {
        return '<option>aranda</option><option>braddon</option><option>garran</option><option>isaacs</option><option>kambah</option><option>kingston</option><option>turner</option>';
    }

    if (state == 'TAS') {
        return '<option>blackmans bay</option><option>claremont</option><option>glenorchy</option><option>hobart</option><option>kings meadows</option><option>newstead</option><option>north hobart</option><option>prospect</option>';
    }

    if (state == 'WA') {
        return '<option>albany</option><option>alfred cove</option><option>armadale</option><option>atwell</option><option>australind</option><option>baldivis</option><option>ballajura</option><option>banksia grove</option><option>bertram</option><option>busselton</option><option>canning vale</option><option>carlisle</option><option>clarkson</option><option>darch</option><option>dunsborough lakes</option><option>east bunbury</option><option>east perth</option><option>eaton</option><option>edgewater</option><option>girrawheen</option><option>greenfields</option><option>halls head</option><option>high wycombe</option><option>huntingdale</option><option>jandakot</option><option>joondalup</option><option>kalamunda</option><option>kingsley</option><option>madeley</option><option>madora bay</option><option>maida vale</option><option>meadow springs</option><option>merriwa</option><option>mindarie</option><option>mount nasura</option><option>myaree</option><option>nollamara</option><option>ocean reef</option><option>port kennedy</option><option>queens park</option><option>rockingham</option><option>secret harbour</option><option>sinagra</option><option>somerville</option><option>stratton</option><option>tapping</option><option>thornlie</option><option>warnbro</option><option>welshpool</option><option>wonthella</option>';
    }

    if (state == 'SA') {
        return '<option>aberfoyle park</option><option>angle park</option><option>bedford park</option><option>belair</option><option>blackwood</option><option>blakeview</option><option>brighton</option><option>campbelltown</option><option>clapham</option><option>clovelly park</option><option>evanston park</option><option>felixstow</option><option>gawler south</option><option>glenelg</option><option>hackham</option><option>hope valley</option><option>ingle farm</option><option>linden park</option><option>magill</option><option>marleston</option><option>mawson lakes</option><option>melrose park</option><option>mount gambier</option><option>nuriootpa</option><option>oakbank</option><option>old reynella</option><option>parafield gardens</option><option>paralowie</option><option>penfield</option><option>plympton</option><option>pooraka</option><option>prospect</option><option>salisbury north</option><option>seaford rise</option><option>semaphore park</option><option>semaphore south</option><option>sheidow park</option><option>smithfield</option><option>whyalla playford</option>';
    }

    if (state == 'NT') {
        return '<option>bakewell</option><option>bees creek</option><option>berrimah</option><option>marrara</option><option>moulden</option><option>nightcliff</option><option>palmerston</option><option>stuart park</option><option>tiwi</option>';
    }

    return '';
}
