/* @author thomas.bran */

/* custom JQuery ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

// tootip rollover for forms
this.tooltip = function() {
    /* CONFIG */
    xOffset = 10;
    yOffset = 20;
    // these 2 variable determine popup's distance from the cursor
    // you might want to adjust to get the right result		
    /* END CONFIG */
    $("a.tooltip").hover(function(e) {

        this.t = this.title;
        this.title = "";
        $("body").append("<p id='tooltip'>" + this.t + "</p>");
        $("#tooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px")
			.fadeIn("fast");
    },
	function() {
	    this.title = this.t;
	    $("#tooltip").remove();
	});
    $("a.tooltip").mousemove(function(e) {
        $("#tooltip")
			.css("top", (e.pageY - xOffset) + "px")
			.css("left", (e.pageX + yOffset) + "px");
    });
};

$(document).ready(function() {
    // allow number-only input on forms
    $("input.numberOnly").keypress(function(e) {
        var nums = "0123456789";
        var keycode = String.fromCharCode(e.which);
        // don't block L/R, Delete, Backspace, or '+'
        if ((e.which === null) || (e.which === 0) || (e.which == 8) || (e.which == 9) || (e.which == 13) || (e.which == 27) || (e.which >= 37 && e.which <= 40) || e.which == 43 || e.which == 46) {
            return true;
            // limit to numbers
        } else if (nums.indexOf(keycode) > -1) {
            return true;
        } else {
            return false;
        }
    });
    // make all links with the class 'external' open in a new window
    $("a.external").attr({ "target": "_blank" });

    // use title for value - see 'custom jquery plugins'
    $(".useTitleForValue").useTitleForValue();

    // focus/blur states for form elements
    $("input[@type='text'], input[@type='password'], textarea").focus(function() { $(this).css("background-color", "#fff"); });
    $("input[@type='text'], input[@type='password'], textarea").blur(function() { $(this).css("background-color", "#f6f4f9"); });
    $("input[@disabled]").css({ "background-color": "#eeeeee", "color": "#555555" });


    // add the 'print page' link to the page
    $("#pageActions").append('<li class="print"><a href="javascript:window.print();" title="Print this page">Print page<\/a><\/li>');

    // add the toggle to the 'show more' links on the search results
    function setupShowMoreLinks() {
        $(".more").hide();
        $(".more").after('<p class="expand"><a href="#" title="Link title">Show more</a></p>');
        $("p.expand a").click(function() {
            $(this).parent().siblings("div.more").slideToggle("fast");
            $(this).parent().toggleClass("open");
            return false;
        }).toggle(function() { $(this).text("Show less"); }, function() { $(this).text("Show more"); }).parent().show();
    }
    setupShowMoreLinks();

    // piano-key-colour (i.e. alternate) the rows of the tables
    $("table:not('.noRowColours') tr:odd(), ul.pianokeys li:odd(), .pianokeys div.item:odd()").addClass("odd");

    //get last item in search result and add a style on the bottom
    //$("mainSearchResults .item").after("ici");
    var itemsTab = $(".searchtop").get();
    var l = itemsTab.length;
    //alert(itemsTab.length);
    if (l > 0) {
        //	$(itemsTab[1]).remove();
    }
    itemsTab = $(".item").get();
    l = itemsTab.length;
    //alert(itemsTab.length);
    if (l >= 0) {
        $(itemsTab[0]).css("border-top", "1px solid #ccc");
    }
    // tootip rollover for forms
    //tooltip();	

    // hide items
    $(".jshide").hide();

    $("a.search-remove").append('<img src="/images/icon_remove.gif" alt="Remove this item" width="14" height="14" />');

    // see templates/default/grantSearch.aspx for js variables
    //var grantSearchHelpTitle = [];
    //var grantSearchHelpContent = ["];

    $("ul.expandable").addClass("expandable-active");
    $("ul.expandable > li:not(.startActive)").addClass("inactive");
    $("ul.expandable > li.startActive").addClass("active");
    $("ul.expandable > li > div div").show();
    // Hide .expand-form-footers
    $("ul.expandable div.expand-form-footer").hide();
    $("ul.expandable div.expand-form-footer input.submit").hide();
    $("ul.expandable > li > a").click(function() {
        $(this).parent().siblings().removeClass("active").addClass("inactive");
        $(this).parent().toggleClass("inactive").toggleClass("active");
        $(this).parent().siblings().find("div:first").slideUp("fast");
        $(this).next().slideToggle("fast", function() {
            // changing the help text on the adv grant search ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            if ($(".grant-search")) {
                var $li = $(this).parent();
                var $id = parseInt($li.attr("id").split("toggle-item")[1], 0);

                if ($id) {
                    if ($(this).parent().parent().find(".active").length > 0) {
                        $("#help-block-title").html(grantSearchHelpTitle[$id]);
                        $("#help-block-content").html(grantSearchHelpContent[$id]);
                    }
                    else {
                        $("#help-block-title").html(grantSearchHelpTitle[0]);
                        $("#help-block-content").html(grantSearchHelpContent[0]);
                    }
                }
                //if ($(".expand-form-footer", this).is(":visible")) { $(".demo .expand-form-footer", this).hide(); }
            }
        });

        return false;
    });
    //    $("ul.expandable input.submit").click(function() {
    //        $(this).parents(".expandable:eq(0)").children("> li").removeClass("active").addClass("inactive").find("> div").slideUp("fast");
    //    });

    // Toggle list (plus/minus) - grant search ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    $(".toggle-list .expand > ul:not(.startOpen)").hide();
    $(".toggle-list .expand > div").prepend('<a class="toggle-plus"></a>');
    $(".toggle-list .expand > ul.startOpen").prev().children("a:first-child").addClass("toggle-plus-active");
    $(".toggle-list .expand > div .toggle-plus").click(function() {
        $(this).parents(".expand:eq(0)").find("> ul").toggle();
        $(this).parents(".expand:eq(0)").find("> div > a.toggle-plus").toggleClass("toggle-plus-active");
    });

    // Open location fields on load
    $("#toggle-item3 .expand:eq(0)").find("> ul").toggle();
    $("#toggle-item3 .expand:eq(1)").find("> ul").toggle();
    $("#toggle-item3 .expand:eq(0)").find("> div > a.toggle-plus").toggleClass("toggle-plus-active");
    $("#toggle-item3 .expand:eq(1)").find("> div > a.toggle-plus").toggleClass("toggle-plus-active");

    // establishes getCounts for Search details
    $(".toggle-list .expand > div input, .toggle-list li > div input").click(function() {
        var $footer = $(this).parents("li.active").find(".expand-form-footer");
        if (!$footer.is(":visible")) {
            $footer.slideDown();
        }
        var $thisChecked = $(this).attr("checked");
        var $thisValue = $(this).attr("id");
        var $valueArray = $(this).attr("value").split("_");
        var $thisName = $valueArray[1];

        if ($thisChecked) {
            $(".tempOutput").html("<p><img src='/images/ajax-loader.gif' width='16' height'16' alt='updating result count' /></p>");
            var $thisData = { add: $thisValue, name: $thisName, time: new Date().getTime() };
            jQuery.get("/Ajax/getCounts.aspx", $thisData, function(data, textStatus) {
                if (data.schemeCount == 1) {
                    $(".tempOutput").html("<p><span>" + data.schemeCount + "</span> result to display</p>");
                } else {
                    $(".tempOutput").html("<p><span>" + data.schemeCount + "</span> results to display</p>");
                }
                updateCriteria();
            }, "json");
            $(this).parents(".expand:eq(0)").find("> div > a.toggle-plus").addClass("toggle-plus-active");
            $(this).parents(".expand:eq(0)").find("> ul").show();
        }
        else {
            $(".tempOutput").html("<p><img src='/images/ajax-loader.gif' width='16' height'16' alt='updating result count' /></p>");
            $thisData = { remove: $thisValue, time: new Date().getTime() };
            jQuery.get("/Ajax/getCounts.aspx", $thisData, function(data, textStatus) {
                if (data.schemeCount == 1) {
                    $(".tempOutput").html("<p><span>" + data.schemeCount + "</span> result to display</p>");
                } else {
                    $(".tempOutput").html("<p><span>" + data.schemeCount + "</span> results to display</p>");
                }
                updateCriteria();
            }, "json");
        }
        if ($(this).parents(".expand:eq(0)").find("ul input").size() > 0) {
            //$(this).parents(".expand:eq(0)").find("ul input").attr('checked', $thisChecked);
        }

    });
    // establishes getCounts for Personal Details checkboxes
    $("#toggle-item2 input[name*='repAges'], #toggle-item2 input[name*='gender'], #toggle-item2 input[name*='pd-benefits']").click(function() {
        var $footer = $(this).parents("li.active").find(".expand-form-footer");
        if (!$footer.is(":visible")) {
            $footer.slideDown();
        }
        var $thisChecked = $(this).attr("checked");
        var $thisValue = $(this).attr("value");
        var $thisData = null;
        var $thisName = $("label[for=" + $(this).attr("id") + "]").text();

        if ($(this).attr("name").indexOf('repAges') > 0) {
            $thisValue = "age_" + $thisValue;
        }
        else if ($(this).attr("name").indexOf('gender') > 0) {
            $thisValue = "gender_" + $thisValue;
        } else if ($(this).attr("name").indexOf('pd-benefits')) {
            if ($thisValue.indexOf("Yes") > 0) {
                $thisValue = "ben_1";
            } else {
                $thisValue = "ben_0";
            }
        }

        if ($thisChecked) {
            $thisData = { add: $thisValue, name: $thisName };
        } else {
            $thisData = { remove: $thisValue };
        }

        getPersonalCounts($thisChecked, $thisData);
    });
    // establishes getCounts for Personal Details drop-downs
    $("#toggle-item2 select").change(function() {
        var $footer = $(this).parents("li.active").find(".expand-form-footer");
        if (!$footer.is(":visible")) {
            $footer.slideDown();
        } var 
        $thisValue = $(this).val();
        var $thisName = this.options[this.selectedIndex].text;
        var $thisChecked = $thisValue !== "";

        if ($(this).attr("name").indexOf('ddFamily') > 0) {
            $thisValue = "fam_" + (($thisChecked) ? $thisValue : "0");
        } else if ($(this).attr("name").indexOf('ddNationality') > 0) {
            $thisValue = "nat_" + $thisValue;
        } else if ($(this).attr("name").indexOf('ddHealth') > 0) {
            $thisValue = "hlt_" + $thisValue;
        } else if ($(this).attr("name").indexOf('ddReligion') > 0) {
            $thisValue = "rel_" + $thisValue;
        } else if ($(this).attr("name").indexOf('ddIssues') > 0) {
            $thisValue = "iss_" + $thisValue;
        }
        var $thisData = null;
        if ($thisChecked) {
            $thisData = { add: $thisValue, name: $thisName };
        } else {
            $thisData = { remove: $thisValue };
        }

        getPersonalCounts($thisChecked, $thisData);
    });

    // Performs AJAX call to get counts for the personal details section
    function getPersonalCounts(isChecked, theData) {
        theData.when = new Date().getTime();
        $(".tempOutput").html("<p><img src='/images/ajax-loader.gif' width='16' height'16' alt='updating result count' /></p>");
        jQuery.get("/Ajax/getCounts.aspx", theData, function(data, textStatus) {
            if (data.schemeCount == 1) {
                $(".tempOutput").html("<p><span>" + data.schemeCount + "</span> result to display</p>");
            } else {
                $(".tempOutput").html("<p><span>" + data.schemeCount + "</span> results to display</p>");
            }
            updateCriteria();
        }, "json");
    }

    // Sets up remove links to use AJAX
    function setUpRemoveLinks() {
        $("#queryBuilderArea a.search-remove").click(function() {
            var $thisHref = $(this).attr("href");
            var $urlParts = $thisHref.split("?");
            var $type = "";
            var $id = "";
            var $thisValue = "";
            var $untick = true;
            var $thisChecked = false;
            if ($urlParts.length == 2) {
                $queryString = $urlParts[1];
                $parameters = $queryString.split("&");
                for (i = 0; i < $parameters.length; i++) {
                    $paramParts = $parameters[i].split("=");
                    if ($paramParts[0] == "type") {
                        $type = $paramParts[1];
                    }
                    if ($paramParts[0] == "id") {
                        $id = $paramParts[1];
                    }
                }
            }
            if ($id != "") {
                switch ($type) {
                    case "Occupation":
                        $thisValue = "occ_" + $id;
                        break;
                    case "HelpRequired":
                        $thisValue = "prp_" + $id;
                        break;
                    case "Location":
                        $thisValue = "loc_" + $id;
                        break;
                    case "AgeRange":
                        $thisValue = "age_" + $id;
                        $untick = false;
                        $("#toggle-item2 input:checkbox[value=" + $id + "]").attr("checked", "");
                        break;
                    case "Gender":
                        $untick = false;
                        $("#toggle-item2 input:radio[id$=radGenderNon]").attr("checked", "checked");
                        $thisValue = "gender_0";
                        $thisChecked = true;
                        break;
                    case "Nationality":
                        $untick = false;
                        $("#toggle-item2 select[id$=ddNationality]").val("");
                        $thisValue = "nat_";
                        break;
                    case "Family":
                        $untick = false;
                        $("#toggle-item2 select[id$=ddFamily]").val("");
                        $thisValue = "fam_0";
                        break;
                    case "Health":
                        $untick = false;
                        $("#toggle-item2 select[id$=ddHealth]").val("");
                        $thisValue = "hlt_";
                        break;
                    case "Religion":
                        $untick = false;
                        $("#toggle-item2 select[id$=ddReligion]").val("");
                        $thisValue = "rel_";
                        break;
                    case "Issues":
                        $untick = false;
                        $("#toggle-item2 select[id$=ddIssues]").val("");
                        $thisValue = "iss_";
                        break;
                    case "RecieveBenefits":
                    case "ReceiveBenefits":
                        $untick = false;
                        $("#toggle-item2 input:radio[id$=radBenefitsNon]").attr("checked", "checked");
                        $thisValue = "ben_0";
                        $thisChecked = true;
                        break;
                    case "Keyword":
                        $untick = false;
                        $("#toggle-item5 input:text[id$=txtKeyword]").val("");
                        $thisValue = "keyword_";
                        break;
                    case "LocationKeyword":
                        $untick = false;
                        $("#toggle-item3 input:text[id$=txtLocationKeyword]").val("");
                        $thisValue = "lockeyword_";
                        break;
                }

                if ($thisValue != "" && $untick == true) {
                    $("#" + $thisValue).attr("checked", "");
                }

                if ($thisValue != "") {
                    if ($thisChecked) {
                        $thisData = { add: $thisValue };
                    } else {
                        $thisData = { remove: $thisValue };
                    }

                    getPersonalCounts($thisChecked, $thisData);
                }
            }
            return false;
        });
    }

    // Updates the search criteria box at the bottom of the search form
    function updateCriteria() {
        if ($("#resultsDisplayArea").is(":visible")) {
            $("#resultsDisplayArea").slideUp();
            $("#resultsDisplayArea").html("");
            $("#resultsDisplayArea").slideDown();
        }
        $("#queryBuilderArea").html("<p><img src='/images/ajax-loader-big.gif' width='32' height'32' alt='loading your current search criteria' /></p>");
        jQuery.get("/Ajax/getCurrentCriteria.aspx", { when: new Date().getTime() }, function(data) {
            $("#queryBuilderArea").html(data);
            $("#queryBuilderArea a.search-remove").append('<img src="/images/icon_remove.gif" alt="Remove this item" width="14" height="14" />');
            setUpRemoveLinks();
            setupSearchButton();
        });
    }

    // Updates the search criteria box at the bottom of the search form
    function updateCriteriaWithOnlineEnqFilter(showOnlineEnqOnly) {
        $("#queryBuilderArea").html("<p><img src='/images/ajax-loader-big.gif' width='32' height'32' alt='loading your current search criteria' /></p>");
        var $filter = "none";
        if (showOnlineEnqOnly)
            $filter = "onlineonly";
        jQuery.get("/Ajax/getCurrentCriteria.aspx", { filter: $filter, when: new Date().getTime() }, function(data) {
            $("#queryBuilderArea").html(data);
            $("#queryBuilderArea a.search-remove").append('<img src="/images/icon_remove.gif" alt="Remove this item" width="14" height="14" />');
            setUpRemoveLinks();
            setupSearchButton();
            performSearch(1, false, "default");
        });
    }

    // Continuing on-load events:

    // Set up remove links
    setUpRemoveLinks();

    // Add button after location keyword search box
    //$("#locationKeywordArea input.keyword").after('<input type="submit" id="locationKeywordButton" class="submit" value="Add to search" />');
    $("#locationKeywordArea input.submit").click(function() {
        $thisValue = $("#locationKeywordArea input.location").val();
        if ($thisValue != null && $thisValue != "" && $thisValue != "Type your keyword(s) here and add them to your search") {
            var $footer = $(this).parents("li.active").find(".expand-form-footer");
            if (!$footer.is(":visible")) {
                $footer.slideDown();
            }

            AddLocationKeyword($thisValue);
        }
        else {
            $("#locationKeywordArea input.location").focus();
        }
        return false;
    });

    // Handle keyword input enter keypress
    $("#locationKeywordArea input.location").keypress(function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            $thisValue = $("#locationKeywordArea input.location").val();
            if ($thisValue != null && $thisValue != "" && $thisValue != "Type your keyword(s) here and add them to your search") {
                var $footer = $(this).parents("li.active").find(".expand-form-footer");
                if (!$footer.is(":visible")) {
                    $footer.slideDown();
                }

                AddLocationKeyword($thisValue);
            }
            else {
                $("#locationKeywordArea input.location").focus();
            }
            return false;
        }
    });

    function AddLocationKeyword($thisValue) {
        $(".tempOutput").html("<p><img src='/images/ajax-loader.gif' width='16' height'16' alt='updating result count' /></p>");
        var $thisData = { add: "lockeyword_" + $thisValue, name: $thisValue, time: new Date().getTime() };
        jQuery.get("/Ajax/getCounts.aspx", $thisData, function(data, textStatus) {
            if (data.schemeCount == 1) {
                $(".tempOutput").html("<p><span>" + data.schemeCount + "</span> result to display</p>");
            } else {
                $(".tempOutput").html("<p><span>" + data.schemeCount + "</span> results to display</p>");
            }
            updateCriteria();
        }, "json");
    }

    // Handle keyword box button click
    $("#keywordArea input.submit").click(function() {
        $thisValue = $("#keywordArea input.keyword").val();
        if ($thisValue != null && $thisValue != "" && $thisValue != "Type your keyword(s) here and add them to your search") {
            var $footer = $(this).parents("li.active").find(".expand-form-footer");
            if (!$footer.is(":visible")) {
                $footer.slideDown();
            }

            addKeywordCriteria($thisValue);
        }
        else {
            $("#keywordArea input.keyword").focus();
        }
        return false;
    });

    // Handle keyword input enter keypress
    $("#keywordArea input.keyword").keypress(function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            $thisValue = $("#keywordArea input.keyword").val();
            if ($thisValue != null && $thisValue != "" && $thisValue != "Type your keyword(s) here and add them to your search") {
                var $footer = $(this).parents("li.active").find(".expand-form-footer");
                if (!$footer.is(":visible")) {
                    $footer.slideDown();
                }

                addKeywordCriteria($thisValue);
            }
            else {
                $("#keywordArea input.keyword").focus();
            }
            return false;
        }
    });

    function addKeywordCriteria(keywords) {
        $(".tempOutput").html("<p><img src='/images/ajax-loader.gif' width='16' height'16' alt='updating result count' /></p>");
        var $thisData = { add: "keyword_" + keywords, name: keywords, time: new Date().getTime() };
        jQuery.get("/Ajax/getCounts.aspx", $thisData, function(data, textStatus) {
            if (data.schemeCount == 1) {
                $(".tempOutput").html("<p><span>" + data.schemeCount + "</span> result to display</p>");
            } else {
                $(".tempOutput").html("<p><span>" + data.schemeCount + "</span> results to display</p>");
            }
            updateCriteria();
        }, "json");
    }

    // Handle search-button click
    function setupSearchButton() {
        $("#queryBuilderArea input.submit").click(function() {
            $(this).parents(".search-select-list").children("> ul.expandable").children("> li").removeClass("active").addClass("inactive").find("> div").slideUp("fast");
            performSearch(1, false, "default");
            return false;
        });
    }
    setupSearchButton();

    // Perform search using AJAX
    function performSearch(pageNum, isPagination, sortDirection) {
        if (!isPagination) {
            $("#resultsDisplayArea").slideUp();
            $("#resultsDisplayArea").html("<p><img src='/images/ajax-loader-big.gif' width='32' height'32' alt='loading results' /></p>");
            $("#resultsDisplayArea").slideDown();
        }

        jQuery.ajax({
            url: '/Ajax/getSearchResults.aspx',
            data: { pagenum: pageNum, sort: sortDirection, when: new Date().getTime() },
            success: function(data, textStatus) {
                if (!isPagination) {
                    $("#resultsDisplayArea").hide();
                }
                $("#resultsDisplayArea").html(data);
                setupShowMoreLinks();
                setupPaginationLinks();
                setupStartNewSearch();
                setupSortLinks();
                setupRating();
                setupOnlineOnlyCheckbox();
                if (!isPagination) {
                    $("#resultsDisplayArea").slideDown();
                }
                $.scrollTo($("#resultsDisplayArea"), 500);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                $("#resultsDisplayArea").html("<p>Error performing the search.</p>");
            }
        });

        // Add google tracking
        if (!isPagination) {
            try {
                var pageTracker = _gat._getTracker(gaKey);
                pageTracker._trackPageview('/advanced_search_completed.htm');
            } catch (err) { }
        }
    }

    // Handle pagination clicks using AJAX
    function setupPaginationLinks() {
        $("#grant-search-results ul.pageNav a").click(function() {
            var $thisHref = $(this).attr("href");
            var $urlParts = $thisHref.split("?");
            var $thisPageNum = 1;
            if ($urlParts.length == 2) {
                var $queryString = $urlParts[1].split("#")[0];
                var $parameters = $queryString.split("&");
                for (i = 0; i < $parameters.length; i++) {
                    var $paramParts = $parameters[i].split("=");
                    if ($paramParts[0] == "pagenum") {
                        $thisPageNum = $paramParts[1];
                    }
                }
            }
            $(this).replaceWith('<img src="/images/ajax-loader-purple.gif" width="16" height="16" alt="loading results" style="margin: 0; float: none;" />');
            performSearch($thisPageNum, true, "default");
            return false;
        });
    }
    setupPaginationLinks();
    setupStartNewSearch();
    setupRating();
    setupSortLinks();
    setupOnlineOnlyCheckbox();

    // Handles the online enquiries only filter
    function setupOnlineOnlyCheckbox() {
        // Hide the refresh button
        $("#grant-search-results input.submit[id$=btnRefresh]").hide();
        $("#grant-search-results input[id$=chkOnlineEnqOnly]").click(function() {
            var $thisChecked = $(this).attr("checked");
            updateCriteriaWithOnlineEnqFilter($thisChecked);
        });
    }

    // Sets up the sorting links in the results
    function setupSortLinks() {
        $("#grant-search-results p.searchAgain a[id$=ancSortAlpha]").click(function() {
            performSearch(1, true, "name");
            return false;
        });
        $("#grant-search-results p.searchAgain a[id$=ancSortGrantSize]").click(function() {
            performSearch(1, true, "award");
            return false;
        });
    }

    // Handle start new search button
    function setupStartNewSearch() {
        $("#grant-search-results a[id$=ancNewSearch]").click(function() {
            jQuery.ajax({
                url: '/Ajax/getCounts.aspx',
                data: { clearsearch: "true", when: new Date().getTime() },
                success: function(data, textStatus) {
                    // Clear all tick-boxes
                    $("#queryBuilderArea a.search-remove").each(function() {
                        var $thisHref = $(this).attr("href");
                        var $urlParts = $thisHref.split("?");
                        var $type = "";
                        var $id = "";
                        var $thisValue = "";
                        var $untick = true;
                        if ($urlParts.length == 2) {
                            $queryString = $urlParts[1];
                            $parameters = $queryString.split("&");
                            for (i = 0; i < $parameters.length; i++) {
                                $paramParts = $parameters[i].split("=");
                                if ($paramParts[0] == "type") {
                                    $type = $paramParts[1];
                                }
                                if ($paramParts[0] == "id") {
                                    $id = $paramParts[1];
                                }
                            }
                        }
                        if ($id != "") {
                            switch ($type) {
                                case "Occupation":
                                    $thisValue = "occ_" + $id;
                                    break;
                                case "HelpRequired":
                                    $thisValue = "prp_" + $id;
                                    break;
                                case "Location":
                                    $thisValue = "loc_" + $id;
                                    break;
                                case "AgeRange":
                                    $untick = false;
                                    $("#toggle-item2 input:checkbox[value=" + $id + "]").attr("checked", "");
                                    break;
                                case "Gender":
                                    $untick = false;
                                    $("#toggle-item2 input:radio[id$=radGenderNon]").attr("checked", "checked");
                                    break;
                                case "Nationality":
                                    $untick = false;
                                    $("#toggle-item2 select[id$=ddNationality]").val("");
                                    break;
                                case "Family":
                                    $untick = false;
                                    $("#toggle-item2 select[id$=ddFamily]").val("");
                                    break;
                                case "Religion":
                                    $untick = false;
                                    $("#toggle-item2 select[id$=ddReligion]").val("");
                                    break;
                                case "Issues":
                                    $untick = false;
                                    $("#toggle-item2 select[id$=ddIssues]").val("");
                                    break;
                                case "RecieveBenefits":
                                case "ReceiveBenefits":
                                    $untick = false;
                                    $("#toggle-item2 input:radio[id$=radBenefitsNon]").attr("checked", "checked");
                                    break;
                                case "Health":
                                    $untick = false;
                                    $("#toggle-item2 select[id$=ddHealth]").val("");
                                    break;
                                case "Keyword":
                                    $untick = false;
                                    $("#toggle-item5 input:text[id$=txtKeyword]").val("");
                                    break;
                                case "LocationKeyword":
                                    $untick = false;
                                    $("#toggle-item3 input:text[id$=txtLocationKeyword]").val("");
                                    break;
                            }

                            if ($thisValue != "" && $untick == true) {
                                $("#" + $thisValue).attr("checked", "");
                            }
                        }
                    });

                    // Show criteria
                    updateCriteria();
                    // Hide search results
                    $("#resultsDisplayArea").slideUp(44, function() {
                        $("#resultsDisplayArea").html("");
                    });
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    $("#resultsDisplayArea").html("<p>Error starting a new search.</p>");
                }
            });
            $.scrollTo(0, 500);
            return false;
        });
    }

    // Handle rating a search with AJAX
    function setupRating() {
        $("#grant-search-results div.rateSearch input.submit").click(function() {
            var $selectedValue = "";
            $("#grant-search-results div.rateSearch input.radio").each(function() {
                if ($(this).attr("checked") != "") {
                    $selectedValue = $(this).attr("value");
                }
            });

            // Clear any error messages
            $("#grant-search-results div.rateSearch p.error").remove();

            if ($selectedValue != "") {
                // Save with AJAX
                $("#grant-search-results div.rateSearch input.submit").after('<img src="/images/ajax-loader-purple.gif" width="16" height="16" alt="saving your rating" style="margin: 0; float: none;" />');
                jQuery.ajax({
                    url: '/Ajax/saveSearchRating.aspx',
                    data: { rating: $selectedValue, when: new Date().getTime() },
                    dataType: "json",
                    success: function(data, textStatus) {
                        if (data.result == "success") {
                            $("#grant-search-results div.rateSearch").slideUp();
                            setTimeout(function() {
                                $("#grant-search-results div.rateSearch").html("<p class=\"success\">Thank you for rating your search.</p>").slideDown();
                                $("#grant-search-results div.rateSearch .success").yellowFade();
                            }, 1000);
                        }
                        else {
                            $("#grant-search-results div.rateSearch img").slideUp();
                            $("#grant-search-results div.rateSearch fieldset").after("<p class=\"error\">There was an error saving the rating.</p>").slideDown();
                            $("#grant-search-results div.rateSearch .error").yellowfade();
                        }
                    },
                    error: function(XMLHttpRequest, textStatus, errorThrown) {
                        $("#grant-search-results div.rateSearch img").slideUp();
                        $("#grant-search-results div.rateSearch fieldset").after("<p class=\"error\">We were unable to save your rating at this time.</p>").slideDown();
                        $("#grant-search-results div.rateSearch .error").yellowFade();
                    }
                });
            }
            else {
                // Display error message
                $("#grant-search-results div.rateSearch fieldset").after("<p class=\"error\">Please choose a rating to save.</p>");
            }
            return false;
        });
    }

    window.onbeforeunload = function() {
        if ($("#resultsDisplayArea").is(":visible") && $("#resultsDisplayArea").html().trim() != "") {
            return "Moving away from this page will lose your search results.";
        }
    };
    //$(window).bind("beforeunload", function() { return "Moving away from this page will lose your search results.  Are you sure you want to change page?"; });

});

