$(document).ready(function()
{

    //help
    $(".help").helpToggle();
    


    //add enhance stylesheet
    var root = $('script[@src*="_assets/"]:eq(0)').attr('src').split('_assets')[0];
    $('head link:eq(0)').after('<link rel="stylesheet" type="text/css" media="screen" href="' + root + '_assets/css/enhance.css" />');


    //big links
    $(".quicklink").hover(function()
    {
        $(this).css("background-position", "0 100%");
        $(this).find("a").css("color", "#0099FE");
    }, function()
    {
        $(this).css("background-position", "-285px 100%");
        $(this).find("a").css("color", "#0067B6");
    })
    .bigLink();

    //toggle help
    $(".faqs dl").toggleList();

    //rounded corners
    $("div.help, .application-sections li.listing, .sign-in, .message, #iBody, .filtered-list, .quote, #iQuicklinks .related, .highlightB, .group, .tariff-list, .highlight, .area-activity, .parish, .case-studies, .case-study, .contact, .task-list, .latest-list, .package-summary").roundedCorners(true);
    $("#iPrefHelp .information, .type-summary .summary").roundedCorners(false);
    $("#iNavL2 h2").roundedCorners(true, 1);
    $("#iPreferences .footer").roundedCorners(true, 2);
    $(".area-list .active").roundedCorners(true, 3);

    //date picker
    $('#idOfFormRow').dateHelper(
	{
	    linkId: 'iDate',  // dynamic a tag, can be any unique id
	    selectDayId: '#iSelect_dd',
	    selectMthId: '#iSelect_mm',
	    selectYrId: '#iSelect_yyyy'
	});

    //form panels
    $(".form").accordian();
});

/**
jQuery extension - hide show of help panels
*/
$.fn.helpToggle = function(arg)
{
    $(this).prev(".information").addClass("js-hide");
    $(this).click(function(e)
    {
        e.preventDefault();
        $(this).prev(".information").toggleClass("js-hide");
    })
}

/**
jQuery extension - add remove of sections
*/
$.fn.addRemove = function(arg)
{
    var stringName = arg;
    var className = $(this).attr("class");

    $(this).prepend("<div class='remove'><a href='#'>Remove " + stringName + "</a></div>");
    $(this).parent("fieldset").append("<div class='add'><a href='#'>Add another " + stringName + "</a></div>");

    $("." + className + ":not(:first)").find(".frmRow").addClass("js-hide");
    $("." + className + ":not(:first) .date").addClass("js-hide");
    $("." + className + " .remove:not(:first)").addClass("js-hide");

    var elemLength = $("." + className).length;
    var elemOpen = 1;

    $(this).parent("fieldset").find(".add a").click(function(e)
    {
        e.preventDefault();
        elemOpen += 1;
        if (elemOpen == elemLength)
        {
            $(this).parent(".add").addClass("js-hide");
        }
        $("." + className).each(function()
        {
            if ($(this).find(".frmRow").hasClass("js-hide") == true)
            {
                $(this).find(".frmRow").removeClass("js-hide").siblings(".remove").removeClass("js-hide");
                $(this).find(".date").removeClass("js-hide");
                return false;
            }
        })
    });

    $(this).find(".remove a").click(function(e)
    {
        e.preventDefault();
        elemOpen += -1;
        $(this).parent(".remove").addClass("js-hide").siblings(".frmRow").addClass("js-hide");
        $(this).parent(".remove").siblings(".date").addClass("js-hide");

        if (elemOpen < elemLength)
        {
            $(this).parent(".remove").parent("fieldset").siblings(".add").removeClass("js-hide");
        }
    });
}

