$(document).ready(function()
{
    /*
    preload images
    */
    $.preloadImages("buttons/imgBtnPrimaryOver.png", "buttons/imgBtnArrowPrimaryOver.png");

    /*
    open in new window
    */
    $(".newWindow").click(function(e)
    {
        window.open(this.href);
        return false;
    });

    /*  
    Tabs through the various sort code fields 
    */
    function WireAutoTab(CurrentElementID, NextElementID, FieldLength)
    {
        //Get a reference to the two elements in the tab sequence.
        var CurrentElement = $('#' + CurrentElementID);
        var NextElement = $('#' + NextElementID);


        CurrentElement.keyup(function(e)
        {
            //Retrieve which key was pressed.
            var KeyID = (window.event) ? event.keyCode : e.keyCode;
            if (CurrentElement.val().length == FieldLength)
            {
                NextElement.focus();
            } else
            {
                if (CurrentElement.val().length < FieldLength && KeyID == 9)
                {
                    return false;
                }
            }
        });
    }
    WireAutoTab('ctl00_ctl00_Main_Main_iIssueDate_1', 'ctl00_ctl00_Main_Main_iIssueDate_2', 2);
    WireAutoTab('ctl00_ctl00_Main_Main_iExpireDate_1', 'ctl00_ctl00_Main_Main_iExpireDate_2', 2);

    /*
    3d secure
    */
    if ($('#iPrimary').hasClass('3dFinal'))
    {
        $('body').css("background", "#fff");
        $("form").submit();
    }
    if ($('#iPrimary').hasClass('3d'))
    {
        $('#i3dSecure').hide();
        $('#form').attr('target', 'i3DIFrame');
        $('#iHide').show();
        $("<div id='iOverlay'></div>").insertAfter($("#iPage")).css({
            width: '100%',
            height: '100%',
            opacity: '0.6',
            background: '#000',
            position: ($.browser.msie && $.browser.version < 7) ? 'absolute' : 'fixed',
            top: '0',
            left: '0',
            zIndex: '99'
        });
        $('<div id="i3d" class="panel"></div>').insertAfter('#iOverlay').css({
            opacity: '1',
            width: '430px',
            height: '540px',
            position: 'absolute',
            left: '50%',
            zIndex: '998',
            marginTop: '-280px',
            marginLeft: '-215px',
            overflow: 'visible',
            top: '50%',
            border: '1px solid #BED7DF',
            fontSize: '125%',
            fontFamily: 'Verdana'
        });
        $('<h2 class="header alpha secure"><span>3D Secure</span></h2><p class="intro" style="margin:10px">Do not click the Refresh or Back button or this transaction may be interrupted.</p><iframe id="i3DIFrame" name="i3DIFrame" frameborder="0" scrolling="no" allowtransparency="true"> </iframe>').appendTo('#i3d');
        $('html, body').css({ overflow: 'hidden', height: '100%' });
        $("form").submit();
    }

    /*
    ie fix for button hover
    */
    if ($.browser.msie && $.browser.version == 6)
    {
        //button size fix
        $(".defaultBtn input, .arrowBtn input, .standardLnk").each(function(i)
        {
            var scrWid = document.getElementById($(this).attr("id")).scrollWidth + "px"
            $(this).css("overflow", "hidden").width(scrWid);
        });
        //button mouseover fix
        $(".defaultBtn input").mouseover(function()
        {
            $(this).parents(".defaultBtn").addClass("defaultBtnOver");
        }).mouseout(function()
        {
            $(this).parents(".defaultBtn").removeClass("defaultBtnOver");
        });
        $(".arrowBtn input").mouseover(function()
        {
            $(this).parents(".defaultBtn").addClass("arrowBtnOver");
        }).mouseout(function()
        {
            $(this).parents(".defaultBtn").removeClass("arrowBtnOver");
        });
    }

    /*
    questions dropdown
    */
    $('.questions dd.faq').addClass("closed");
    //add a tag to list items
    $('.questions dt.faq').addClass("closed").wrapInner("<a href='#'></a>");
    $('.questions dt.faq a').click(function(e)
    {
        e.preventDefault();
    });
    //keep first item open or open linked to item
    var urlString = window.location.href.split("#")[1];
    if (urlString !== undefined && !!$('#' + urlString).length)
    {
        $('#' + urlString + ' a:first').parent().removeClass("closed").next().removeClass("closed");
    }
    else
    {
        $('.questions dt.faq a:first').parent().removeClass("closed").next().removeClass("closed");
    }

    $('.questions dt.faq a').click(function()
    {
        if ($(this).parent().hasClass("closed"))
        {
            $(this).parent().removeClass('closed').next().removeClass("closed");
        }
        else
        {
            $(this).parent().addClass('closed').next().addClass("closed");
        }
    });

    /*
    print
    */
    $(".print").show().click(function(e)
    {
        e.preventDefault();
        window.print();
    });

    /*
    replace dropdown boxes for cross browser support
    */
    $('.select select').dropdown(
	{
	    inputClass: 'frmSelectBox ', //css class for the input which will replace the select tag, display the background image  
	    containerClass: 'frmSelectBoxOptions', // The list container class (a div element)  
	    hoverClass: 'current', // css class for the current element  
	    currentClass: 'selected', // css class for the selected element  
	    boxWidth: '276px' //safari fix
	});

    /*
    validation
    */
    $(".validate").think_validation({
        formId: "#aspnetForm",
        urlString: window.location.href, //live data
        mainMessageBlock: "err",
        parentMessageClass: "inline", // form row class containing message
        successClass: "successMessage", // inline class for success
        errorClass: "errorMessage" // inline class for error
    });

    /*
    form helpers
    */
    $('.helpPanel').each(function(i)
    {
        $(this).wrap('<div id="iHigh_' + i + '" class="helpArea"></div>');
        $(this).find('select, input').each(function()
        {
            $(this).addClass('clickable');
        });
    });
    $('.clickable').data("position", true).addHelpPanel();
    $("#ctl00_ctl00_Main_Main_iCustNo").data("position", false);

    /*
    payment card selector
    */
    if ($("#iSelectPayment").length)
    {
        $("#iSelectPayment .frmSelect, .mss, #iPayment, .cardAccess").hide();
        $('#iSelectPayment').css({ marginBottom: "0", marginBottom: "0" });
        $("#iTabPayment").css({ display: "block" });

        var tabs = $('#iVisaLnk,#iVisaElecLnk,#iMasterLnk,#iMaestroLnk,#iSwitchLnk');

        function mssDisplay(arg, cardType)
        {
            if ($("#iPayment .intro").length)
            {

                $("#iPayment .intro").html("Enter your <strong>" + cardType + "</strong> details below.");
            }
            else
            {
                $("#iPayment").prepend("<p class='intro'>Enter your <strong>" + cardType + "</strong> details below.</p>");
            }
            if (arg)
            {
                $('.mssOnly').show();
                $('#iIssue, #iIssueDate_2, #iExpireDate_2').addClass("validate");
            }
            else
            {
                $('.mssOnly').hide();
                $('#iIssue, #iIssueDate_2, #iExpireDate_2').removeClass("validate");
            }
        };

        tabs.click(function(e)
        {
            e.preventDefault();
            $("#iPayment, .cardAccess").show();
            $(this).parent().siblings().removeClass("here").end().addClass("here");

            switch (this.id)
            {
                case 'iVisaLnk':
                    $("#iSelectPayment .frmSelect").val("1");
                    mssDisplay(false, "visa");
                    break;
                case 'iVisaElecLnk':
                    $("#iSelectPayment .frmSelect").val("2");
                    mssDisplay(false, "visa electron");
                    break;
                case 'iMasterLnk':
                    $("#iSelectPayment .frmSelect").val("3");
                    mssDisplay(false, "mastercard");
                    break;
                case 'iMaestroLnk':
                    $("#iSelectPayment .frmSelect").val("4");
                    mssDisplay(true, "maestro");
                    break;
                case 'iSwitchLnk':
                    $("#iSelectPayment .frmSelect").val("6");
                    mssDisplay(true, "switch");
                    break;
            };
        });
        //check if payment form should be open
        var flagOpen = false;
        $("#iPayment input").each(function()
        {
            if ($(this).val().length > 0) flagOpen = true;
        });
        if ($(".inline").length || flagOpen)
        {
            switch ($("#iSelectPayment .frmSelect").val())
            {
                case "1":
                    $("#iVisaLnk").click();
                    break;
                case "2":
                    $("#iVisaElecLnk").click();
                    break;
                case "3":
                    $("#iMasterLnk").click();
                    break;
                case "4":
                    $("#iMaestroLnk").click();
                    break;
                case "6":
                    $("#iSwitchLnk").click();
                    break;
            }
        }
    }
});