/* custom jQuery plugins ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

jQuery.fn.useTitleForValue = function() { 
	this.each(function(){
		i = jQuery(this);
		if (i.attr("title").length) {
			i.addClass("inactive").attr({
				"value": i.attr("title")
			});
			i.focus(function(){
				if (jQuery(this).val() == jQuery(this).attr("title")) {jQuery(this).removeClass("inactive").attr("value","");}
			})
			i.blur(function(){
				if (jQuery(this).val() === "") {jQuery(this).addClass("inactive").attr({"value": jQuery(this).attr("title")});}
			});
		}
	});
	return this;
};

jQuery.fn.yellowFade = function() {
	var $y = $(this);
	$y.css("backgroundColor","#ffff99");
	setTimeout(function(){
		$y.animate({"backgroundColor":"white"},2000);
	},2000);
};


/* custom JS functions ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

/*function toggleContrast(){
$('body').toggleClass('hc')
}
*/

function updateRelatedFormFields() {
    // var options is loaded in an external file - see formoptions.js
    var option = $("#selectOne").val();

    if (option != "_") {
        $("#selectTwo").children().remove();
        for (i = 0; i < options[option].length; i++) {
            $("<option value='" + i + "'>" + options[option][i] + "<\/option>").appendTo("#selectTwo");
            //$("#selectTwo").css("background-color", "#ffffaa").end().animate({backgroundColor: "white"},2000);
        }
    }
    return false;
}

