/// <reference path="/scripts/jquery-1.6.2-vsdoc.js" />

var apprenticeshipAndJobSearchTypeDefault = "Apprenticeships and Jobs",
    apprenticeshipSearchTypeDefault = "Apprenticeships and Courses",
    sectorDefault = "All",
    newstextboxWithButtonText = "Email Address",
    searchTextboxWithButtonText = "What are you looking for?";

function AuthenticateFaceBook()
{
    FB.getLoginStatus(function (response)
    {
        if (response.status === 'connected')
        {
            var uid = response.authResponse.userID; 
            var accessToken = response.authResponse.accessToken;
            document.location.href = '/Verification/FacebookLogin.aspx?returnUrl=' + document.location.href + '&uid=' + uid + '&accessToken=' + accessToken;
        } 
    });
}

function EscapeQuote(text)
{
    return text.replace(/\'/g, '\\\'');
}

function getParameterByName(name)
{
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

function InitialiseHeaderCarousel(id)
{
    $(id).everyTime(8000, function ()
    {
        $(id + " div.image:first").clone().delay(2500).appendTo(id);
        //$(id + " div.image:first").delay(1).remove();
        $(id + " div.image:first").animate({ width: '0px' }, 2500, 'easeInOutSine', function () { $(id + " div.image:first").remove(); });
    });
}

function InitialiseRotator(id)
{
    $(this).everyTime(5000, function ()
    {
        $(id + " li:nth-child(1)").clone().appendTo(id);
        $(id + " li:nth-child(1)").slideUp(1000, "easeOutSine", function () { $(this).remove(); });
    });
}

function SetNewsletterAndFindTiles()
{
    $(".rightColumn div.module.single.textboxWithButton.home div.inner input").val(newstextboxWithButtonText);
    $(".rightColumn div.module.single.textboxWithButton.search div.inner input").val(searchTextboxWithButtonText);

    $(".rightColumn div.module.single.textboxWithButton.home div.inner button").click(function (e)
    {
        e.preventDefault();
        var emailAddress = encodeURIComponent($.trim($("#txtEmailAddress").val()));
        if ($("#txtEmailAddress").attr("disabled") != "disabled")
        {
            $.ajax({
                type: "POST",
                url: "/API/NewsletterService.asmx/SignUpForNewsletter",
                data: "{ 'emailAddress': '" + emailAddress + "' }",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg)
                {
                    $("#txtEmailAddress").val("Thank You!");
                    $("#txtEmailAddress").attr("disabled", true);
                },
                error: AjaxFailed()
            });
        }
    });
    $(".rightColumn div.module.single.textboxWithButton.search div.inner button").click(function (e) {
        PerformFindTileSearch($(this), e);
    });
    $(".rightColumn div.module.single.textboxWithButton.search div.inner input").keypress(function (e) {
        code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            PerformFindTileSearch($(this), e);
        }
    });

    //clear input on focus
    $(".rightColumn div.module.single.textboxWithButton.home div.inner input").focus(function ()
    {
        if ($(this).val() == newstextboxWithButtonText)
        {
            $(this).val("");
        }
    });
    //clear input on focus
    $(".rightColumn div.module.single.textboxWithButton.search div.inner input").focus(function ()
    {
        if ($(this).val() == searchTextboxWithButtonText)
        {
            $(this).val("");
        }
    });
    
    //reset input text to default upon blur
    $(".rightColumn div.module.single.textboxWithButton.home div.inner input").blur(function ()
    {
        if ($(this).val() == "")
        {
            $(this).val(newstextboxWithButtonText);
        }
    });
    //reset input text to default upon blur
    $(".rightColumn div.module.single.textboxWithButton.search div.inner input").blur(function ()
    {
        if ($(this).val() == "")
        {
            $(this).val(searchTextboxWithButtonText);
        }
    });
}

function PerformFindTileSearch(context, e) {
    e.preventDefault();
    var modulediv = context.parents("div.module.single.textboxWithButton.search");
    var searchInput = context.parent("div.inner").find("#txtSearchKeywords");
    var query = encodeURIComponent($.trim($(searchInput).val()));

    if (modulediv.hasClass("apprenticeshipsAndJobs")) {
        window.location = "/apprenticeship-and-job-search?kw=" + query;
    }
    else if (modulediv.hasClass("apprenticeships")) {
        window.location = "/apprenticeships/search?kw=" + query;
    }
    else if (modulediv.hasClass("jobs")) {
        window.location = "/jobs/search?kw=" + query;
    }
    else if (modulediv.hasClass("feed")) {
        if (modulediv.hasClass("careers")) {
            window.location = "/social/careers/search?kw=" + query;
        }
        else if (modulediv.hasClass("deals")) {
            window.location = "/social/deals/search?kw=" + query;
        }
        else if (modulediv.hasClass("games")) {
            window.location = "/social/games/search?kw=" + query;
        }
        else if (modulediv.hasClass("stuff")) {
            window.location = "/social/stuff/search?kw=" + query;
        }
    }
}