/**
jQuery plugin extensionpreloads any images to stop flickr
*/
jQuery.preloadImages = function()
{
    for (var i = 0; i < arguments.length; i++)
    {
        jQuery("<img>").attr("src", "/_assets/css/images/" + arguments[i]);
    }
}

/**
jQuery plugin extension which adds context driven help
*/
jQuery.fn.addHelpPanel = function()
{
    //hide unwanted help
    $(".assist").hide();
    //reset help area
    function cleanUp()
    {
        $('.helpArea').removeClass("highlight");
        $('.helpArea').children('.frmRow').css({ background: 'transparent' });
        //show secondary panels
        $("#iSecondary .panel").show();
        //hide help panel
        $(".assist").hide();
    }
    //stop click closing help
    $('.helpArea, .assist, .helpArea a, .assist a')
	.click(function(e)
	{
	    e.stopPropagation();
	})
	.focus(function(e)
	{
	    e.stopPropagation();
	});
    $('#ctl00_ctl00_Main_Main_btnLogin').click(function(e)
    {
        e.stopPropagation();
    })
    //fire clean up
    $("input:text").focus(cleanUp);
    $('body').click(cleanUp);

    $(this).focus(function()
    {
        //hide secondary panels
        $("#iSecondary .panel").hide();

        if ($(this).parents('.helpArea').length)
        {
            var i = $(this).parents('.helpArea').attr('id').split('_')[1];
        }

        //hide first help panel
        $(".assist:eq(" + i + ")").show();
        $('#iHigh_' + i).addClass("highlight").children('.frmRow').css({ background: '#fff' });

        if ($(this).data('position'))
        {
            var panelFrmTopWin = $(this).parent(".frmRow").offset().top;
            var secFrmTopWin = $("#iSecondary").offset().top;
            var secHeadHeight = $(".assist:eq(" + i + ") h3.header").height();
            //set margin on help panel
            var resultPos = panelFrmTopWin - (secFrmTopWin + secHeadHeight + 30);

            $(".assist:eq(" + i + ")").css({ marginTop: resultPos + 'px' });
        }
    });

}

