/*
 *
 * Copyright (c) 2006-2010 Sam Collett (http://www.texotela.co.uk)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * 
 * Version 1.2
 * Demo: http://www.texotela.co.uk/code/jquery/numeric/
 *
 *  Used to only allow numbers to be entered into textarea
 *  Used on the Enquiry form
 *
 */
(function($){$.fn.numeric=function(decimal,callback)
{decimal=(decimal===false)?"":decimal||".";callback=typeof callback=="function"?callback:function(){};return this.data("numeric.decimal",decimal).data("numeric.callback",callback).keypress($.fn.numeric.keypress).blur($.fn.numeric.blur);}
$.fn.numeric.keypress=function(e)
{var decimal=$.data(this,"numeric.decimal");var key=e.charCode?e.charCode:e.keyCode?e.keyCode:0;if(key==13&&this.nodeName.toLowerCase()=="input")
{return true;}
else if(key==13)
{return false;}
var allow=false;if((e.ctrlKey&&key==97)||(e.ctrlKey&&key==65))return true;if((e.ctrlKey&&key==120)||(e.ctrlKey&&key==88))return true;if((e.ctrlKey&&key==99)||(e.ctrlKey&&key==67))return true;if((e.ctrlKey&&key==122)||(e.ctrlKey&&key==90))return true;if((e.ctrlKey&&key==118)||(e.ctrlKey&&key==86)||(e.shiftKey&&key==45))return true;if(key<48||key>57)
{if(key==45&&this.value.length==0)return true;if(decimal&&key==decimal.charCodeAt(0)&&this.value.indexOf(decimal)!=-1)
{allow=false;}
if(key!=8&&key!=9&&key!=13&&key!=35&&key!=36&&key!=37&&key!=39&&key!=46)
{allow=false;}
else
{if(typeof e.charCode!="undefined")
{if(e.keyCode==e.which&&e.which!=0)
{allow=true;if(e.which==46)allow=false;}
else if(e.keyCode!=0&&e.charCode==0&&e.which==0)
{allow=true;}}}
if(decimal&&key==decimal.charCodeAt(0))
{if(this.value.indexOf(decimal)==-1)
{allow=true;}
else
{allow=false;}}}
else
{allow=true;}
return allow;}
$.fn.numeric.blur=function()
{var decimal=$.data(this,"numeric.decimal");var callback=$.data(this,"numeric.callback");var val=$(this).val();if(val!="")
{var re=new RegExp("^\\d+$|\\d*"+decimal+"\\d+");if(!re.exec(val))
{callback.apply(this);}}}
$.fn.removeNumeric=function()
{return this.data("numeric.decimal",null).data("numeric.callback",null).unbind("keypress",$.fn.numeric.keypress).unbind("blur",$.fn.numeric.blur);}})(jQuery);


/* @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" });
    //Add hints to links which open in a new window
    var externalHint = 'opens in an external window';
    $('.footerLogo .external, #footer .external').append(' (' + externalHint + ')')
    $('.external').attr('title', externalHint);

    // 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").each(function() {
        $(this).prepend('<li class="print"><a href="javascript:window.print();" title="Print this page">Print page<\/a><\/li>');
        /*if (!($('body:first').hasClass('.myturn2us'))) {
            var prevItem = $(this).prev('#spotlight');
            if (prevItem.size()) {
                $(this).append('<li class="social"><a href="https://twitter.com/share" class="twitter-share-button" data-count="none">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script></li>')
                   .append('<li class="social"><iframe src="//www.facebook.com/plugins/like.php?href&amp;send=false&amp;layout=button_count&amp;width=91&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:91px; height:21px;" allowTransparency="true"></iframe></li>');

            } else {
                $(this).addClass('inline')
                   .prepend('<li class="social"><iframe src="//www.facebook.com/plugins/like.php?href&amp;send=false&amp;layout=button_count&amp;width=91&amp;show_faces=false&amp;action=like&amp;colorscheme=light&amp;font&amp;height=21" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:91px; height:21px;" allowTransparency="true"></iframe></li>')
                   .prepend('<li class="social"><a href="https://twitter.com/share" class="twitter-share-button" data-count="none">Tweet</a><script type="text/javascript" src="//platform.twitter.com/widgets.js"></script></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 "";
        }
    }


    //Survey form for /my_turn2us/EnquirySubmitted.aspx - added 18.08.11 
    function popup() {
        var page = "http://www.snapsurveys.com/turn2us/";
        var windowprops = "width=850,height=600,location=no,menubar=no,toolbar=no,scrollbars=no,resizable=no";
        newWindow = window.open(page, 'Turn2us_Survey', windowprops);
    }
    //Check if the pathname contains our URL, then open the popup if so
    if (location.pathname.indexOf('my_turn2us/EnquirySubmitted.aspx') > -1) {
        popup();
    }


});

/* 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;
}




/* In-page Pagination and easing to rollback to top of page ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */

function sectionsPagination() {
    var nos = $('.section').length;
    if (nos > 1) {
        var cs = 1;
        $('#mainContent').wrapInner('<div id="dynamicPages" />');
        $('.section').hide();
        $('.section:first').show();

        $('.section:last').after("<div class='pages'><div class='bottom'><p>Page " + cs + " of " + nos + "</p><ul><li class='prev'><a href='#pev'>Previous</a></li><li class='next'><a href='#next'>Next</a></li></ul></div>");
        $('.section:first').before("<div class='pages'><div class='top'><p>Page " + cs + " of " + nos + "</p><ul><li class='prev'><a href='#pev'>Previous</a></li><li class='next'><a href='#next'>Next</a></li></ul></div>");

        $('.prev a').hide();
        $('.section').each(function(i) {
            i++;
            $(this).addClass('section' + i);
        });
        $('.pages ul li a').click(function(event) {
            if ($(this).parent('li').attr('class') == "next") {
                if (cs == (nos - 1)) {
                    cs = nos;
                    $('.next a').hide();
                    $('.section').hide();
                    $('.section' + cs).show();
                    $('.pages p').text("Page " + cs + " of " + nos);
                } else if (cs < nos) {
                    cs++;
                    $('.next a').show();
                    $('.prev a').show();
                    $('.section').hide();
                    $('.section' + cs).show();
                    $('.pages p').text("Page " + cs + " of " + nos);
                }
            } else {
                if (cs == 1) {
                    $('.prev a').hide();
                    $('.pages p').text("Page " + cs + " of " + nos);
                } else if (cs >= 2) {
                    cs--;
                    $('.next a').show();
                    $('.prev a').show();
                    $('.section').hide();
                    $('.section' + cs).show();
                    $('.pages p').text("Page " + cs + " of " + nos);
                    if (cs == 1) {
                        $('.prev a').hide();
                    }
                }
            }
            event.preventDefault();
        });
        //get all anchor links and make them working with hidden content
        var sections = $('.section');
        var anchors = $('a[href*="#"]', sections);
        anchors.click(function(e) {
            var anchor = $(this);
            var href = anchor.attr('href');
            var index = href.indexOf('#');
            var bookmark = href.substring(index + 1);
            var aBookmark = sections.find('a[name=' + bookmark + ']:first');
            var section = aBookmark.parents('.section:first');
            var sectionIndex = sections.index(section);
            //alert(sectionIndex);
            cs = sectionIndex + 1;
            if (sectionIndex > -1) {
                if (cs == nos) {
                    $('.next a').hide();
                    $('.section').hide();
                    $('.section' + cs).show();

                    $(window).scrollTop(aBookmark.offset().top);

                    $('.pages p').text("Page " + cs + " of " + nos);
                } else if (cs < nos) {
                    $('.next a').show();
                    if (cs > 1) { $('.prev a').show(); }
                    $('.section').hide();
                    $('.section' + cs).show();

                    $(window).scrollTop(aBookmark.offset().top);

                    $('.pages p').text("Page " + cs + " of " + nos);
                }
            }
            e.preventDefault();
        });

    }
}