/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}
	
	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break; 

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};
	
	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {
		aqua:[0,255,255],
		azure:[240,255,255],
		beige:[245,245,220],
		black:[0,0,0],
		blue:[0,0,255],
		brown:[165,42,42],
		cyan:[0,255,255],
		darkblue:[0,0,139],
		darkcyan:[0,139,139],
		darkgrey:[169,169,169],
		darkgreen:[0,100,0],
		darkkhaki:[189,183,107],
		darkmagenta:[139,0,139],
		darkolivegreen:[85,107,47],
		darkorange:[255,140,0],
		darkorchid:[153,50,204],
		darkred:[139,0,0],
		darksalmon:[233,150,122],
		darkviolet:[148,0,211],
		fuchsia:[255,0,255],
		gold:[255,215,0],
		green:[0,128,0],
		indigo:[75,0,130],
		khaki:[240,230,140],
		lightblue:[173,216,230],
		lightcyan:[224,255,255],
		lightgreen:[144,238,144],
		lightgrey:[211,211,211],
		lightpink:[255,182,193],
		lightyellow:[255,255,224],
		lime:[0,255,0],
		magenta:[255,0,255],
		maroon:[128,0,0],
		navy:[0,0,128],
		olive:[128,128,0],
		orange:[255,165,0],
		pink:[255,192,203],
		purple:[128,0,128],
		violet:[128,0,128],
		red:[255,0,0],
		silver:[192,192,192],
		white:[255,255,255],
		yellow:[255,255,0]
	};
	
})(jQuery);