/**
jQuery plugin dropdown enhance
*/
jQuery.fn.extend({
    dropdown: function(options)
    {
        return this.each(function()
        {
            new jQuery.dropdownbox(this, options);
        });
    }
});

jQuery.dropdownbox = function(selectobj, options)
{

    //set default options
    var opt = options || {};
    opt.inputClass = opt.inputClass || "dropdownbox";
    opt.containerClass = opt.containerClass || "dropdownbox-wrapper";
    opt.hoverClass = opt.hoverClass || "current";
    opt.currentClass = opt.selectedClass || "dropHere"

    var elm_id = selectobj.id;
    var active = 0;
    var inFocus = false;
    var hasfocus = 0;
    //jquery object for select element
    var $select = $(selectobj);
    // jquery container object
    var $container = setupContainer(opt);
    //jquery input object 
    var $input = setupInput(opt);
    // hide select and append newly created elements
    $select.hide().before($input).before($container);

    init();

    $input
	.click(function()
	{
	    if (!inFocus)
	    {
	        $container.hide();
	        inFocus = true;
	    }
	    else
	    {
	        $container.show();
	        inFocus = false;
	    }
	})
	.focus(function()
	{
	    if ($container.not(':visible'))
	    {
	        $container.show();
	        inFocus = true;
	    }
	})
	.keydown(function(event)
	{
	    switch (event.keyCode)
	    {
	        case 38: // up
	            event.preventDefault();
	            moveSelect(-1);
	            break;
	        case 40: // down
	            event.preventDefault();
	            moveSelect(1);
	            break;
	        case 13: // return
	            event.preventDefault();
	            $('li.' + opt.hoverClass).trigger('click');
	            break;
	        case 27: //escape
	            hideMe();
	            break;
	    }
	})
	.blur(function()
	{
	    if ($container.is(':visible') && hasfocus > 0)
	    {
	        return false;
	    }
	    else
	    {
	        if ($.browser.msie)
	        {
	            if (document.activeElement.getAttribute('id').indexOf('_container') == -1)
	            {
	                hideMe();
	            }
	            else
	            {
	                $input.focus();
	            }
	        }
	        else
	        {
	            hideMe();
	        }
	    }
	});

    function hideMe()
    {
        hasfocus = 0;
        $container.hide();
    }

    function init()
    {
        $container.append(getSelectOptions($input.attr('id'))).hide();
        var width = $input.css('width');
        $container.width(opt.boxWidth);

        //add css
        var selectHeight = $("#" + elm_id + "_input").outerHeight();
        $container.css({
            position: "absolute",
            zIndex: "999",
            marginTop: selectHeight + "px"
        });
        //browser hacks to allow positioning of deropdown
        if (jQuery.browser.safari)
        {
            var mt = $("#" + elm_id + "_input").css("marginTop");
            var mb = $("#" + elm_id + "_input").css("marginBottom");
            var pt = $("#" + elm_id + "_input").css("paddingTop");
            var pb = $("#" + elm_id + "_input").css("paddingBottom");

            var safHeight = selectHeight + parseInt(mt) + parseInt(mb) + parseInt(pt) + parseInt(pb) + 2;

            $container.css("marginTop", safHeight + "px");
        }
        if (jQuery.browser.msie)
        {
            if (jQuery.browser.version.substr(0, 1) == 7)
            {
                var selectWidth = $("#" + elm_id + "_input").outerWidth();
                var marRight = $("#" + elm_id + "_input").css("marginRight");
                var marLeft = $("#" + elm_id + "_input").css("marginLeft");
                var newSelectWidth = selectWidth + parseInt(marRight) + parseInt(marLeft);
                $container.css("marginLeft", "-" + newSelectWidth);
                $container.css("marginTop", "26px");
            }
            else
            {
                $container.css("marginTop", "0");
            }
        }
    }

    function setupContainer(options)
    {
        var container = document.createElement("div");
        $container = $(container);
        $container.attr('id', elm_id + '_container');
        $container.addClass(options.containerClass);

        return $container;
    }

    function setupInput(options)
    {
        var input = document.createElement("input");
        var $input = $(input);
        $input.attr("id", elm_id + "_input");
        $input.attr("type", "text");
        $input.addClass(options.inputClass);
        $input.attr("autocomplete", "off");
        $input.attr("readonly", "readonly");
        $input.attr("tabIndex", $select.attr("tabindex"));

        return $input;
    }

    function moveSelect(step)
    {
        var lis = $("li", $container);
        if (!lis || lis.length == 0) return false;
        active += step;
        if (active < 0)
        {
            active = lis.size();
        }
        else if (active > lis.size())
        {
            active = 0;
        }
        scroll(lis, active);
        lis.removeClass(opt.hoverClass);

        $(lis[active]).addClass(opt.hoverClass);
    }

    function scroll(list, active)
    {
        var el = $(list[active]).get(0);
        var list = $container.get(0);

        if (el.offsetTop + el.offsetHeight > list.scrollTop + list.clientHeight)
        {
            list.scrollTop = el.offsetTop + el.offsetHeight - list.clientHeight;
        }
        else if (el.offsetTop < list.scrollTop)
        {
            list.scrollTop = el.offsetTop;
        }
    }

    function setCurrent()
    {
        var li = $("li." + opt.currentClass, $container).get(0);
        var ar = ('' + li.id).split('*');
        var el = ar[ar.length - 1];
        $select.val(el);
        $input.val($(li).html());
        $select.trigger('blur');
        return true;
    }

    // select value
    function getCurrentSelected()
    {
        return $select.val();
    }

    // input value
    function getCurrentValue()
    {


        return $input.val();
    }

    function getSelectOptions(parentid)
    {
        var select_options = new Array();
        var ul = document.createElement('ul');
        $select.children('option').each(function()
        {
            var li = document.createElement('li');
            li.setAttribute('id', parentid + '*' + $(this).val());
            li.innerHTML = $(this).html();
            if ($(this).is(':selected'))
            {
                $input.val($(this).html());
                $(li).addClass(opt.currentClass);
            }
            ul.appendChild(li);
            $(li)
			.mouseover(function(event)
			{
			    hasfocus = 1;
			    jQuery(event.target, $container).addClass(opt.hoverClass);
			})
			.mouseout(function(event)
			{
			    hasfocus = -1;
			    jQuery(event.target, $container).removeClass(opt.hoverClass);
			})
			.click(function(event)
			{
			    var fl = $('li.' + opt.hoverClass, $container).get(0);
			    $('li.' + opt.currentClass).removeClass(opt.currentClass);
			    $(this).addClass(opt.currentClass);
			    setCurrent();
			    $select.get(0).blur();
			    hideMe();
			});
        });
        return ul;
    }

    $($select).change(function()
    {
        getSelectOptions(); //set the ul if the select changes
    });
};