$(document).ready(function() {

    sectionsPagination();
    var contactFormToggle = {};

    contactFormToggle = {
        checkToggler: $("input.check_toggler"),
        init: function() {
            contactFormToggle.pageLoad();
            contactFormToggle.checkboxClick();
        },
        pageLoad: function() {
            var checkTriggers = $(contactFormToggle.checkToggler);
            /*	Loop through any instances of checkbox triggers 
            Find the hidden content related to this trigger
            Check if the checkbox is checked
            If it is checked hide the content
            If not show it 			
            */
            $(checkTriggers).each(function() {
                var myContent = $(this).parent().next(".toggle_content");
                var myCheckedState = $(this).attr("checked");
                if (myCheckedState != 0) {
                    $(myContent).hide();
                } else {
                    $(myContent).show();
                };
            });
        },
        checkboxClick: function() {
            /*	Get the checkbox which has been clicked
            Find the hidden content related to this trigger
            Check if the checkbox is checked
            If it is checked slide up the content
            If not slide down the content.
            */
            $(contactFormToggle.checkToggler).click(function() {
                var myContent = $(this).parent().next(".toggle_content");
                var myCheckedState = $(this).attr("checked");
                if (myCheckedState != 0) {
                    $(myContent).stop(true, true).slideUp('slow');
                } else {
                    $(myContent).stop(true, true).slideDown('slow');
                };

            });
        }
    }

    contactFormToggle.init();

    /* -- START TODO TEST POPULATE FIELDS - Delete once back end is hooked up -- */

    var timeData = $("input.time_data");

    var noTimeData = $("input.no_time_data");


    $(timeData).val("|id4;Farrier;3|id7;Forestry and timber worker;5|id3;Farmer;2");

    $(noTimeData).val("|id4;Foo|id7;Foo bar|id3;Bar foo bar");

    /* -- END TODO TEST POPULATE FIELDS - Delete once back end is hooked up -- */


    $("a.anchorLink").anchorAnimate();


    /*  Enquiry form 
    @lance.cooper
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
    var occupations = [];

    var enquiryForm = {};

    enquiryForm = {

        //Classnames used as listeners
        select: ".lightboxSelect",
        modalLink: ".addValues",
        modalClass: "modal",

        //Store if edit has been clicked
        editClicked: false,

        //Error messages to be displayed when form fails validation
        radioError: "<p class=\"errorMsg radio\" style=\"display:none\">Please select an occupation</p>",
        timeError: "<p class=\"errorMsg time\" style=\"display:none\">Please fill in Time at this occupation</p>",

        //Store validation details
        formOccValidated: false,
        formTimeValidated: false,

        //Store selected options to append to the main page
        occId: "",
        occText: "",
        occTime: "",

        //Store time input details
        timeInput: "timeInput", //if this classname is present on the original link it will return true
        showTimeInput: false, //time input will not display by default

        //The meta form used to submit the modal
        formWrapper: "meta",
        formTimeInput: "<label id=\"" + enquiryForm.timeInput + "\">How long in this occupation?*</label><input type=\"text\" class=\"textfield\" maxlength=\"2\" id=" + enquiryForm.timeInput + " /><span>years</span>",
        formSubmit: "<input type=\"button\" value=\"Add\" class=\"s-modal\" value=\"\" />",

        //Function that is called from the document ready
        init: function() {

            //Loop through each select and create a modal container at the bottom of the page for it
            $(enquiryForm.select).each(function() {
                enquiryForm.buildModal($(this));
            });

            //Hide selects
            $(".jsHide").hide();

            //Show modal links
            $(enquiryForm.modalLink).show();

            //Submit modal when Add is clicked       
            $("." + enquiryForm.formWrapper).find("input[type=button]").click(function(e) {

                //Determine whether timeInput is being used
                if ($(this).siblings().is("input:text")) {
                    enquiryForm.showTimeInput = true;
                }

                //Pass in the current modal to use later
                var modal = $(this).parent().parent("div");
                enquiryForm.validateModal(modal);

            });

            //Set variables depending on the link that was clicked
            $(enquiryForm.modalLink).find("a").click(function() {

                //Store the current clicked link to append content later
                enquiryForm.clickedLink = $(this);

            });



            // Execute Owens function
            enquiryForm.repopulate();

        },

        //This function will create a container at the bottom of the page, filled with radio boxes to load with a lightbox later
        buildModal: function(select) {

            //Store relationship to use as the modal ID
            var rel = select.attr("rel");

            //Set whether the time input should be shown or not
            if (select.hasClass(enquiryForm.timeInput)) {
                enquiryForm.showTimeInput = true;
            } else {
                enquiryForm.showTimeInput = false;
            };

            //Write a container to hold the modal
            $("body").append("<div id=\"" + rel + "\" class=\"" + enquiryForm.modalClass + "\" style=\"display:none\" />");

            //Cache the new div for use later
            var $modal = $("#" + rel);

            //Create and cache new container to handle the scrolling
            $modal.append("<div class=\"modal-content\"></div>");
            var $modalContent = $modal.find(".modal-content");

            //Prepend error messages to display if form fails validation
            $modalContent.prepend(enquiryForm.radioError, enquiryForm.timeError);

            //Loop through each option group to render it as a chunk of HTML
            select.find("optgroup").each(function(i) {

                //Store the label to use later as the title
                var title = $(this).attr("label");

                //Open container for each option group, store the index so the HTML goes in the right place
                $modalContent.append("<div class=\"optgroup opt" + i + "\" \>");

                //Store the group container to append items to
                var $optgroup = $modalContent.find(".opt" + i);

                //Travese the DOM and append the label variable as a heading
                $optgroup.append("<h3>" + title + "</h3>");

                //Find each option tag within the option group
                $(this).find("option").each(function() {
                    //Store variables to reference when we build our inputs
                    var radio = "<input type=\"radio\" name=\"occupation\" id=\"" + $(this).attr("value") + "\"/>";
                    var label = "<label for=\"" + $(this).attr("value") + "\">" + $(this).text() + "</label>";
                    //Traverse the DOM and append the radio button and label using the variables we have stored
                    $optgroup.append("<p>" + radio + label + "</p>");
                });

            });

            //Append submit form wrapper to bottom of modal
            $modal.append("<fieldset class=\"" + enquiryForm.formWrapper + "\"></fieldset>");

            //Append form inputs to form wrapper
            //Check if time inputs are required
            if (enquiryForm.showTimeInput) {
                $modal.find("." + enquiryForm.formWrapper).append(enquiryForm.formTimeInput)
            };
            $modal.find("." + enquiryForm.formWrapper).append(enquiryForm.formSubmit)

            //Ensure only numbers can be entered into the time field
            $(".meta input:text").numeric();

        },

        //Validate form - check if Time and Occupation are both selected
        validateModal: function(modal) {

            var modal = "#" + modal.attr("id");
            var $modal = $(modal);
            var $occInput = $(".optgroup input");
            var $timeInput = $(modal + " .meta input:text");
            enquiryForm.occTime = $timeInput.attr("value");

            //Validate occupational inputs
            $occInput.each(function() {

                //Check if checked
                var isChecked = $(this).is(":checked");

                //If checked
                if (isChecked) {

                    //Set form validation
                    enquiryForm.formOccValidated = true;

                    //Update id with this id
                    enquiryForm.occId = $(this).attr("id");

                    //Update occupation with this label
                    enquiryForm.occText = $(this).next("label").text();

                    //Break loop
                    return false;

                }

            });

            //Validate time input
            if (enquiryForm.occTime === "") {
                enquiryForm.formTimeValidated = false;
            } else {
                enquiryForm.formTimeValidated = true;
            }

            //If the time input isnt required, automatically let it pass validation
            if (enquiryForm.showTimeInput === false) {
                enquiryForm.formTimeValidated = true;
            }

            //Check if occupation and time are both validated
            if (enquiryForm.formOccValidated && enquiryForm.formTimeValidated) {

                //Close modal if both items are validated
                enquiryForm.closeModal(modal);

                //Add this item to the occupation list, pass values to build the list
                enquiryForm.createOccList(enquiryForm.occText, enquiryForm.occId, enquiryForm.occTime, true);

            } else {

                //Show and hide error messages depending on specific validation

                //Occupation list validation
                if (enquiryForm.formOccValidated) {
                    $modal.find(".errorMsg.radio").hide();
                } else if (enquiryForm.formOccValidated === false) {
                    $modal.find(".errorMsg.radio").show();
                    $modal.find(".modal-content").scrollTop("0px");
                }

                //Time validation
                if (enquiryForm.formTimeValidated) {
                    $modal.find(".errorMsg.time").hide();
                } else if (enquiryForm.formTimeValidated === false) {
                    $modal.find(".errorMsg.time").show();
                    $modal.find(".modal-content").scrollTop("0px");
                }

            }



        },

        closeModal: function(modal) {

            //Remove current selection
            $(".optgroup input:radio").attr("checked", false);
            $(".meta input:text").val("");
            $(".errorMsg.radio,.errorMsg.time").hide();

            //If edit has been clicked, remove the current selection from the DOM
            if (enquiryForm.editClicked) {

                //Remove current selection from the DOM because it is about to be replaced with an updated one
                $("p[rel=" + enquiryForm.editRel + "]").remove();

                //Reset edit being clicked
                enquiryForm.editClicked = false;

            }

            //Remove current validation
            enquiryForm.formOccValidated = false;
            enquiryForm.formTimeValidated = false;

            //Close modal window
            $("#TB_closeWindowButton").trigger("click");

        },

        createOccList: function(text, id, time, updateString) {

            var text = text;
            var id = id;
            var time = time;

            if (id != undefined && id != '') {

                //Build string to show current occupation
                if (enquiryForm.showTimeInput) {
                    var selection = "<p class=\"selection\" rel=\"" + id + "\"><span class=\"text\">" + text + "</span> - <span class=\"time\">" + time + "</span> years <a href=\"javascript:void(0)\" class=\"edit\">Edit</a> <a href=\"javascript:void(0)\" class=\"remove\">Remove</a></p>";
                } else {
                    var selection = "<p class=\"selection\" rel=\"" + id + "\"><span class=\"text\">" + text + "</span> <a href=\"javascript:void(0)\" class=\"edit\">Edit</a> <a href=\"javascript:void(0)\" class=\"remove\">Remove</a></p>";
                }

                //var occListName = $(":input", enquiryForm.clickedLink.parent(".addValues")).attr('name');

                var list;

                //Update page with selected items
                enquiryForm.clickedLink.parent(".addValues").before(selection);

                //Reset timeInput
                enquiryForm.showTimeInput = false;

                //Apply clicks to buttons
                enquiryForm.removeOcc();
                enquiryForm.editOcc();

                //Update our hidden values to send to the server
                var selectionInput = enquiryForm.clickedLink.siblings("input");

                if (updateString) {
                    enquiryForm.updateString(selectionInput);
                }

            }

        },
        repopulate: function() {

            var $hiddenInputs = $(".addValues input.hidden_data");


            $($hiddenInputs).each(function() {
                var $_this = $(this);
                var $myVal = $($_this).val();
                //Find the previous <a> tag and store it in clickedLink
                enquiryForm.clickedLink = $($_this).prev("a");

                var valueArray = $($_this).val().split("|");

                valueArray.shift();

                for (var i in valueArray) {
                    var ItemArray = valueArray[i].split(";");
                    var id = ItemArray[0];
                    var text = ItemArray[1];
                    if (ItemArray[2] != undefined) {
                        var time = ItemArray[2];
                        enquiryForm.showTimeInput = true;
                    } else {
                        enquiryForm.showTimeInput = false;
                    }
                    enquiryForm.createOccList(text, id, time, false);
                }

                /*
                for(var i in valueArray) {
                var ItemArray = valueArray[i].split(",");	
                var id = ItemArray[0];
                var text = ItemArray[1];
                var time = ItemArray[2];
					
					
					//enquiryForm.createOccList(id, text, time);
                }
                */
            });

        },
        // owens: function() {


        // //$(".addValues input").each(){

        // //if(value is empty) {

        // //get the value

        // //Find the previous <a> tag and store it in clickedLink
        // //eg: clickedLink = $(this).previous("a");

        // var valueArray = $("input").val().split("|");

        // for(var i in valueArray) {

        // var ItemArray = valueArray[i].split(",");

        // //For each value, use a regular expression to seperate variables as below
        // //var text = ItemArray[0];
        // //var id = ItemArray[1];
        // //var time = ItemArray [2];

        // //createOccList(text, id, time);

        // }

        // //valuevar.split("|");

        // //In that array, loop through it {

        // /

        // //}

        // //}

        // },

        removeOcc: function() {

            //Remove occupation when remove is clicked
            $("p.selection .remove").click(function() {

                //Get the hidden input so we can access it later
                var selectionInput = $(this).parent("p").siblings(".addValues").children("input");

                //Remove our selection from the DOM
                $(this).parent("p").remove();

                //After the item is removed from the DOM run updateString
                enquiryForm.updateString(selectionInput);

            });



        },

        editOcc: function() {

            $("p.selection .edit").click(function() {

                //Let everyone know that edit has been clicked
                enquiryForm.editClicked = true;

                //Update the current click linked to this
                enquiryForm.clickedLink = $(this);

                //Store current variables to use later
                enquiryForm.editRel = $(this).parent().attr("rel");
                var occId = "#" + $(this).parent().attr("rel");
                var occTime = $(this).siblings(".time").text();

                //Open modal
                $(this).parent("p").siblings(enquiryForm.modalLink).find("a").trigger("click");

                //Set inputs to current options
                $(occId).attr("checked", true);
                $(".meta input:text").val(occTime);

                //Get the 3 input so we can access it later
                var selectionInput = $(this).parent("p").siblings(".addValues").children("input");

                //After the item is removed from the DOM run updateString
                enquiryForm.updateString(selectionInput);

            });

        },

        updateString: function(selectionInput) {

            var $selectionInput = selectionInput;

            //Clear the current value so we can rebuild it with the current selection
            $selectionInput.attr("val", "");

            //Give our newValue scope
            var newValue = '';

            //If .selection doesnt exist, we want to keep the value empty
            if ($selectionInput.parent().parent().children(".selection").length === 0) {

                //If no items are selected, make the newVal empty
                var newValue = '';

            } else {

                //Iterate through each selection and add relevant data to the string
                $selectionInput.parent().parent().children(".selection").each(function() {

                    //Store our variables so we can send them to the input value
                    var valId = $(this).attr("rel");
                    var valText = $(this).children(".text").text();
                    var valTime = $(this).children(".time").text();

                    //Check if valTime exists, because its only on a few selections
                    if (valTime) {
                        //Add to the newValue which is currently looping through
                        newValue += "|" + valId + ";" + valText + ";" + valTime;
                    } else {
                        //Add to the newValue which is currently looping through
                        newValue += "|" + valId + ";" + valText;
                    }

                });

            }

            //Updatae the input value on each iteration
            $selectionInput.attr("value", newValue);

        }

    };

    //Initialise enquiry form
    enquiryForm.init();

});

jQuery.fn.anchorAnimate = function(settings) {

    settings = jQuery.extend({
        speed: 100
    }, settings);

    return this.each(function() {

        var caller = this;

        $(caller).css({ 'border': '5px solid red' });

        $(caller).click(function(event) {
            event.preventDefault();
            var locationHref = window.location.href;
            var elementClick = $(caller).attr("href");

            alert(elementClick);
            
            if ($(elementClick).size()) {
                var destination = $(elementClick).offset().top;
                $("html:not(:animated),body:not(:animated)").animate({ scrollTop: destination }, settings.speed, function() {
                    window.location.hash = elementClick;
                });
            }
            return false;
        })
    })
}