/**
jQuery extension - adds rounded corners to elements

@param [noIe] boolean selector to determine whether to set corners on ie6
@param [bottomOnly] boolean selector to only add the bottom two corners
*/
$.fn.roundedCorners = function(/**Bool*/noIe, /**int*/corners)
{
    var ie6 = $.browser.msie && $.browser.version < 7;
    if (ie6 && noIe)
    {
        $(this).each(function()
        {
            var pb, pt, pl, pr;
            ($(this).css("padding-bottom") == "auto") ? pb = "1px" : pb = (parseInt(pb) + 1) + "px";
            ($(this).css("padding-top") == "auto") ? pt = "1px" : pt = (parseInt(pt) + 1) + "px";
            ($(this).css("padding-left") == "auto") ? pl = "1px" : pl = (parseInt(pl) + 1) + "px";
            ($(this).css("padding-right") == "auto") ? pr = "1px" : pr = (parseInt(pr) + 1) + "px";

            var padding = "padding: " + pt + " " + pr + " " + pb + " " + pl + ";";

            if (corners == 1)
            {
                $(this).prepend('<span class="tl"></span>');
            }
            else if (corners == 2)
            {
                $(this).css("padding", "0");
                $(this).wrapInner('<div class="iebr" style="float:left;z-index:10;position:relative;margin:0 -1px -1px 0"><div class="iebl" style="float:left;padding:3px 10px 6px 7px;margin:0 0 0 -1px;z-index:9;position:relative;"></div></div>');
            }
            else if (corners == 3)
            {
                $(this).css("padding", "0 0 0 1px");
                $(this).wrapInner('<div class="tl" style="margin:-1px 0 0 -1px;z-index:10;border:none;padding:0;float:left;width:auto;height:auto;top:0;left:0;background-position:0 0;"><div class="tr" style="margin:0 -1px 0 0;padding:0;border:none;float:left;width:auto;height:auto;top:0;left:0;background-position:100% 0;"><div class="br" style="margin:0 0 -1px 0;z-index:10;border:none;padding:10px 6px 10px 9px;float:left;width:136px;height:auto;top:0;left:0;background-position:100% 100%;"></div></div></div>');
            }
            else
            {
                $(this).wrapInner("<div class='ietr' style='zoom:1;z-index:999;position:relative;margin-right:-1px;margin-top:-1px;'><div class='ietl' style='zoom:1;z-index:999;position:relative;margin-left:-1px;'><div class='iebr' style='zoom:1;z-index:999;position:relative;margin-bottom:-1px;'><div class='iebl' style='z-index:998;position:relative;zoom:1;height:1%;" + padding + "'></div></div></div></div>");
                $(this).css({ "padding-top": "0",
                    "padding-bottom": "0",
                    "padding-left": "0",
                    "padding-right": "0"
                });
            }
        })

    }
    if (!ie6)
    {
        if (corners == 2)
        {
            $(this).append('<span class="bl"></span><span class="br"></span>');
        }
        else if (corners == 3)
        {
            $(this).append('<span class="tl"></span><span class="tr"></span><span class="br"></span>');
        }
        else if (corners == 1)
        {
            $(this).prepend('<span class="tl"></span>');
        }
        else
        {
            $(this).append('<span class="tl"></span><span class="tr"></span><span class="bl"></span><span class="br"></span>');
        }

    }
}

/**
jQuery extension - tabbing with radio buttons
*/
$.fn.tabs = function()
{
    $(this).find(":radio").each(function(i)
    {
        //add class to all options
        $(".opt" + i).addClass("tabOption");
        
        //check if option is shown
        console.log($(this).is(":checked"));
        ($(this).is(":checked")) ? $(this).parents("li").addClass("selected") : $(this).parents("li").removeClass("selected").parents(".frmConditional").find(".opt" + i).addClass("js-hide");

        $(this).click(function()
        {
            $(".tabOption").each(function()
            {
                ($(this).hasClass(".opt" + i)) ? $(this).removeClass("js-hide") : $(this).addClass("js-hide");
            })

            $(this).parents("li").addClass("selected").siblings("li").removeClass("selected");
        })
    })
}

/**
jQuery extension - Add accordian functionallity to a group of form items
*/
$.fn.accordian = function()
{
    $(this).find(".frmSection .container:not(:first)").addClass("js-hide");
    $(this).find("h2").wrapInner("<a class='js-toggle' href='#'></a>");
    $(this).find(".footer").html("<a class='js-toggle-next' href='#'>open next section</a>");

    $(".js-toggle").click(function(e)
    {
        e.preventDefault();
        if ($(this).parents(".frmSection").find(".container").hasClass("js-hide") == true)
        {
            $(this).parents(".frmSection").find(".container").removeClass("js-hide");
            var pos = $(this).parents(".frmSection").position();
            $('html, body').animate({ scrollTop: pos.top + 50 }, 500);
        }
        else
        {
            $(this).parents(".frmSection").find(".container").addClass("js-hide");
        }

    });

    $(".js-toggle-next").click(function(e)
    {
        e.preventDefault();
        $(this).parents(".frmSection").next().find(".container").removeClass("js-hide");
        var pos = $(this).parents(".frmSection").next().position();
        $('html, body').animate({ scrollTop: pos.top + 50 }, 500);
    })
}

/**
jQuery extension - Add hide show functionallity to a data list of q and a's
*/
$.fn.toggleList = function()
{
    $(this).find("dd").addClass("js-hide").end()
    .find("dt").addClass("js-closed").wrapInner("<a href='#'></a>")
    .find("a").click(function(e)
    {
        e.preventDefault();
        $(this).parent("dt").toggleClass("js-closed").next("dd").toggleClass("js-hide");
    });
}