/**
jQuery plugin think validation
*/
jQuery.fn.think_validation = function(vOptions)
{
    //validation
    function isValid(fieldToValidate)
    {
        var postData = $(vOptions.formId).serialize() + "&validate_json_request=true&validate_json_field=" + fieldToValidate; //live data

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: vOptions.urlString,
            data: postData,
            dataType: "json",
            contentType: "application/x-www-form-urlencoded",
            error: function(errorData, errorData1)
            {
                return false;
            },
            success: function(returnedData)
            {
                var fieldId = returnedData.validation.field[0].field_id;
                var inlineMess = returnedData.validation.field[0].message;
                var success = returnedData.validation.field[0].sucess;

                inlineMessage(fieldId, inlineMess, success);
            }
        });
    };

    //display inline message next to field
    function inlineMessage(fieldId, inlineMess, success)
    {
        var parentClass; //set parent class
        success ? parentClass = "success" : parentClass = "error"; //set success or error to parent container

        if ($("#" + fieldId).data("hasMessage")) //if field has message assoc with it
        {
            //replace existing with new message and replace parent class (error, success)

            if ($("#" + fieldId).parents(".frmRow").hasClass(parentClass) && $("#" + fieldId).parents(".frmRow").find("." + vOptions.parentMessageClass).html() == $(inlineMess).html())
            {
                return false; //check if message is the same
            }
            else
            {
                $("#" + fieldId).parents(".frmRow").removeClass("error").removeClass("success")
                .addClass(parentClass)
                .find("." + vOptions.parentMessageClass)
                .animate({
                    opacity: "0"
                }, 1000, function()
                {
                    $(this).replaceWith($(inlineMess).css("opacity", "0").animate({
                        opacity: "1"
                    }, 1000));
                });
            }

        }
        else //no message exists
        {
            //add message state and parent class
            $("#" + fieldId).data("hasMessage", true).parents(".frmRow").addClass(parentClass);

            //check for custom components, and append error in diff area
            if ($("#" + fieldId).parents().hasClass("select") === true)
            {
                $(inlineMess).insertAfter($("#" + fieldId).parents(".frmRow").children(".container:last"))
                .css("opacity", "0")
                .animate({
                    opacity: "1"
                }, 1000);
            }
            else
            {
                //add inline message
                $(inlineMess).insertAfter("#" + fieldId)
                .css("opacity", "0")
                .animate({
                    opacity: "1"
                }, 1000);
            }
        }
        checkForErrors();
    };

    function checkForErrors()
    {
        if (($("." + vOptions.mainMessageBlock).length) && ($("." + vOptions.errorClass).length == 0)) //check if main error block exists at top of page
        {
            $("." + vOptions.mainMessageBlock).remove();
        }
    }

    //set event on fields
    $(this).blur(function()
    {
        if (!$(this).data("hasMessage"))
        {
            $(this).data("hasMessage", false);
        }
        if ($(this).parents(".frmRow").find("." + vOptions.parentMessageClass).length)
        {
            $(this).data("hasMessage", true);
        }
        if (!($(this).val())) //check for null/empty value in field
        {
            //check for existing message
            if ($(this).data("hasMessage"))
            {
                //remove inline message and parent class
                $(this).parents(".frmRow").removeClass("error").removeClass("success").find("." + vOptions.parentMessageClass)
                .animate({ opacity: "0" }, 1000, function() { $(this).remove(); });
                checkForErrors();
                //reset hasMessage state
                $(this).data("hasMessage", false);
            }
            return false;
        }
        else //if value exists then validate it
        {
            isValid(escape(this.name));
        }
    });
    /*
    end validation
    */
};