/* colour contrast switcher ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/

//---thanks to alistapart
//-----------------------------------------------------------------------------rerender
/*function rerender (x) {
w = 100 - 0.0001* (x);
//document.getElementById ('header').style.width = w + '%';
}*/
//-----------------------------------------------------------------------------cookie functions
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    } else {
        expires = "";
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}
function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1, c.length);
        }
        if (c.indexOf(nameEQ) === 0) {
            return c.substring(nameEQ.length, c.length);
        }
    }
    return null;
}
//-----------------------------------------------------------------------------setActiveStyleSheet
function setActiveStyleSheet(cssFileName) {
    href = '/templates/default/css/system/' + cssFileName + '.css';
    //alert (href);
    document.getElementById("Template_contrast").href = href;
    //alert ("done");
    return null;
}
//-----------------------------------------------------------------------------getActiveStyleSheet
function getActiveStyleSheet() {
    var obj = document.getElementById("Template_contrast");
    var cssFileName = "";

    if (null != obj) {
        href = obj.href;
        x = href.lastIndexOf('/') + 1;
        y = href.lastIndexOf('.');
        cssFileName = href.substring(x, y);
    }
    //alert ('cssFileName = ' + cssFileName);

    return cssFileName;
}
//-----------------------------------------------------------------------------getPreferredStyleSheet
function getPreferredStyleSheet() {
    var i, a;
    for (i = 0; (a = document.getElementsByTagName("link")[i]); i++) {
        if (a.getAttribute("rel").indexOf("style") != -1 &&
	a.getAttribute("rel").indexOf("alt") == -1 &&
	a.getAttribute("title")) {
            return a.getAttribute("title");
        }
    }
    return null;
}
//-----------------------------------------------------------------------------changeContrast
function changeContrast(caseNumber) {
    switch (caseNumber) {
        case 1: setActiveStyleSheet('normal-contrast'); displayHighContrastLink(); break;
        case 2: setActiveStyleSheet('high-contrast'); displayNormalContrastLink(); break;
    }
    rerender(caseNumber);
}
//-----------------------------------------------------------------------------displayFontSizeButtons
// buttons are displayed only when javascript is enabled.
function displayHighContrastLink() {
    li = document.getElementById('contrastLink');
    li.innerHTML = '<a href="javascript:changeContrast(2)" title="Use this link to view the high contrast site">High contrast view</a>';
    $(".sIFR-alternate-disabled").removeClass("sIFR-alternate-disabled").addClass("sIFR-alternate");
}
function displayNormalContrastLink() {
    li = document.getElementById('contrastLink');
    li.innerHTML = '<a href="javascript:changeContrast(1)" title="Use this link to view the normal contrast site">Normal contrast view</a>';
    $(".sIFR-alternate").removeClass("sIFR-alternate").addClass("sIFR-alternate-disabled");
}
//-----------------------------------------------------------------------------onLoad
if (document.addEventListener) {
    //doc is loaded twice!?!? 
    //document.addEventListener("DOMContentLoaded", init, false);
}
function init(e) {
    var cookie = readCookie("style");
    //alert(" - init - 1");
    var title = cookie ? cookie : getActiveStyleSheet();
    if (cookie !== null) {
        //alert(" - init - 2");
        setActiveStyleSheet(title);
        //alert(" - init - 3");
        if (title == "normal-contrast") {
            //alert(" - init - 31");
            displayHighContrastLink();
        } else {
            //alert(" - init - 32");
            displayNormalContrastLink();
            //alert(" - init - 42");
        }
    } else {
        //alert(" - init - 33");
        displayHighContrastLink();
        //alert(" - init - 43");
    }
    //rerender(4);
}

window.onload = init; /*works for IE and FF and Safari*/
window.onunload = function(e) {
    var title = getActiveStyleSheet();
    createCookie("style", title, 0);
};