/**
jQuery extension - Create a large clickable area from a hyperlink, when clicked the hyperlink click event is invoked.
	
@param [selector] An optional jQuery selector string pointing the link you wish to 'make big', if ommitted it will use the first hyperlink within the element
*/
$.fn.bigLink = function(/**String*/selector)
{
    var link = selector ? $(selector) : this.find('a[@href]:eq(0)');

    this.click(function()
    {
        // the first link within the supplied element
        var prevent_default = false;

        // check through all click events to for preventDefault command
        var all_events = link.data('events');
        var click_events;

        if (all_events && all_events.click)
        {
            click_events = all_events.click;

            for (var k in click_events)
            {
                if (/\.preventDefault\(\)/.test(click_events[k].toString()))
                {
                    prevent_default = true;
                }
            }
        }

        // trigger all jquery assigned events
        link.triggerHandler('click');

        // if preventDefault has never been assigned to this link then it is safe to do a standard redirect
        if (!prevent_default)
        {
            document.location = link.attr('href');
        }
    })
	.css('cursor', 'pointer');
}

/**
jQuery plugin extension which adds inline date selection
*/
jQuery.fn.dateHelper = function(attr)
{
    if (this.length == 0) return this;

    var containingId = "#" + this.attr("id");

    //add link
    $(containingId + " .frmElement:last").after('<a id="' + attr.linkId + '" href="#" class="dp-applied dateSelector">Select date</a>');

    $('#' + attr.linkId).click(function(e) { e.preventDefault(); });

    //get the start end dates	
    var endDd = $(attr.selectDayId + ' option:last').val();
    var endMm = $(attr.selectMthId + ' option:last').val();
    var endYyyy = $(attr.selectYrId + ' option:last').val();
    var endDate = endDd + "/" + endMm + "/" + endYyyy;
    var startDd = $(attr.selectDayId + ' option:first').val();
    if (startDd.length === 1) startDd = "0" + startDd;
    var startMm = $(attr.selectMthId + ' option:first').val();
    if (startMm.length === 1) startMm = "0" + startMm;
    var startYyyy = $(attr.selectYrId + ' option:first').val();
    var startDate = startDd + "/" + startMm + "/" + startYyyy;

    $('#' + attr.linkId)
		.datePicker(
    // associate the link with a date picker
			{
			createButton: false,
			startDate: startDate,
			endDate: endDate

            }
		).bind(
    // when the link is clicked display the date picker
			'click',
			function()
			{
			    //updateSelects($(this).dpGetSelected()[0]);
			    updateSelects($(attr.selectMthId).val() + '/' + $(attr.selectDayId).val() + '/' + $(attr.selectYrId).val());
			    $(this).dpDisplay();
			    return false;
			}
		).bind(
    // when a date is selected update the SELECTs
			'dateSelected',
			function(e, selectedDate, $td, state)
			{
			    updateSelects(selectedDate);
			}
		).bind(
			'dpClosed',
			function(e, selected)
			{
			    updateSelects(selected[0]);
			}
		);

    var updateSelects = function(selectedDate)
    {
        selectedDate = new Date(selectedDate);
        var d = selectedDate.getDate();
        var m = selectedDate.getMonth();
        var y = selectedDate.getFullYear();
        ($(attr.selectDayId)[0]).selectedIndex = d - 1;
        ($(attr.selectMthId)[0]).selectedIndex = m;
        ($(attr.selectYrId)[0]).selectedIndex = y - startYyyy;

        $(attr.selectDayId + ", " + attr.selectMthId + ", " + attr.selectYrId).trigger("change");
    }
    // listen for when the selects are changed and update the picker
    $(attr.selectDayId + ", " + attr.selectMthId + ", " + attr.selectYrId)
		.bind(
			'change',
			function()
			{
			    var d = new Date(
							$(attr.selectYrId).val(),
							$(attr.selectMthId).val() - 1,
							$(attr.selectDayId).val()
						);
			    $('#' + attr.linkId).dpSetSelected(d.asString());
			}
		);

    // default the position of the selects to today

    var today = new Date();

    ($(attr.selectDayId)[0]).selectedIndex = today.getDate() - 1;
    ($(attr.selectMthId)[0]).selectedIndex = today.getMonth();
    ($(attr.selectYrId)[0]).selectedIndex = today.getFullYear() - 2005;


    // and update the datePicker to reflect it...
    $(attr.selectDayId + ", " + attr.selectMthId + ", " + attr.selectYrId).trigger("change")
    $(attr.selectDayId).trigger('change');
}


/**
jQuery extension - ready reckoner
*/
$.fn.toggleResult = function()
{
    var result = $(this).find("div.result").addClass("js-hide");
    $(this).find(":submit").click(function()
    {
       
      result.slideToggle();
      return false;
    })
}