Object.size = function (obj)
{
    var size = 0, key;
    for (key in obj)
    {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

function AjaxFailed(message)
{

}

function CheckLoggedIn()
{
    var isLoggedIn = false;
    if ($("#isLoggedIn").val() == "true")
    {
        isLoggedIn = true;
    }
    return isLoggedIn;
}

function ResizeLoginWindow(defaultSize)
{
    if (defaultSize)
    {
        $(".loginJoinLightboxContainerOuter").animate(
        {
            "width": "502px",
            "margin-left": "-251px"
        },
        500,
        function ()
        {
            $(".loginJoinLightboxContainerInner div.register").fadeIn();
        });

        $(".loginJoinLightboxContainerInner").animate(
        {
            width: '470px'
        },
        500
        );
    }
    else
    {
        $(".loginJoinLightboxContainerOuter").animate(
        {
            "width": "700px",
            "margin-left": "-350px"
        },
        500,
        function ()
        {
            $(".loginJoinLightboxContainerInner div.register").fadeIn();
        });

        $(".loginJoinLightboxContainerInner").animate(
        {
            width: '670px'
        },
        500
        );
    }
}

function Login(e)
{
    e.preventDefault();
    $(".loginJoinLightboxContainerInner.login .errorField").fadeOut();

    var emailAddress = $("#emailAddress").val(),
            password = $("#password").val();

    $.ajax({
        type: "POST",
        url: "/API/MemberService.asmx/LoginBIGDOGAccount",
        data: "{ 'emailAddress': '" + emailAddress + "', 'password': '" + password + "' }",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg)
        {
            //console.log(msg.d); DO NOT LEAVE breaks IE7/8!
            if (msg.d == true)
            {
                _gaq.push(['_trackEvent', 'login', emailAddress]);
                window.location.href = window.location.href;
            }
            else
            {
                $(".loginJoinLightboxContainerInner .login .errorField").show();
            }
        },
        error: AjaxFailed()
    });

    return false;
}

function SetUpLoginLinks()
{
    $(".forgotPassword a").click(function ()
    {
        $(".loginJoinLightboxContainerInner div.login").fadeOut(function ()
        {
            $.get("/jQueryTemplates/forgotPasswordTemplate.htm", function (template)
            {
                $.tmpl(template).insertAfter(".loginJoinLightboxContainerInner div.login");
                $(".loginJoinLightboxContainerInner div.forgot").fadeIn();

                $("#forgotEmail").focus();

                //console.log($("div.forgot").find("button.cancel")); DO NOT LEAVE breaks IE7/8!

                $("div.forgot").find("button.cancel").click(function ()
                {
                    $(".loginJoinLightboxContainerInner div.forgot").fadeOut(function ()
                    {
                        $(this).remove();
                        $(".loginJoinLightboxContainerInner div.login").fadeIn();
                        $("#emailAddress").focus();
                    });
                });

                $("div.forgot").find("button.submit").click(function ()
                {
                    var emailAddress = $("#forgotEmail").val();

                    $.ajax({
                        type: "POST",
                        url: "/API/MemberService.asmx/ForgottenPassword",
                        data: "{ 'emailAddress': '" + emailAddress + "' }",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (msg)
                        {
                            //console.log(msg.d); DO NOT LEAVE breaks IE7/8!
                            if (msg.d == true)
                            {
                                _gaq.push(['_trackEvent', 'forgot-password', emailAddress]);
                                if (window.location.href.indexOf('?', 0) > 0)
                                {
                                    window.location.href = window.location.href + "\&w=3";
                                }
                                else
                                {
                                    window.location.href = window.location.href + "?w=3";
                                }
                            }
                        },
                        error: AjaxFailed()
                    });
                    return false;
                });

            });
        });

        return false;
    });
    $(".login button[type=button]").click(function (e)
    {
        return Login(e);
    });
    $(".register a").click(function ()
    {
        ResizeLoginWindow(false);
        $(".loginJoinLightboxContainerInner div.login").fadeOut(function ()
        {
            $.get("/jQueryTemplates/registerTemplate.htm", function (template)
            {
                $.tmpl(template).insertAfter(".loginJoinLightboxContainerInner div.login");

                $("div.joinContainer").find("button.cancel").click(function ()
                {
                    $(".loginJoinLightboxContainerInner div.join").fadeOut(function ()
                    {
                        ResizeLoginWindow(true);
                        $(this).remove();
                        $(".loginJoinLightboxContainerInner div.login").fadeIn();
                        $("#emailAddress").focus();
                    });
                });

                $(".loginJoinLightboxContainerInner div.join").fadeIn();
                $("#firstName").focus();

                $(".join .fieldContainer.field input").focus(function () { $(this).parent("div").removeClass("error"); if ($(this).val() == "This is a required field") { $(this).val(""); } });

                $(".loginJoinLightboxContainerInner").find(".join").find("button.submit").click(function ()
                {
                    var firstName = $("#registerFirstName").val(),
                        lastName = $("#registerLastName").val(),
                        emailAddress = $("#registerEmailAddress").val(),
                        password = $("#registerPassword").val(),
                        confirmPassword = $("#registerConfirmPassword").val(),
                        telephoneHome = $("#registerHomeTelephone").val(),
                        telephoneMobile = $("#registerMobileTelephone").val(),
                        postCode = $("#registerPostcode").val();

                    $(".join .fieldContainer.field").removeClass("error");

                    var isValid = true;

                    if (firstName == "" || firstName == "This is a required field")
                    {
                        isValid = false;
                        $("#registerFirstName").val("This is a required field")
                        $(".join .fieldContainer.field.registerFirstName").addClass("error");
                    }
                    if (lastName == "" || lastName == "This is a required field")
                    {
                        isValid = false;
                        $("#registerLastName").val("This is a required field")
                        $(".join .fieldContainer.field.registerLastName").addClass("error");
                    }
                    if (emailAddress == "" || emailAddress == "This is a required field")
                    {
                        isValid = false;
                        $("#registerEmailAddress").val("This is a required field")
                        $(".join .fieldContainer.field.registerEmailAddress").addClass("error");
                    }
                    if (password == "")
                    {
                        isValid = false;
                        $(".join .fieldContainer.field.registerPassword").addClass("error");
                    }
                    if (password != confirmPassword)
                    {
                        isValid = false;
                        $(".join .fieldContainer.field.registerPassword").addClass("error");
                        $(".join .fieldContainer.field.registerConfirmPassword").addClass("error");
                    }

                    if (postCode == "" || postCode == "This is a required field")
                    {
                        isValid = false;
                        $("#registerPostcode").val("This is a required field")
                        $(".join .fieldContainer.field.registerPostcode").addClass("error");
                    }

                    if (isValid)
                    {

                        $.ajax({
                            type: "POST",
                            url: "/API/MemberService.asmx/CreateBigDogAccount",
                            data: "{ 'firstName': '" + firstName + "', 'lastName': '" + lastName + "', 'emailAddress': '" + emailAddress + "', 'password': '" + password + "', 'telephoneHome': '" + telephoneHome + "', 'telephoneMobile': '" + telephoneMobile + "', 'postCode': '" + postCode + "' }",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (msg)
                            {
                                //console.log(msg.d); DO NOT LEAVE breaks IE7/8!
                                if (msg.d == true)
                                {
                                    _gaq.push(['_trackEvent', 'register-bigdog', emailAddress]);
                                    if (window.location.href.indexOf('?', 0) > 0)
                                    {
                                        window.location.href = window.location.href + "\&w=2";
                                    }
                                    else
                                    {
                                        window.location.href = window.location.href + "?w=2";
                                    }
                                }
                                else
                                {
                                    $(".loginJoinLightboxContainerInner .login .errorField").show();
                                }
                            },
                            error: AjaxFailed()
                        });
                    }
                    return false;
                });
            });
        });

        return false;
    });
}

function ShowLoginPane()
{
    $.get("/jQueryTemplates/loginTemplate.htm", function (template)
    {
        $(document).keyup(function (e)
        {
            e.preventDefault();
            if (e.keyCode == 27)
            {
                if ($(".loginJoinLightboxShadow").length > 0)
                {
                    $(".loginJoinLightboxShadow, .loginJoinLightboxContainerOuter").fadeOut(function ()
                    {
                        $(this).remove();
                    });
                }
            }
            if (e.keyCode == 13)
            {
                Login(e);
            }
        });

        $.tmpl(template).appendTo("#loginContainer");

        $(".loginJoinLightboxShadow, .loginJoinLightboxContainerOuter").hide().fadeIn();

        $("#emailAddress").focus();

        SetUpLoginLinks();

        FB.XFBML.parse();

        $(".loginJoinLightboxShadow").click(function ()
        {
            $(".loginJoinLightboxShadow, .loginJoinLightboxContainerOuter").fadeOut(function ()
            {
                $(this).remove();
            });
        });
    });
}

function ShowDialogPane(dialogHeader, dialogHTML, dialogButton)
{
    $.get("/jQueryTemplates/dialogTemplate.htm", function (dialogTemplate)
    {
        $(document).keyup(function (e)
        {
            e.preventDefault();
            if (e.keyCode == 27)
            {
                if ($(".loginJoinLightboxShadow").length > 0)
                {
                    $(".loginJoinLightboxShadow, .loginJoinLightboxContainerOuter").fadeOut(function ()
                    {
                        $(this).remove();
                    });
                }
            }
        });

        $.tmpl(dialogTemplate, { "dialogHeader": dialogHeader, "dialogHTML": dialogHTML, "dialogButton": dialogButton }).appendTo("#loginContainer");

        $(".loginJoinLightboxShadow, .loginJoinLightboxContainerOuter").hide().fadeIn();

        $(".loginJoinLightboxShadow").click(function ()
        {
            $(".loginJoinLightboxShadow, .loginJoinLightboxContainerOuter").fadeOut(function ()
            {
                $(this).remove();
            });
        });
        $("#dialogClose").click(function ()
        {
            $(".loginJoinLightboxShadow, .loginJoinLightboxContainerOuter").fadeOut(function ()
            {
                $(this).remove();
            });
        });
    });
}

function PerformSiteSearch()
{
    var searchInputSelector = $("#searchContainer").children("input");
    var query = encodeURIComponent($.trim($(searchInputSelector).val()));
    window.location = "/search?q=" + query;
}

function PerformApprenticeshipSearch()
{
    var jobSearchKeyword = $("#jobSearchKeyword").val(),
        jobSearchLocation = $("#jobSearchLocation").val(),
        queryString = [],
        variableCount = 0;

    if ((jobSearchKeyword != "") || (jobSearchLocation != ""))
    {

        if (jobSearchKeyword != "")
        {
            queryString.push("kw=" + jobSearchKeyword);
            variableCount++;
        }
        if (jobSearchLocation != "")
        {
            if (variableCount > 0)
            {
                queryString.push("&")
            }
            queryString.push("lo=" + jobSearchLocation);
            variableCount++;
        }
        if (variableCount > 0)
        {
            window.location = "/apprenticeships/search?" + queryString.join("");
        }
    }
    else
    {

        $("#jobSearchKeyword, #jobSearchLocation").addClass("inputError").val("Please enter a value").focus(function ()
        {
            $("#jobSearchKeyword, #jobSearchLocation").removeClass("inputError").val("");
        });
    }
}

function PerformJobSearch()
{
    var jobSearchKeyword = $("#jobSearchKeyword").val(),
        jobSearchLocation = $("#jobSearchLocation").val(),
        jobSearchSector = $("#jobSearchSector").val(),
        queryString = [],
        variableCount = 0;

    if ((jobSearchKeyword != "") || (jobSearchLocation != ""))
    {

        if (jobSearchKeyword != "")
        {
            queryString.push("kw=" + jobSearchKeyword);
            variableCount++;
        }
        if (jobSearchLocation != "")
        {
            if (variableCount > 0)
            {
                queryString.push("&")
            }
            queryString.push("lo=" + jobSearchLocation);
            variableCount++;
        }
        if (jobSearchSector != sectorDefault)
        {
            if (variableCount > 0)
            {
                queryString.push("&")
            }
            queryString.push("se=" + jobSearchSector);
            variableCount++;
        }
        if (variableCount > 0)
        {
            window.location = "/jobs/search?" + queryString.join("");
        }
    }
    else
    {

        $("#jobSearchKeyword, #jobSearchLocation").addClass("inputError").val("Please enter a value").focus(function ()
        {
            $("#jobSearchKeyword, #jobSearchLocation").removeClass("inputError").val("");
        });
    }
}

function PerformApprenticeshipAndJobSearch()
{
    var jobSearchKeyword = $("#jobSearchKeyword").val(),
        jobSearchLocation = $("#jobSearchLocation").val(),
        jobSearchType = $("#jobSearchType").val(),
        jobSearchSector = $("#jobSearchSector").val(),
        queryString = [],
        variableCount = 0;

    if ((jobSearchKeyword != "") || (jobSearchLocation != ""))
    {

        if (jobSearchKeyword != "")
        {
            queryString.push("kw=" + jobSearchKeyword);
            variableCount++;
        }
        if (jobSearchLocation != "")
        {
            if (variableCount > 0)
            {
                queryString.push("&")
            }
            queryString.push("lo=" + jobSearchLocation);
            variableCount++;
        }
        if (jobSearchType != apprenticeshipAndJobSearchTypeDefault)
        {
            if (variableCount > 0)
            {
                queryString.push("&")
            }
            queryString.push("ty=" + jobSearchType);
            variableCount++;
        }
        if (jobSearchSector != sectorDefault)
        {
            if (variableCount > 0)
            {
                queryString.push("&")
            }
            queryString.push("se=" + jobSearchSector);
            variableCount++;
        }
        if (variableCount > 0)
        {
            window.location = "/apprenticeship-and-job-search?" + queryString.join("");
        }
    }
    else
    {

        $("#jobSearchKeyword, #jobSearchLocation").addClass("inputError").val("Please enter a value").focus(function ()
        {
            $("#jobSearchKeyword, #jobSearchLocation").removeClass("inputError").val("");
        });
    }
}

$(document).ready(function () {
    SetNewsletterAndFindTiles();

    InitialiseRotator(".module.threeRow.topTen.jobs .list ul");
    InitialiseRotator(".module.threeRow.topTen.news .list ul");
    InitialiseRotator(".module.threeRow.topTen.apprenticeships .list ul");
    InitialiseRotator(".module.threeRow.topTen.vacancies .list ul");
    InitialiseRotator(".module.twoRow.topTen.vacancies .list ul");

    InitialiseHeaderCarousel(".module.twoCol.headerCarousel .content .inner");

    $("#searchContainer").children("input").keypress(function (e) {
        code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            PerformSiteSearch();
            return false;
        }
    });
    $("a.searchButton").click(function () {
        PerformSiteSearch();
        return false;
    });
    $(".module.search.apprenticeshipSearch").find("div.submitContainer").children("button").click(function () {
        PerformApprenticeshipSearch();
        return false;
    });
    $(".module.search.apprenticeshipSearch").find("div.fieldContainer").children("input").keypress(function (e) {
        code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            PerformApprenticeshipSearch();
            return false;
        }
    });
    $(".module.search.jobSearch").find("div.submitContainer").children("button").click(function () {
        PerformJobSearch();
        return false;
    });
    $(".module.search.jobSearch").find("div.fieldContainer").children("input").keypress(function (e) {
        code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            PerformJobSearch();
            return false;
        }
    });
    $(".module.search.apprenticeshipAndJobSearch").find("div.submitContainer").children("button").click(function () {
        PerformApprenticeshipAndJobSearch();
        return false;
    });
    $(".module.search.apprenticeshipAndJobSearch").find("div.fieldContainer").children("input").keypress(function (e) {
        code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            PerformApprenticeshipAndJobSearch();
            return false;
        }
    });
    $("#loginContainer a.login").click(function () {
        ShowLoginPane();
        return false;
    });

    $("#loginContainer a.logout").click(function () {
        $.ajax({
            type: "POST",
            url: "/API/MemberService.asmx/Logout",
            data: "{ }",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                window.location.href = window.location.href;
            },
            error: AjaxFailed()
        });
        return false;
    });

    //Set backgorunds / overlay
    $.vegas({ src: '/images/backgrounds/palebluecartoon.jpg' });
    //$.vegas('overlay', { src: '/images/backgrounds/overlays/03.png' });

    //Show Welcome Panel
    if (getParameterByName("w") == "1") {
        ShowDialogPane("Welcome to BIGDOG!", "<p>Your email address has been verified and you're ready to go!</p>", "Close");
    }
    else if (getParameterByName("w") == "2") {
        ShowDialogPane("Welcome to BIGDOG!", "<p>To be able to complete the setup of your account we need to verify your email address. Please check your inbox for an email from BIGDOG and click the link in the message.!</p>", "Close");
    }
    else if (getParameterByName("w") == "3") {
        ShowDialogPane("Password Reset", "<p>A new password has been sent to your email address</p>", "Close");
    }
});

