/* @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 attribute for value in form field
    var input = $(".useTitleForValue");
    input.attr({ "value": input.attr("title") });
    input.addClass("inactive");

    input.focus(function() {
        if ($(this).val() == input.attr("title")) {
            input.removeAttr("value");
            input.removeClass("inactive");
        }
    });
    input.blur(function() {
        if ($(this).val() === "") {
            input.attr({ "value": $(".useTitleForValue").attr("title") });
            input.addClass("inactive");
        }
    });

    // 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
    $(".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();

    // 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" />');

    // see templates/default/grantSearch.aspx for js variables
    //var grantSearchHelpTitle = [];
    //var grantSearchHelpContent = ["];

    $(".expandable").addClass("expandable-active");
    $(".expandable > li:not(.startActive)").addClass("inactive");
    $(".expandable > li.startActive").addClass("active");
    $(".expandable > li > div div").show();
    $(".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]);
                    }
                }
            }
        });

        return false;
    });
    $(".expandable input.submit").click(function() {
        $(this).parents(".expandable:eq(0)").children("> li").removeClass("active").addClass("inactive").find("> div").slideUp("fast");
    });

    // Grant search map ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    var $firstAccess = true;
    var $defaultBgPos;
    var $regionSelected = false;

    var $mapLocationArray =
	{
	    "international":0,
		"world-wide":0,
		"england":0,
		"scotland":1,
		"northern-ireland":2,
		"yorkshire-and-the-humber":3,
		"north-west-england":4,
		"north-east-england":5,
		"east-midlands":6,
		"wales":7,
		"west-midlands":8,
		"east-of-england":9,
		"greater-london":10,
		"south-west-england":11,
		"south-east-england":12
	};

    $.fn.mapHover = function(name) {
		if (name != "") {
			name = name.indexOf(" ") != -1 ? name.split(" ")[0] : name;
		}
		
        var $mapWidth = 376;
        if ( name == "" || $mapLocationArray[name] == null || $mapLocationArray[name] == undefined) {
            $("#grant-search-map .wrapper").css({ backgroundPosition: $defaultBgPos });
        } else {
            $("#grant-search-map .wrapper").css({ backgroundPosition: '-' + (($mapLocationArray[name]) * $mapWidth) + 'px 0' });
        }
        if ($regionSelected) {
            if ($firstAccess) {
                $firstAccess = false;
                $defaultBgPos = $("#grant-search-map .wrapper").css("backgroundPosition");
            }
        } else {
            $defaultBgPos = "0 0";
        }
    };
    //var mapClass = readCookie("wizGrantMap");
    //if(mapClass != null){
    //	$("#grant-search-map > div").addClass(mapClass);
    //}

    $("#grant-search-map li a").bind("mouseover focus", function() { $(this).mapHover( $(this).parent().attr("class")); });
    $("#grant-search-map li a").bind("mouseout blur", function() { $(this).mapHover(""); });
    $("#grant-search-map li a").click(function() {
        createCookie("wizGrantMap", "region-selected " + $(this).parent().attr("class"));
        document.forms["wiz-search"].submit();
        return false;
    });
    if ($("#grant-search-map div").hasClass("region-selected")) {
        $regionSelected = true;
        var $regionName = $("#grant-search-map div").attr("class").split("region-selected ")[1];
        var $regionObj = $("#grant-search-map li." + $regionName);
        var $regionIndex = $regionObj.parent().children().index($regionObj);
        $regionObj.mapHover($regionIndex);
    }

    // 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 label").click(function() {
        $(this).parents(".expand:eq(0)").find("> ul").toggle();
        $(this).parents(".expand:eq(0)").find("a.toggle-plus").toggleClass("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");
    });
    // establishes getCounts for Search details
    $("div.grant-search .toggle-list .expand > div input, div.grant-search .toggle-list li > div input").click(function() {
        var $thisChecked = $(this).attr("checked");
        var $thisValue = $(this).attr("name");
        if ($thisChecked) {
			$(".tempOutput").html("<img src='/images/ajax-loader.gif' width='16' height'16' alt='updating result count' />");
            var $thisData = { add: $thisValue, time: new Date().getTime() };
            jQuery.get("/Ajax/getCounts.aspx", $thisData, function(data, textStatus) {
                //$(".tempOutput").html("<span>" + data.schemeCount + "</span> <em>results so far</em>.");
                if (data.schemeCount == 1) {
                    $(".tempOutput").html("<p><span>" + data.schemeCount + "</span> result results to display</p>");
                } else {
                    $(".tempOutput").html("<p><span>" + data.schemeCount + "</span> results results to display</p>");
                }
            }, "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("<img src='/images/ajax-loader.gif' width='16' height'16' alt='updating result count' />");
            $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 results to display</p>");
                } else {
                    $(".tempOutput").html("<p><span>" + data.schemeCount + "</span> results results to display</p>");
                }
            }, "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 $thisChecked = $(this).attr("checked");
        var $thisValue = $(this).attr("value");
        var $thisData = null;

        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 };
        } else {
            $thisData = { remove: $thisValue };
        }

        getPersonalCounts($thisChecked, $thisData);
    });
    // establishes getCounts for Personal Details drop-downs
    $("#toggle-item2 select").change(function() {
        var $thisValue = $(this).val();
        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;
		}
        var $thisData = null;
        if ($thisChecked) {
            $thisData = { add: $thisValue };
        } else {
            $thisData = { remove: $thisValue };
        }

        getPersonalCounts($thisChecked, $thisData);
    });

    function getPersonalCounts(isChecked, theData) {
        theData.when = new Date().getTime();
		$(".tempOutput").html("<img src='/images/ajax-loader.gif' width='16' height'16' alt='updating result count' />");
        jQuery.get("/Ajax/getCounts.aspx", theData, function(data, textStatus) {
            if (data.schemeCount == 1) {
                $(".tempOutput").html("<p><span>" + data.schemeCount + "</span> result results to display</p>");
            } else {
                $(".tempOutput").html("<p><span>" + data.schemeCount + "</span> results results to display</p>");
            }
        }, "json");
        //if ( isChecked ) {
        //	$(this).parents(".expand:eq(0)").find("> div > a.toggle-plus").addClass("toggle-plus-active");
        //	$(this).parents(".expand:eq(0)").find("> ul").show();
        //}
    }
    /*
    * Amends Grand search A to Z
    **********************************************************/
    $(".letter label").click(function() {
        $(".letter label").removeClass("active");
        $(this).toggleClass("active");
    });


    // Register intermediary form

    // Register variables

    var formDisabled = ($("#yourAdminArea .isFormDisabled").length > 0) ? ($("#yourAdminArea .isFormDisabled").val().toLowerCase() === 'true') : false;

    // Startup

    if (formDisabled) {

        // Disable overall form

        $("#yourAdminArea").addClass("disableSection");
        $("#yourAdminHeading span").removeClass("hide");
    }
    else if ($("#yourAdminArea .isIntermediaryAdmin").is(":checked")) {

        // Disable just admin detail fields

        $("#yourAdminArea select, #yourAdminArea input[type='text']").val("");
        $("#yourAdminArea select, #yourAdminArea input[type='text']").attr("disabled", true);
        $("#yourAdminArea li.adminDetailField").addClass("disableSection");

    }

    // Event handlers that trigger form events

    $(".selectBranches").click(function() {
        if ($(".txtOtherBranch").val() === "") {
            if ($(".selectBranches").val() != "NOTSELECTED") {
				populateAdminForm();
			}else{
				clearAdminForm();
			}
        }
    });

    $(".txtOtherBranch").keyup(function() {
        if ($(this).val() !== "") {
			clearAdminForm();
		}else if ($(".selectBranches").val() != "NOTSELECTED") {
			populateAdminForm();
		}
    });

    $("input[name='radBranch']").click(function() {
        if ($(this).hasClass("otherButton")) {
			clearAdminForm();
		}
		else {
			populateAdminForm();
		}
    });

    $("#yourAdminArea input[name='radIsAdmin']").click(function() {
        if (!formDisabled) {
            if ($("#yourAdminArea .isIntermediaryAdmin").is(":checked")) {
				disableAdminDetailFields();
			}else {
				enableAdminDetailFields();
			}
        }
    });

    // Functionality

    function populateAdminForm() {
        var branchName = getBranchName();

        $.ajax({
            type: "POST",
            url: "/Ajax/IntermediaryAdmin.aspx/Get",
            data: "{branchName: \"" + branchName + "\"}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data) {

                // Disable form

                disableAdminForm();

                var parentElement = $("#yourAdminArea");

                var selAdminTitle = parentElement.find(".selAdminTitle");
                var txtAdminOtherTitle = parentElement.find(".txtAdminOtherTitle");
                var txtAdminForename = parentElement.find(".txtAdminForename");
                var txtAdminSurname = parentElement.find(".txtAdminSurname");
                var txtAdminEmail = parentElement.find(".txtAdminEmail");
                var txtAdminPhone = parentElement.find(".txtAdminPhone");
                var txtAdminMobile = parentElement.find(".txtAdminMobile");

                selAdminTitle.val(data.Title);
                var x = selAdminTitle.val();
                if (selAdminTitle.val() == "Select") {
					txtAdminOtherTitle.val(data.Title);
				}

                txtAdminForename.val(data.Firstname);
                txtAdminSurname.val(data.Surname);
                txtAdminEmail.val(data.Email);
                txtAdminPhone.val(data.Telephone);
                txtAdminMobile.val(data.Mobile);
            }
        });
    }

    function clearAdminForm() {
        enableAdminForm();
        var parentElement = $("#yourAdminArea");

        var selAdminTitle = parentElement.find(".selAdminTitle");
        var txtAdminOtherTitle = parentElement.find(".txtAdminOtherTitle");
        var txtAdminForename = parentElement.find(".txtAdminForename");
        var txtAdminSurname = parentElement.find(".txtAdminSurname");
        var txtAdminEmail = parentElement.find(".txtAdminEmail");
        var txtAdminPhone = parentElement.find(".txtAdminPhone");
        var txtAdminMobile = parentElement.find(".txtAdminMobile");

        selAdminTitle.val("");
        txtAdminOtherTitle.val("");

        txtAdminForename.val("");
        txtAdminSurname.val("");
        txtAdminEmail.val("");
        txtAdminPhone.val("");
        txtAdminMobile.val("");
    }

    function disableAdminForm() {
        if (!formDisabled) {

            // Set form disabled

            formDisabled = true;
            setFormStatus();

            // Disable fields

            $("#yourAdminArea input[type='text'], #yourAdminArea input[type='radio'], #yourAdminArea select").attr("disabled", true);

            $("#yourAdminArea .isNotIntermediaryAdmin").attr("checked", true);

            $("#yourAdminArea").animate({ opacity: 0.5 }, 500, function() {
                $(this).addClass("disableSection");
                $("#yourAdminHeading span").fadeIn("fast", function() { $(this).removeClass("hide"); });
            });
        }
    }

    function enableAdminForm() {
        if (formDisabled) {

            // Set form enabled

            formDisabled = false;
            setFormStatus();

            // Reset radio button

            $("#yourAdminArea input[name='radIsAdmin']").removeAttr("disabled");
            $("#yourAdminArea .isIntermediaryAdmin").attr("checked", true);
            $("#yourAdminArea input[name='radIsAdmin']").trigger("change");

            $("#yourAdminArea").animate({ opacity: 1 }, 500, function() {
                $(this).removeClass("disableSection");
                $("#yourAdminHeading span").fadeOut("fast", function() { $(this).addClass("hide"); });
            });
        }
    }

    function disableAdminDetailFields() {

        $("#yourAdminArea select, #yourAdminArea input[type='text']").val("");
        $("#yourAdminArea select, #yourAdminArea input[type='text']").attr("disabled", true);

        $("#yourAdminArea li.adminDetailField").animate({ opacity: 0.5 }, 500, function() {
            if (!$(this).hasClass("disableSection")) {
				$(this).addClass("disableSection");
			}
        });
    }

    function enableAdminDetailFields() {

        $("#yourAdminArea select, #yourAdminArea input[type='text']").removeAttr("disabled");

        $("#yourAdminArea li.adminDetailField").animate({ opacity: 1 }, 500, function() {
            if ($(this).hasClass("disableSection")) {
				$(this).removeClass("disableSection");
			}
        });
    }

    function setFormStatus() {
        $("#yourAdminArea .isFormDisabled").val(formDisabled.toString());
    }

    function getBranchName() {
        if ($(".selectBranches").length > 0 && $(".selectBranches").val() != "NOTSELECTED") {
			return $(".selectBranches").val();
		}else if ($("input[name='radBranch']").is(":checked") && !$("input[name='radBranch']:checked").hasClass("otherBranch")) {
			return $("input[name='radBranch']:checked").next("span").text();
		}else{
			return "";
		}
    }

});

/* 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;
}