var vdf = {
    _projectPrefix: "vdf",
    _CSSFilesPath: "css/",
    _jsonlycssFiles: ["JSModules"],
    newVOP: {},
    init: function () {
        try {
            if (vdf.Tools) {
                vdf.Tools.init();
            }
        }
        catch (e) {}
        try {
            if (vdf.Views) {
                vdf.Views.init();
            }
        }
        catch (e) {}
        try {
            if (vdf.newVOP.Form) {
                vdf.newVOP.Form.init();
            }
        }
        catch (e) {}
        try {
            if (vdf.newVOP.DeviceCarousel) {
                vdf.newVOP.DeviceCarousel.init();
            }
        }
        catch (e) {}
        Event.observe(window, "unload", function () {
            vdf = null;
        });
    },
    testStyles: function () {
        var testStyles = '<style type="text/css" id="testStyles">#testStylesOn {width: 100px;}</style>';
        document.body.innerHTML += testStyles;
        var testStylesTag = document.getElementById("testStyles");
        var testStylesElement = document.createElement("div");
        testStylesElement.id = "testStylesOn";
        document.body.appendChild(testStylesElement);
        var result = false;
        if (testStylesElement.offsetWidth === 100 || Prototype.Browser.WebKit) {
            result = true;
        }
        document.body.removeChild(testStylesTag);
        document.body.removeChild(testStylesElement);
        return result;
    }
};

vdf.Tools = {
    lastScroll: 0,
    init: function () {
        vdf.Tools.Expander.init();
        try {
            vdf.Tools.Overlay.init();
        } catch (e) {}
        try {
            vdf.Tools.Lightbox.init();
        } catch (e) {}

        /* VMI - START - 28-01-2010 */
        try {
            if (vdf.Tools.Tabs) {
                var aTabbedElements = $$('div.tabbedContent');
                if (aTabbedElements[0]) {
                    vdf.Tools.Tabs.init(aTabbedElements);
                }
            }
        } catch (e) {} /* VMI - END - 28-01-2010 */

        var aSubscriptionCheckboxTargetLinks = $$('.subscriptionCheckbox');
        if (aSubscriptionCheckboxTargetLinks[0]) {
            vdf.Tools.SubscriptionChecks.init(aSubscriptionCheckboxTargetLinks);
        }
        var helpHoverTargets = $$('.helpHoverTarget');
        if (helpHoverTargets[0]) {
            vdf.Tools.HelpHover.init(helpHoverTargets);
        }
    },
    isChildOf: function (parent, element) {
        if (element && element.nodeName !== "BODY") {
            if (element.parentNode === parent) {
                return true;
            }
            else if (element === parent) {
                return true;
            }
            else {
                return vdf.Tools.isChildOf(parent, element.parentNode);
            }
        }
        return false;
    },
    getParentByClass: function (sClassName, element) {
        if (element && element.nodeName !== "BODY") {
            if ($(element.parentNode).hasClassName(sClassName)) {
                return true;
            }
            else if ($(element).hasClassName(sClassName)) {
                return element;
            }
            else {
                return vdf.Tools.getParentByClass(sClassName, element.parentNode);
            }
        }
        return false;
    },
    checkNoScroll: function () {
        var iCurrentTime = new Date().getTime();
        if (iCurrentTime > (vdf.Tools.lastScroll + 250)) {
            return true;
        } else {
            return false;
        }
    },
    stripWhitespace: function (sData, sReplacement) {
        if (!sReplacement) {
            sReplacement = '';
        }
        return sData.replace(/[ \t\n\r]+/, sReplacement);
    }
};

vdf.Tools.MessagePane = {
    _sMessagePaneID: 'messagePane',
    _sMessageListID: 'paneErrorList',
    _sErrorPaneToggleID: 'errorPaneToggle',
    _sErrorIFrameLayer: 'errorIFrameLayer',
    _sErrorIFrameDivLayer: 'errorIFrameDivLayer',
    _sErrorMsg: "",
    _HTMLString: "",
    _HideErrorsString: "",
    eErrorPane: null,
    eErrorList: null,
    init: function () {
        this._sErrorMsg = "Sorry we are not able to process your request yet as there are still errors in your form.";
        this._HTMLString = '<p class="error_pane_intro"><strong>' + this._sErrorMsg + '</strong></p>';
        this._HideErrorsString = '<hr class="accessible" /> <h3 class="accessible">Error Messages</h3><p><a href="#" id="' + this._sErrorPaneToggleID + '">Hide errors</a></p>';
        this.createMessagePane();
        return this;
    },
    createMessagePane: function () {
        vdf.Tools.MessagePane.eErrorPane = new Element("div", {
            id: vdf.Tools.MessagePane._sMessagePaneID,
            tabindex: -1,
            'class': 'displayNone'
        }).update(vdf.Tools.MessagePane._HideErrorsString + vdf.Tools.MessagePane._HTMLString).setOpacity(0.9);
        document.body.appendChild(vdf.Tools.MessagePane.eErrorPane);
        vdf.Tools.MessagePane.eErrorList = new Element("ul", {
            id: vdf.Tools.MessagePane._sMessageListID
        });
        vdf.Tools.MessagePane.eErrorPane.appendChild(vdf.Tools.MessagePane.eErrorList);
        vdf.Tools.MessagePane.eErrorIFrame = new Element("iframe", {
            id: vdf.Tools.MessagePane._sErrorIFrameLayer,
            src: '/en_GB/assets/sso/images/common/iFrameSrc.gif',
            frameborder: '0',
            scrolling: 'no',
            marginheight: '0',
            marginwidth: '0',
            style: 'border-top-width: 0!important'
        });
        vdf.Tools.MessagePane.eErrorPane.appendChild(vdf.Tools.MessagePane.eErrorIFrame);
        vdf.Tools.MessagePane.eErrorIFrameDiv = new Element("div", {
            id: vdf.Tools.MessagePane._sErrorIFrameDivLayer,
            style: ''
        });
        vdf.Tools.MessagePane.eErrorPane.appendChild(vdf.Tools.MessagePane.eErrorIFrameDiv);
        Event.observe(vdf.Tools.MessagePane._sErrorPaneToggleID, "click", function (event) {
            vdf.Tools.MessagePane.toggleMessagePane(this);
            Event.stop(event);
        });
    },
    showMessagePane: function () {
        if (vdf.Tools.MessagePane.eErrorPane.hasClassName('displayNone')) {
            vdf.Tools.MessagePane.eErrorPane.removeClassName('displayNone');
            var paneHeight = vdf.Tools.MessagePane.eErrorPane.offsetHeight;
            Animate.tween(vdf.Tools.MessagePane.eErrorPane, {
                marginBottom: {
                    time: 0,
                    duration: 0.5,
                    start: 0 - paneHeight,
                    stop: 0,
                    units: 'px',
                    transition: FX.sineInOut
                }
            });
            Animate.play();
        }
    },
    toggleMessagePane: function (callingElement) {
        vdf.Tools.MessagePane.eErrorList.toggle();
        if (callingElement.innerHTML == 'Hide errors') {
            errorLayerIFrame(vdf.Tools.MessagePane.eErrorPane.offsetHeight);
            callingElement.update('Show errors');
        }
        else {
            errorLayerIFrame(vdf.Tools.MessagePane.eErrorPane.offsetHeight);
            callingElement.update('Hide errors');
        }
    },
    closeMessagePane: function () {
        if (!vdf.Tools.MessagePane.eErrorPane.hasClassName('displayNone')) {
            var paneHeight = vdf.Tools.MessagePane.eErrorPane.offsetHeight;
            Animate.tween(vdf.Tools.MessagePane.eErrorPane, {
                height: {
                    time: 0,
                    duration: 0.5,
                    start: paneHeight,
                    stop: 0,
                    units: 'px',
                    transition: FX.sineInOut,
                    onStop: function (element) {
                        vdf.Tools.MessagePane.eErrorPane.style.height = 'auto';
                        vdf.Tools.MessagePane.eErrorPane.addClassName('displayNone');
                    }
                }
            });
            Animate.play();
        }
    },
    addErrorMessage: function (sIDvalue, sErrorTitle, sError, iIndex, sGroupID) {
        var sMainErrorID;
        if (sGroupID && sGroupID !== '') {
            sMainErrorID = sGroupID;
        }
        else {
            sMainErrorID = sIDvalue;
        }
        var aErrorMessage = vdf.Tools.MessagePane.eErrorList.select('li.val_' + sMainErrorID);
        if (!aErrorMessage[0]) {
            vdf.Tools.MessagePane.showMessagePane();
            vdf.Tools.MessagePane.addErrorHeader(sMainErrorID, sErrorTitle, iIndex);
            var errorUL = new Element("ul", {
                'class': 'val_' + sMainErrorID
            }).update('<li class="valItem_' + sIDvalue + iIndex + '">' + sError + '</li>');
            vdf.Tools.MessagePane.eErrorList.appendChild(errorUL);
        }
        else {
            var aErrorMessageLI = vdf.Tools.MessagePane.eErrorList.select('li.valItem_' + sIDvalue + iIndex);
            if (!aErrorMessageLI[0]) {
                var aErrorMessageUL = vdf.Tools.MessagePane.eErrorList.select('ul.val_' + sMainErrorID);
                var errorlink = new Element("li", {
                    'class': 'valItem_' + sIDvalue + iIndex
                }).update(sError);
                aErrorMessageUL[0].appendChild(errorlink);
            }
        }
    },
    addErrorHeader: function (sIDvalue, sErrorTitle, iIndex) {
        var errorHeadingText = '<a href="#' + sIDvalue + '"><span>' + sErrorTitle + '</span></a>';
        var errorHeading = new Element("li", {
            'class': 'val_' + sIDvalue
        }).update(errorHeadingText);
        vdf.Tools.MessagePane.eErrorList.appendChild(errorHeading);
    },
    removeErrorMessage: function (sIDvalue, iIndex, sGroupID) {
        var sMainErrorID;
        if (sGroupID) {
            sMainErrorID = sGroupID;
        }
        else {
            sMainErrorID = sIDvalue;
        }
        var aErrorUL = vdf.Tools.MessagePane.eErrorList.select('ul.val_' + sMainErrorID)[0];
        if (aErrorUL) {
            var aErrorMessage = aErrorUL.select('li.valItem_' + sIDvalue + iIndex);
            if (aErrorMessage.length !== 0) {
                aErrorMessage[0].remove();
                return true;
            }
        }
        return false;
    },
    checkErrorBlock: function (sIDvalue, sGroupID) {
        var sMainErrorID;
        if (sGroupID) {
            sMainErrorID = sGroupID;
        }
        else {
            sMainErrorID = sIDvalue;
        }
        var aErrorUL = vdf.Tools.MessagePane.eErrorList.select('ul.val_' + sMainErrorID)[0];
        if (aErrorUL) {
            var aValItems = aErrorUL.select('li');
            var bRemainingErrors = true;
            if (aErrorUL.select('li').length === 0) {
                aErrorUL.remove();
                vdf.Tools.MessagePane.fadeOutErrorMessage(vdf.Tools.MessagePane.eErrorList.select('li.val_' + sMainErrorID)[0]);
                return true;
            }
            else {
                for (var i = 0, k = aValItems.length; i < k; i++) {
                    var startsWithPattern = new RegExp('valItem_' + sIDvalue);
                    bRemainingErrors = startsWithPattern.test(aValItems[i].getAttribute('class'));
                    if (bRemainingErrors) {
                        break;
                    }
                }
            }
            return !bRemainingErrors;
        }
    },
    checkForOpenErrors: function () {
        var iInvisibleErrors = vdf.Tools.MessagePane.eErrorList.select('li').length;
        if (iInvisibleErrors === 0) {
            vdf.Tools.MessagePane.closeMessagePane();
            return true;
        }
        return false;
    },
    fadeOutErrorMessage: function (eErrorMessageItem) {
        if (eErrorMessageItem) {
            eErrorMessageItem.addClassName("validated");
            eErrorMessageItem.tween({
                color: {
                    time: 0,
                    duration: 0.2,
                    start: "#000000",
                    stop: "#80c451",
                    transition: FX.quadInOut,
                    onStop: function (element) {
                        element.remove();
                        vdf.Tools.MessagePane.checkForOpenErrors();
                    }
                },
                alpha: {
                    time: 0.2,
                    duration: 0.2,
                    start: 100,
                    stop: 0,
                    transition: FX.quadInOut
                }
            });
            Animate.play();
        }
    }
};

vdf.Tools.Overlay = {
    _sOverlayID: "lightBoxOverlay",
    _sOverlayIE6ID: "lightBoxOverlayIE6Hack",
    _eOverlay: null,
    _eOverlayIFrame: null,
    examplePublicProperty: null,
    init: function () {},
    createOverlay: function () {
        vdf.Tools.Overlay._eOverlay = document.createElement("div");
        vdf.Tools.Overlay._eOverlay.id = vdf.Tools.Overlay._sOverlayID;
        vdf.Tools.Overlay._eOverlayIFrame = document.createElement("iframe");
        vdf.Tools.Overlay._eOverlayIFrame.id = vdf.Tools.Overlay._sOverlayIE6ID;
        $(vdf.Tools.Overlay._eOverlayIFrame).setOpacity(0);
        $(vdf.Tools.Overlay._eOverlayIFrame).src = '/en_GB/assets/sso/images/common/iFrameSrc.gif';
        document.body.appendChild(vdf.Tools.Overlay._eOverlayIFrame);
        document.body.appendChild(vdf.Tools.Overlay._eOverlay);
    },
    showOverlay: function () {
        if (!vdf.Tools.Overlay._eOverlay) {
            vdf.Tools.Overlay.createOverlay();
        }
        var scrollHeight = document.body.scrollHeight;
        var windowHeight = document.viewport.getHeight();
        var iCurrentPageHeight = windowHeight;
        if (scrollHeight > windowHeight) {
            iCurrentPageHeight = scrollHeight;
        }
        $(vdf.Tools.Overlay._eOverlay).setStyle({
            height: iCurrentPageHeight + "px",
            display: "block"
        });
        $(vdf.Tools.Overlay._eOverlayIFrame).setStyle({
            height: iCurrentPageHeight + "px",
            display: "block"
        });
        $(vdf.Tools.Overlay._eOverlay).tween({
            alpha: {
                time: 0,
                duration: 0.2,
                start: 0,
                stop: 60,
                transition: FX.sineInOut
            }
        });
    },
    hideOverlay: function () {
        $(vdf.Tools.Overlay._eOverlay).setOpacity(0);
        $(vdf.Tools.Overlay._eOverlay).setStyle({
            height: "",
            display: "none"
        });
        $(vdf.Tools.Overlay._eOverlayIFrame).setStyle({
            height: "",
            display: "none"
        });
    },
    exampleMethod: function () {
        var iExampleInteger = 1;
        var sExampleString = "string";
        var bExampleBoolean = true;
        var eExampleElement = document.createElement("div");
        var oExampleObject = {};
        var aExampleArray = [];
        var fExampleFunction = vdf.Tools.Overlay.exampleMethod;
    }
};

vdf.Tools.HelpHover = {
    _aHelpHoverTargets: [],
    _aHelpHovers: [],
    _sHelpHoverCloseClass: 'closeButton',
    _sHelpHoverCloseButton: '<a href="#" class="helpHoverCloseButton"><img alt="Close" src="/en_GB/assets/sso/images/helphover/help_hover_close.gif"/></a>',
    _iHoverWidth: 219,
    init: function (aHelpHoverTargets) {
        vdf.Tools.HelpHover._aHelpHoverTargets = aHelpHoverTargets;
        vdf.Tools.HelpHover._aHelpHovers = $$('.helpHover');
        var eHelpContent = $$(".helpContent")[0];
        if (eHelpContent) {
            document.body.appendChild(eHelpContent);
        }
        vdf.Tools.HelpHover._aHelpHoverTargets.each(function (eTarget, iIndex) {
            Event.attachMouseEnter(eTarget, function () {
                vdf.Tools.HelpHover.showHelpHover(eTarget);
            });
            Event.attachMouseLeave(eTarget, function () {
                vdf.Tools.HelpHover.hideHelpHover.delay(1, vdf.Tools.HelpHover.getHelpHover(eTarget));
            });
			//handle keyboard focus, the link tag gets the focus to we need to bind to that, typically we have the image here.
			var eTargetLink = eTarget;
			if (eTargetLink.nodeName == 'IMG') {
				eTargetLink = eTarget.up();
			}
			if (eTargetLink.nodeName == 'A') {
				eTargetLink.observe('focus', function(){
					vdf.Tools.HelpHover.showHelpHover(eTarget);
				});
	
				eTargetLink.observe('blur', function(){
					vdf.Tools.HelpHover.hideHelpHover.delay(1,vdf.Tools.HelpHover.getHelpHover(eTarget));
				});	
			}

        });
        vdf.Tools.HelpHover._aHelpHovers.each(function (eHelpHoverElement, iIndex) {
            eHelpHoverElement.setOpacity(0);
            eHelpHoverElement.setStyle({
                zIndex: 9999987
            });
            Event.attachMouseEnter(eHelpHoverElement, function () {
                eHelpHoverElement.addClassName('focusedHelpHover');
            });
            Event.attachMouseLeave(eHelpHoverElement, function () {
                eHelpHoverElement.removeClassName('focusedHelpHover');
                vdf.Tools.HelpHover.hideHelpHover(eHelpHoverElement);
            });
        });
    },
    showHelpHover: function (eThis) {
        var sHelpHoverID = eThis.readAttribute('class').match(/hoverID[A-Za-z0-9-]*/);
        if (sHelpHoverID) {
            var eHover = $(sHelpHoverID[0]);
			var sPreferredPositionID = eHover.readAttribute('class').match(/hoverPosition[A-Za-z0-9-]*/);
            sPreferredPositionID = (sPreferredPositionID) ? sPreferredPositionID[0] : '';
			var sPositionID = vdf.Tools.HelpHover.testBounds(eThis, eHover, sPreferredPositionID);
			//vdf.Tools.HelpHover.styleHelpHover(eHover, sPositionID);
			vdf.Tools.HelpHover.setPosition(eThis, eHover, sPositionID);
            if (!eHover.hasClassName("inTransition")) {
			
                if (!eHover.hasClassName('positionedHH')) {
                    //var sPreferredPositionID = eHover.readAttribute('class').match(/hoverPosition[A-Za-z0-9-]*/);
                    //sPreferredPositionID = (sPreferredPositionID) ? sPreferredPositionID[0] : '';
                    //var sPositionID = vdf.Tools.HelpHover.testBounds(eThis, eHover, sPreferredPositionID);
                    if (sPreferredPositionID != sPositionID) {
                        eHover.removeClassName(sPreferredPositionID);
                        eHover.addClassName(sPositionID);
                    }
                    vdf.Tools.HelpHover.styleHelpHover(eHover, sPositionID);
                    //vdf.Tools.HelpHover.setPosition(eThis, eHover, sPositionID);
					eHover.addClassName('positionedHH');
                    if (eHover.hasClassName(vdf.Tools.HelpHover._sHelpHoverCloseClass)) {
                        var eHoverButton = eHover.select('.helpHoverCloseButton')[0];
                        Event.observe(eHoverButton, 'click', function (event) {
                            eHover.addClassName('JShidden');
                            Event.stop(event);
                        });
                    }
                }
                eHover.removeClassName('JShidden');
                eHover.addClassName('inTransition');
                eHover.tween({
                    alpha: {
                        time: 0,
                        duration: 0.5,
                        start: 0,
                        stop: 100,
                        transition: FX.quadInOut,
                        onStop: function (element) {
                            element.removeClassName('inTransition');
                        }
                    }
                });
                Animate.play();
            }
        }
    },
    hideHelpHover: function (eHover) {
        if (!eHover.hasClassName('inTransition') && !eHover.hasClassName('focusedHelpHover') && !eHover.hasClassName('JShidden')) {
            eHover.addClassName('inTransition');
            eHover.tween({
                alpha: {
                    time: 0,
                    duration: 0.5,
                    start: 100,
                    stop: 0,
                    transition: FX.quadInOut,
                    onStop: function (element) {
                        element.addClassName('JShidden');
                        element.removeClassName('inTransition');
                    }
                }
            });
            Animate.play();
        }
    },
    getHelpHover: function (eThis) {
        var sHelpHoverID = eThis.readAttribute('class').match(/hoverID[A-Za-z0-9-]*/);
        if (sHelpHoverID) {
            return $(sHelpHoverID[0]);
        }
        return null;
    },
    testBounds: function (eTarget, eHover, sPosition) {
        var sInboundsResult = sPosition;
        var aTargetOffset = eTarget.viewportOffset();
        var aViewPortWidth = [document.viewport.getWidth(), document.viewport.getHeight()];
        if (sPosition == 'hoverPositionAboveCentered') {
            if (aTargetOffset[0] + vdf.Tools.HelpHover._iHoverWidth / 2 > aViewPortWidth[0]) {
                sInboundsResult = 'hoverPositionLeft';
            }
            else if (aTargetOffset[0] - vdf.Tools.HelpHover._iHoverWidth / 2 < 0) {
                sInboundsResult = 'hoverPositionRight';
            }
            else if (aTargetOffset[1] - (eHover.getHeight() + 19) < 0) {
                sInboundsResult = 'hoverPositionRight';
            }
        }
        if (sPosition == 'hoverPositionRight') {
            if (aTargetOffset[0] + vdf.Tools.HelpHover._iHoverWidth > aViewPortWidth[0]) {
                sInboundsResult = 'hoverPositionLeft';
            }
        }
        else if (sPosition == 'hoverPositionLeft') {
            if (aTargetOffset[0] - vdf.Tools.HelpHover._iHoverWidth < 0) {
                sInboundsResult = 'hoverPositionRight';
            }
        }
        return sInboundsResult;
    },
    setPosition: function (eTarget, eHover, sPosition) {
        var aTargetPostition = eTarget.cumulativeOffset();
        var iTopOffset = 0;
        switch (sPosition) {
        case 'hoverPositionBottomCentered':
            aTargetPostition[0] += ((eTarget.getWidth() / 2) - vdf.Tools.HelpHover._iHoverWidth / 2);
            aTargetPostition[1] += (eTarget.getHeight());
            break;
        case 'hoverPositionBottomRight':
            aTargetPostition[0] += ((eTarget.getWidth()) - vdf.Tools.HelpHover._iHoverWidth);
            aTargetPostition[1] += (eTarget.getHeight());
            break;
        case 'hoverPositionBottomLeft':
            aTargetPostition[1] += (eTarget.getHeight());
            break;
        case 'hoverPositionAboveCentered':
            aTargetPostition[0] += ((eTarget.getWidth() / 2) - vdf.Tools.HelpHover._iHoverWidth / 2);
            aTargetPostition[1] -= +95;
            break;
        case 'hoverPositionAboveRight':
            aTargetPostition[0] += ((eTarget.getWidth()) - vdf.Tools.HelpHover._iHoverWidth);
            aTargetPostition[1] -= (eHover.getHeight() + iTopOffset);
            break;
        case 'hoverPositionRight':
            aTargetPostition[0] += eTarget.getWidth();
            aTargetPostition[1] -= 24;
            break;
        case 'hoverPositionLeft':
            aTargetPostition[0] -= vdf.Tools.HelpHover._iHoverWidth;
            aTargetPostition[1] -= 24;
            break;
        default:
            aTargetPostition[1] -= (eHover.getHeight() + iTopOffset);
        }
        eHover.setStyle({
            left: aTargetPostition[0] + 'px',
            top: aTargetPostition[1] + 'px'
        });
        //eHover.addClassName('positionedHH');
    },
    styleHelpHover: function (eHover, sPosition) {
        var sContent = '';
        var sCloseButton = (eHover.hasClassName(vdf.Tools.HelpHover._sHelpHoverCloseClass)) ? vdf.Tools.HelpHover._sHelpHoverCloseButton : '';
        if (sPosition.indexOf('Bottom') == -1) {
            sContent = '<div class="helpHoverContent">' + sCloseButton + eHover.innerHTML + '</div><div class="helpHoverFooter"></div>';
        }
        else {
            sContent = '<div class="helpHoverHeader"></div><div class="helpHoverContent">' + vdf.Tools.HelpHover._sHelpHoverCloseButton + eHover.innerHTML + '</div>';
        }
        eHover.update(sContent);
    }
};

vdf.Tools.Lightbox = {
    _sDetailsRef: ".generic_Lightbox",
    _sWaitingRef: ".waiting_Lightbox",
    _sWaitingURL: "/en_GB/assets/sso/html/payment_waiting_window.html",
    _sLightBoxID: "genericLightBox",
    /* VMI - START - 01-02-2010 */
    _sLightBoxClassName: "",
    _sContainerRef: "body",
    /* VMI - END - 01-02-2010 */
    _eLightBox: null,
    _oPageCache: {},
    _sCurrentHref: null,
    _iTopOffset: 10,
    _bMouseOver: false,

    /**
     // vdf.Tools.Lightbox.init : class constructor (description)
     */
    init: function () {
        var aLightBoxes = $$(vdf.Tools.Lightbox._sDetailsRef);
        aLightBoxes.each(function (element) {
            Event.observe(element, "click", vdf.Tools.Lightbox.triggerLightbox);
        });

        var aWaitingLightBoxes = $$(vdf.Tools.Lightbox._sWaitingRef);
        aWaitingLightBoxes.each(function (element) {
            Event.observe(element, "click", vdf.Tools.Lightbox.triggerWaitingLightbox);
        });
    },

    triggerWaitingLightbox: function (event) {
        vdf.Tools.Lightbox.triggerLightbox(event, true, vdf.Tools.Lightbox._sWaitingURL);
    },

    triggerLightbox: function (event, bContinueAction, sTargetURL) {
        if (event && !bContinueAction) {
            Event.stop(event);
        }
        var eContentHolder = document.createElement("div");
        vdf.Tools.Lightbox._eLightBox = eContentHolder;
        eContentHolder.id = vdf.Tools.Lightbox._sLightBoxID; /* VMI - START - 01-02-2010 */
        $(eContentHolder).writeAttribute('tabindex', -1).setStyle({
            visibility: "hidden"
        });
        eContentHolder.className = (vdf.Tools.Lightbox._sLightBoxClassName) ? vdf.Tools.Lightbox._sLightBoxClassName : ""; /* VMI - END - 01-02-2010 */
        document.body.appendChild(eContentHolder);

        //get the final height of the window & width
        var oDimensions = $(eContentHolder).getDimensions();
        var iFinalHeight = oDimensions.height;
        var iFinalWidth = oDimensions.width;

        //set the start height & width & left and right
        var windowSize = document.viewport.getDimensions();
        var iStartHeight = 100;
        var iStartWidth = 150;

        //get the start and end left
        var containerWidth = $$(vdf.Tools.Lightbox._sContainerRef)[0].getWidth();
        var iStartLeft = (containerWidth - iStartWidth) / 2;
        var iEndLeft = (containerWidth - iFinalWidth) / 2;

        var currentPos = $(event.target).cumulativeOffset();
        var currentDimensions = $(event.target).getDimensions();

        var scrollHeight = document.viewport.getScrollOffsets()[1] + vdf.Tools.Lightbox._iTopOffset;
        $(eContentHolder).setStyle({
            visibility: "visible",
            width: iStartWidth + "px",
            height: iStartHeight + "px",
            left: iStartLeft + "px",
            top: currentPos[1] + "px"
        });
        $(eContentHolder).tween({
            left: {
                time: 0.3,
                duration: 0.3,
                start: iStartLeft,
                stop: iEndLeft,
                units: 'px',
                transition: FX.quadInOut
            },

            width: {
                time: 0.3,
                duration: 0.3,
                start: iStartWidth,
                stop: iFinalWidth,
                units: 'px',
                transition: FX.quadInOut
            },
            height: {
                time: 0.9,
                duration: 0.3,
                start: iStartHeight,
                stop: iFinalHeight,
                units: 'px',
                transition: FX.quadInOut,
                onStop: function (element) {
                    element.style.height = "";
                }
            },

            top: {
                time: 0.9,
                duration: 0.3,
                start: currentPos[1],
                stop: scrollHeight,
                units: 'px',
                transition: FX.quadInOut
            }

        });
        if (sTargetURL) {
            vdf.Tools.Lightbox.getLightWindowContents(null, sTargetURL);
        }
        else {
            vdf.Tools.Lightbox.getLightWindowContents(event.target);
        }
        vdf.Tools.Overlay.showOverlay();
        $(vdf.Tools.Overlay._eOverlay).observe("click", vdf.Tools.Lightbox.bodyClick);

        Animate.play(); /* VMI - START - 01-02-2010 */
        vdf.Tools.Lightbox._eLightBox.focus(); /* VMI - END - 08-02-2010 */
    },

    getLightWindowContents: function (element, sTargetURL) {
        var sHref;

        // Changes done for OBU 7.1 Release: OB3184-PAYM - Start
/*if (element) {
			var link = element;
			if (!element.href) {
				link = $(element).select("a")[0];
			}
			sHref = link.href;
		}
		else {
			sHref = sTargetURL;
		}*/

        if (element) {
            var link;
            if (element.parentNode.nodeName == "A") {
                link = element.parentNode;
            } else {
                link = element;
            }

            if (!link.href) {
                link = $(element).select("a")[0];
            }
            sHref = link.href;
        } else {
            sHref = sTargetURL;
        }
        // Changes done for OBU 7.1 Release: OB3184-PAYM - End
        if (sHref) {
            vdf.Tools.Lightbox._sCurrentHref = escape(sHref);
            if (vdf.Tools.Lightbox._oPageCache[vdf.Tools.Lightbox._sCurrentHref]) {
                vdf.Tools.Lightbox.processContents(vdf.Tools.Lightbox._oPageCache[vdf.Tools.Lightbox._sCurrentHref]);
            } else {
                new Ajax.Request(sHref, {
                    method: 'get',
                    parameters: {
                        ajaxRequest: true
                    },
                    onSuccess: vdf.Tools.Lightbox.processContents,
                    onFailure: vdf.Tools.Lightbox.failureHandler
                });
            }


        }

    },

    processContents: function (response, fCallBack) {
        if (vdf.Tools.Lightbox._eLightBox.style.height === "" || vdf.Tools.Lightbox._eLightBox.style.height === "auto") {
            vdf.Tools.Lightbox.insertContents(response.responseText, fCallBack);
        } else {
            window.setTimeout(function () {
                vdf.Tools.Lightbox.processContents(response, fCallBack);
            }, 1);
        }
    },

    insertContents: function (response, fCallBack) {
        vdf.Tools.Lightbox._oPageCache[vdf.Tools.Lightbox._sCurrentHref] = {
            responseText: response
        };
        $(vdf.Tools.Lightbox._eLightBox).removeClassName("loading");
        vdf.Tools.Lightbox._eLightBox.style.height = "auto";
        vdf.Tools.Lightbox._eLightBox.innerHTML = response;
        sBGColor = $(vdf.Tools.Lightbox._eLightBox).getStyles("backgroundColor").backgroundColor;
        $(vdf.Tools.Lightbox._eLightBox).setStyle({
            overflow: "auto"
        });
        var fader = document.createElement("div");
        $(fader).setStyle({
            width: "100%",
            height: "100%",
            position: "absolute",
            top: "0px",
            left: "0px",
            backgroundColor: sBGColor
        });
        vdf.Tools.Lightbox._eLightBox.appendChild(fader);
        $(fader).tween({
            alpha: {
                time: 0,
                duration: 0.2,
                start: 100,
                stop: 0,
                transition: FX.quadInOut,
                onStop: function (element) {
                    element.parentNode.removeChild(element);
                }

            }
        });
        Animate.play();
        if (fCallBack) {
            fCallBack(vdf.Tools.Lightbox._eLightBox);
        }
        vdf.Tools.Lightbox.applyClose();
        vdf.Tools.Lightbox.applyPrint();
        vdf.Tools.Lightbox.hideSelectBoxes();
    },

    hideSelectBoxes: function () {
        var allSelectBoxes = document.getElementsByTagName("select");
        var browser = navigator.appName;
        var b_version = navigator.appVersion;
        var version = parseFloat(b_version);
        if ((browser == "Microsoft Internet Explorer") && (version >= 4)) {
            for (i = 0; i < allSelectBoxes.length; i++) {
                allSelectBoxes[i].style.visibility = "hidden";
            }
        }
    },

    showSelectBoxes: function () {
        var allSelectBoxes = document.getElementsByTagName("select");
        for (i = 0; i < allSelectBoxes.length; i++) {
            if (allSelectBoxes[i].style.visibility == "hidden") {
                allSelectBoxes[i].style.visibility = "visible";
            }
        }
    },

    applyClose: function () {
        //apply the close functions to the lightbox buttons
        var closeLinks = $(vdf.Tools.Lightbox._eLightBox).select(".link_close");
        closeLinks.each(function (element) {
            element.observe("click", vdf.Tools.Lightbox.closeLightBox);
        });
        //apply the form submit
        var forms = $(vdf.Tools.Lightbox._eLightBox).select("form");
        forms.each(function (element) {
            element.observe("submit", vdf.Tools.Lightbox.formSubmit);
        });
        //also check for help hovers
        var helpHoverTargets = $(vdf.Tools.Lightbox._eLightBox).select('.helpHoverTarget');
        if (helpHoverTargets[0]) {
            vdf.Tools.HelpHover.init(helpHoverTargets);
        }

    },

    formSubmit: function (event) {
        Event.stop(event);
        $(vdf.Tools.Lightbox._eLightBox).addClassName("loading");

        //send the form via ajax and get the response
        var eForm = event.target;
        var oParmeters = $(eForm).serialize(true);
        var sDestination = event.target.getAttribute("action");
        vdf.Tools.Lightbox._sCurrentHref = escape(sDestination);
        oParmeters.ajaxRequest = true;
        new Ajax.Request(sDestination, {
            parameters: oParmeters,
            onSuccess: vdf.Tools.Lightbox.processContents
        });
    },

    applyPrint: function ()

    {
        var printLinks = $(vdf.Tools.Lightbox._eLightBox).select(".link_print");
        printLinks.each(function (element) {
            element.observe("click", vdf.Tools.Lightbox.printLightBox);
        });
    },

    closeLightBox: function (event) {
        document.getElementById("grid").className = "grid";
        if (document.getElementById("mainShell")) {
            document.getElementById("mainShell").className = "";
        }
        vdf.Tools.Lightbox.showSelectBoxes();
        vdf.Tools.Overlay.hideOverlay();
        vdf.Tools.Lightbox._eLightBox.parentNode.removeChild(vdf.Tools.Lightbox._eLightBox);
        Event.stop(event);
    },

    printLightBox: function (event) {
        document.getElementById("grid").className = "grid printOverlay";
        if (document.getElementById("mainShell")) {
            document.getElementById("mainShell").className = "printOverlay";
        }
        window.print();
        Event.stop(event);
    },

    bodyClick: function (event) {
        //check whether the mouse is over the panel
        vdf.Tools.Lightbox.closeLightBox(event);
    }
};


vdf.newVOP.Form = {
    _vdfForms: document.forms,
    _oValidator: null,
    _oPostCodeSearch: null,
    _eShowSecurityCode: null,
    _eShowDirectDebit: null,
    _sCreditCardType: 'creditCardType',
    _sPostcodeSubmitUrl: "MatchAddressResponse.xml",
    _sDisabledClass: "disabled",
    init: function () {
        if ($$("form.personalDetails")[0]) {
            vdf.newVOP.Form._oValidator = new vdf.newVOP.Form.Validation("personalDetails");
            this.toggleController($$("label[for='account']")[0], new Element("input", {
                type: "checkbox",
                id: "account"
            }), "accountSection", this.passwordBlockToggle);
        }
        else if ($$("form.paymentDetails")[0]) {
            vdf.newVOP.Form._oValidator = new vdf.newVOP.Form.Validation("paymentDetails");
            var inputsAndSelects = $$('.cardDetails select', '.cardDetails input');
            inputsAndSelects.splice(0, 1);
            vdf.newVOP.Form.disableFields(true, inputsAndSelects, true);
            var eCardSelectElement = $(vdf.newVOP.Form._sCreditCardType);
            Event.observe(eCardSelectElement, "change", function (event) {
                vdf.newVOP.Form.displayCardFields(eCardSelectElement);
                Event.stop(event);
            });
            vdf.newVOP.Form._eShowSecurityCode = $$('.showSecurityCodeLink')[0];
            if (vdf.newVOP.Form._eShowSecurityCode) {
                $$('.securityCodeContainer')[0].hide();
                Event.observe(vdf.newVOP.Form._eShowSecurityCode, "click", vdf.newVOP.Form.openSecurityCodeOverlay);
            }
            vdf.newVOP.Form._eShowDirectDebit = $$('.showDDLink')[0];
            if (vdf.newVOP.Form._eShowDirectDebit) {
                $$('.directDebitContainer')[0].hide();
                Event.observe(vdf.newVOP.Form._eShowDirectDebit, "click", vdf.newVOP.Form.openDirectDebitOverlay);
            }
            var eDirectDebitPopup = $$('.directDebitAgreementPopup')[0];
            if (eDirectDebitPopup) {
                var fDirectDebitPopup_bind = vdf.newVOP.Form.openPopup.bindAsEventListener(this, 'ddagreement.html', 'Direct Debit Agreement');
                Event.observe(eDirectDebitPopup, "click", fDirectDebitPopup_bind);
            }
            var eTermsAndConditionsPopup = $$('.termsAndConditionsPopup')[0];
            if (eTermsAndConditionsPopup) {
                var fTermsAndConditionsPopup_bind = vdf.newVOP.Form.openPopup.bindAsEventListener(this, 'terms.html', 'Terms and Conditions');
                Event.observe(eTermsAndConditionsPopup, "click", fTermsAndConditionsPopup_bind);
            }
        }
        else if ($$("form.basketSummary")[0]) {
            vdf.newVOP.Form._oValidator = new vdf.newVOP.Form.Validation("basketSummary");
            var eToggleCheckBox = $$('.existingNumber');
            var mobileContainer = $$('.numberContainer');
            eToggleCheckBox.each(function (element, i) {
                var eMobileContainer = mobileContainer[i];
                var eeToggleCheckBox = eToggleCheckBox[i];
                if (eMobileContainer && eeToggleCheckBox) {
                    if (!eToggleCheckBox[i].checked) {
                        vdf.newVOP.Form.toggleAdditionalFormFields(mobileContainer[i], false);
                    }
                    Event.observe(eToggleCheckBox[i], "click", function (event) {
                        vdf.newVOP.Form.toggleAdditionalFormFields(eMobileContainer, eeToggleCheckBox.checked);
                    });
                }
            });
        }
		else if ($$("form.streamlineRegForm")[0]) {
            vdf.newVOP.Form._oValidator = new vdf.newVOP.Form.Validation("streamlineRegForm",'MessageBlock');
        }
    },
    toggleController: function (oController, oElementToInsert, sBlockToToggle, oFunctionToObserve) {
        if (!oController) {
            return;
        }
        var oBlockToToggle = $(sBlockToToggle).hide();
        oBlockToToggle.select("input").each(function (item) {
            inputElement.addClassName(vdf.newVOP.Form._sDisabledClass);
        });
        var oToggleFunction = oFunctionToObserve ||
        function () {
            oBlockToToggle.toggle();
        };
        oController.insert({
            "top": oElementToInsert.observe("click", function (e) {
                oToggleFunction(oBlockToToggle);
            })
        });
    },
    passwordBlockToggle: function (oBlockToToggle) {
        var aPasswords = oBlockToToggle.select("input");
        if (!oBlockToToggle.visible()) {
            vdf.Tools.Expander.expand(oBlockToToggle, oBlockToToggle.offsetHeight);
            aPasswords.each(function (item) {
                inputElement.removeClassName(vdf.newVOP.Form._sDisabledClass);
            });
        }
        else {
            vdf.Tools.Expander.contract(oBlockToToggle, oBlockToToggle.offsetHeight);
            aPasswords.each(function (item) {
                item.clear();
                inputElement.addClassName(vdf.newVOP.Form._sDisabledClass);
            });
        }
    },
    disableFields: function (disable, source, allFields) {
        var aAllInputsAndSelects = [];
        if (Object.isElement(source)) {
            aAllInputsAndSelects = source.select("input", "select");
        }
        else {
            aAllInputsAndSelects = source;
        }
        if (allFields) {
            aAllInputsAndSelects.each(function (inputElement, elementIndex) {
                if (disable) {
                    inputElement.addClassName(vdf.newVOP.Form._sDisabledClass);
                } else {
                    inputElement.removeClassName(vdf.newVOP.Form._sDisabledClass);
                }
            });
        }
        else {
            if (disable) {
                inputElement.addClassName(vdf.newVOP.Form._sDisabledClass);
            } else {
                inputElement.removeClassName(vdf.newVOP.Form._sDisabledClass);
            }
        }
    },
    displayCardFields: function (eCardSelectElement) {
        var _sCardDetailFields = '.card_detail';
        var _sCardDetailAdditionalFields = '.card_detail_additional';
        var _aCardFields = $$(_sCardDetailFields);
        var _aCardAdditionalFields = $$(_sCardDetailAdditionalFields);
        if (eCardSelectElement.value !== '') {
            _aCardFields.each(function (eLabelElement, iArrayIndex) {
                eLabelElement.removeClassName('hidden');
                eLabelElement.select('input', 'select').each(function (eLabelFormElement, iArrayIndex) {
                    eLabelFormElement.removeClassName(vdf.newVOP.Form._sDisabledClass);
                });
            });
            if (eCardSelectElement.value == 'Solo' || eCardSelectElement.value == 'Switch' || eCardSelectElement.value == 'Maestro') {
                vdf.newVOP.Form.toggleAdditionalFormFields(_aCardAdditionalFields, true);
            }
            else {
                vdf.newVOP.Form.toggleAdditionalFormFields(_aCardAdditionalFields, false);
            }
        }
        else {
            _aCardFields.each(function (eLabelElement, iArrayIndex) {
                eLabelElement.addClassName('hidden');
                eLabelElement.select('input', 'select').each(function (eLabelFormElement, iArrayIndex) {
                    eLabelFormElement.addClassName(vdf.newVOP.Form._sDisabledClass);
                });
            });
            vdf.newVOP.Form.toggleAdditionalFormFields(_aCardAdditionalFields, false);
        }
    },
    toggleAdditionalFormFields: function (eLabelElement, bDisplayBool) {
        if (bDisplayBool) {
            for (var i = 0; i < eLabelElement.length; i++) {
                eLabelElement[i].removeClassName('hidden');
                eLabelElement[i].select('input', 'select').each(function (eLabelFormElement, iArrayIndex) {
                    eLabelFormElement.removeClassName(vdf.newVOP.Form._sDisabledClass);
                });
            }
        }
        else {
            for (i = 0; i < eLabelElement.length; i++) {
                eLabelElement[i].addClassName('hidden');
                eLabelElement[i].select('input', 'select').each(function (eLabelFormElement, iArrayIndex) {
                    eLabelFormElement.addClassName(vdf.newVOP.Form._sDisabledClass);
                });
            }
        }
    },
    openPopup: function (event, url, windowTitle) {
        window.open(url, windowTitle, "width=300,height=360,menubar=no,toolbar=no");
        Event.stop(event);
    },
    openSecurityCodeOverlay: function (event) {
        $$('.securityCodeContainer')[0].show();
        Event.observe(document.body, "click", vdf.newVOP.Form.closeSecurityCodeOverlay);
        Event.stopObserving(vdf.newVOP.Form._eShowSecurityCode, "click", vdf.newVOP.Form.openSecurityCodeOverlay);
        Event.stop(event);
    },
    openDirectDebitOverlay: function (event) {
        $$('.directDebitContainer')[0].show();
        Event.observe(document.body, "click", vdf.newVOP.Form.closeDirectDebitOverlay);
        Event.stopObserving(vdf.newVOP.Form._eShowDirectDebit, "click", vdf.newVOP.Form.openDirectDebitOverlay);
        Event.stop(event);
    },
    closeSecurityCodeOverlay: function (event) {
        $$('.securityCodeContainer')[0].hide();
        Event.stopObserving(document.body, "click", vdf.newVOP.Form.closeSecurityCodeOverlay);
        Event.observe(vdf.newVOP.Form._eShowSecurityCode, "click", vdf.newVOP.Form.openSecurityCodeOverlay);
        Event.stop(event);
    },
    closeDirectDebitOverlay: function (event) {
        $$('.directDebitContainer')[0].hide();
        Event.stopObserving(document.body, "click", vdf.newVOP.Form.closeDirectDebitOverlay);
        Event.observe(vdf.newVOP.Form._eShowDirectDebit, "click", vdf.newVOP.Form.openDirectDebitOverlay);
        Event.stop(event);
    }
};
vdf.newVOP.Form.Validation = Class.create({
	sMessagePaneReference:'MessagePane',
    _oMessagePane: null,
    _eForm: null,
    _validateClass: 'validateItem',
    _validationFailed: "validationFailed",
    _validationPassed: "validationPassed",
    _validateAll: false,
    _keyPressed: false,
    _validations: [],
    validationInformation: null,
    aRequireds: [],
    initialize: function (formName, sNewMessagePaneRef) {
        this.validationInformation = vdf.newVOP.Form[formName];
		
        if (this.validationInformation) {
			this.eForm = $$('.' + formName)[0];
			
			if (sNewMessagePaneRef) {
				this.sMessagePaneReference = sNewMessagePaneRef;
			}
            this._oMessagePane = vdf.Tools[this.sMessagePaneReference].init(this.eForm);
            
            this.updateItemsToValidateArray();
            this.register();
        }
    },
    hasValidationInformation: function (oField) {
        return this.validationInformation[oField.id];
    },
    register: function () {
        var _this = this;
        Event.observe(_this.eForm, "submit", function (event) {
            isFormHasSubmitted = 'yes';
            _this.validateAll(event);
            invoke_dcsMultiTrack();
        });
        _this.registerEvents(_this.aRequireds);
    },
    registerEvents: function (aFields) {
        var _this = vdf.newVOP.Form._oValidator ? vdf.newVOP.Form._oValidator : this;
        aFields.each(function (oField, iIndex) {
            if (_this.hasValidationInformation(oField)) {
                switch (oField.nodeName) {
                case "INPUT":
                    switch (oField.readAttribute('type')) {
                    case 'checkbox'://commented the code to display error message on form submit but not on any other event
                        /*Event.observe(oField, 'blur', function (e) {
                            _this.reFieldValidator(oField, iIndex);
                        });*/
                        break;
                    default:
                        /*Event.observe(oField, 'blur', function (e) {
                            if (oField.hasClassName("keyPressed")) {
                                _this.reFieldValidator(oField, iIndex);
                            }
                        });*/
                        Event.observe(oField, 'keyup', function (e) {
							if (oField.hasClassName("validationFailed")) {
								oField.removeClassName("validationFailed");
							}
                            var key = e.which || e.keyCode;
                            if (key !== 9) {
                                oField.addClassName("keyPressed");
                            }
                        });
                        Event.observe(_this.eForm, "submit", function (e) {
                            if (oField.hasClassName("validationFailed")) {
                                _this.reFieldValidator(oField, iIndex);
                            }
							
                        });
                        break;
                    }
                    break;
                case "SELECT":
                    /*Event.observe(oField, 'blur', function (e) {
                        _this.reFieldValidator(oField, iIndex);
                    });*/
                    Event.observe(oField, 'change', function (e) {
                        if (oField.hasClassName("validationFailed")) {
							oField.removeClassName("validationFailed");
						}
                    });
                    break;
                }
            }
        });
    },
    reFieldValidator: function (oField, iIndex) {
        if ($(oField).hasClassName(vdf.newVOP.Form._sDisabledClass) === false) {
            var oItemValidation = null;
            var bFieldValid = null;
            var ruleNames = vdf.newVOP.Form._oValidator.validationInformation[oField.id].ruleNames;
			var iErrorPaneHeight = vdf.Tools[this.sMessagePaneReference].eErrorPane.offsetHeight;
			if (vdf.newVOP.Form._oValidator.validationInformation[oField.id].rules) {
                var fieldErrorTitle = vdf.newVOP.Form._oValidator.validationInformation[oField.id].sFieldTitle;
                bFieldValid = true;
                for (var iValIndex = 0; iValIndex < ruleNames.length; iValIndex++) {
                    oIndividualValidation = vdf.newVOP.Form._oValidator.validationInformation[oField.id].rules[ruleNames[iValIndex]];
                    var sGroupIdString = null;
                    sGroupIdString = oIndividualValidation.sGroupID;
                    switch (oIndividualValidation.sValidationType) {
                    case 'required':
                        if (!(vdf.newVOP.Form._oValidator.validateHasValue(oField) == oIndividualValidation.sRuleValue && (!oField.disabled))) {
                            vdf.newVOP.Form._oValidator.addError(oField, fieldErrorTitle, oIndividualValidation.sValidationMessage, iValIndex, sGroupIdString);
                            bFieldValid = false;
                            vdf.newVOP.Form._oValidator._validateAll = false;
                            this.localLayerIFrame(iErrorPaneHeight);
                        } else {
                            vdf.newVOP.Form._oValidator.removeError(oField, iValIndex, sGroupIdString);
                            this.localLayerIFrame(iErrorPaneHeight, true);
                        }
                        break;
                    case 'requiredOptional':
                        if (!(vdf.newVOP.Form._oValidator.validateHasValue(oField) == oIndividualValidation.sRuleValue) && (!oField.disabled)) {
                            if (oField.className.indexOf('optionalField') == -1) {
                                vdf.newVOP.Form._oValidator.addError(oField, fieldErrorTitle, oIndividualValidation.sValidationMessage, iValIndex, sGroupIdString);
                                bFieldValid = false;
                                vdf.newVOP.Form._oValidator._validateAll = false;
                                this.localLayerIFrame(iErrorPaneHeight);
                            }
                        } else {
                            vdf.newVOP.Form._oValidator.removeError(oField, iValIndex, sGroupIdString);
                            this.localLayerIFrame(iErrorPaneHeight, true);
                        }
                        break;
                    case 'requiredEnable':
                        if ((!(vdf.newVOP.Form._oValidator.validateHasValue(oField) == oIndividualValidation.sRuleValue)) && (!oField.disabled)) {
                            if (oField.className.indexOf('optionalField') == -1) {
                                vdf.newVOP.Form._oValidator.addError(oField, fieldErrorTitle, oIndividualValidation.sValidationMessage, iValIndex, sGroupIdString);
                                bFieldValid = false;
                                vdf.newVOP.Form._oValidator._validateAll = false;
                                this.localLayerIFrame(iErrorPaneHeight);
                            }
                        } else {
                            vdf.newVOP.Form._oValidator.removeError(oField, iValIndex, sGroupIdString);
                            this.localLayerIFrame(iErrorPaneHeight, true);
                        }
                        break;
                    case 'required_if':
                        var bFieldRequired = false;
                        var eParentField = null;
                        for (var i = 0, j = oIndividualValidation.aParentFields.length; i < j; i++) {
                            eParentField = $(oIndividualValidation.aParentFields[i]);
                            if (vdf.newVOP.Form._oValidator.validateHasValue(eParentField) == oIndividualValidation.aParentRuleValue[i]) {
                                bFieldRequired = true;
                            }
                        }
                        if (bFieldRequired) {
                            if (!(vdf.newVOP.Form._oValidator.validateHasValue(oField) == oIndividualValidation.sRuleValue)) {
                                vdf.newVOP.Form._oValidator.addError(oField, fieldErrorTitle, oIndividualValidation.sValidationMessage, iValIndex, sGroupIdString);
                                bFieldValid = false;
                                vdf.newVOP.Form._oValidator._validateAll = false;
                                this.localLayerIFrame(iErrorPaneHeight);
                            }
                            else {
                                vdf.newVOP.Form._oValidator.removeError(oField, iValIndex, sGroupIdString);
                                this.localLayerIFrame(iErrorPaneHeight, true);
                            }
                        }
                        else {
                            vdf.newVOP.Form._oValidator.removeError(oField, iValIndex, sGroupIdString);
                            this.localLayerIFrame(iErrorPaneHeight, true);
                        }
                        break;
                    case 'regex':
                        if (vdf.newVOP.Form._oValidator.validateHasValue(oField) && (!oField.hasClassName('dontCheckNow'))) {
                            if ((!oIndividualValidation.sRuleValue.test(oField.getValue())) && (!oField.disabled)) {
                                vdf.newVOP.Form._oValidator.addError(oField, fieldErrorTitle, oIndividualValidation.sValidationMessage, iValIndex, sGroupIdString);
                                bFieldValid = false;
                                vdf.newVOP.Form._oValidator._validateAll = false;
                                this.localLayerIFrame(iErrorPaneHeight);
                                if (isFormHasSubmitted == '') {
                                    invoke_dcsMultiTrack();
                                    isFormHasSubmitted = '';
                                }
                            }
                            else {
                                vdf.newVOP.Form._oValidator.removeError(oField, iValIndex, sGroupIdString);
                                this.localLayerIFrame(iErrorPaneHeight, true);
                            }
                        } else {
                            vdf.newVOP.Form._oValidator.removeError(oField, iValIndex, sGroupIdString);
                            this.localLayerIFrame(iErrorPaneHeight, true);
                        }
                        break;
                    case 'isEqual':
                        if (vdf.newVOP.Form._oValidator.validateHasValue(oField) && (!oField.disabled)) {
                            if (!(oField.getValue() !== oIndividualValidation.sRuleValue)) {
                                vdf.newVOP.Form._oValidator.addError(oField, fieldErrorTitle, oIndividualValidation.sValidationMessage, iValIndex, sGroupIdString);
                                bFieldValid = false;
                                vdf.newVOP.Form._oValidator._validateAll = false;
                                this.localLayerIFrame(iErrorPaneHeight);
                                if (isFormHasSubmitted == '') {
                                    invoke_dcsMultiTrack();
                                    isFormHasSubmitted = '';
                                }
                            }
                            else {
                                vdf.newVOP.Form._oValidator.removeError(oField, iValIndex, sGroupIdString);
                                this.localLayerIFrame(iErrorPaneHeight, true);
                            }
                        }
                        break;
                    case 'isNotEqual':
                        if (vdf.newVOP.Form._oValidator.validateHasValue(oField) && (!oField.disabled)) {
                            if (!(oField.getValue() === oIndividualValidation.sRuleValue)) {
                                vdf.newVOP.Form._oValidator.addError(oField, fieldErrorTitle, oIndividualValidation.sValidationMessage, iValIndex, sGroupIdString);
                                bFieldValid = false;
                                vdf.newVOP.Form._oValidator._validateAll = false;
                                this.localLayerIFrame(iErrorPaneHeight);
                                if (isFormHasSubmitted == '') {
                                    invoke_dcsMultiTrack();
                                    isFormHasSubmitted = '';
                                }
                            }
                            else {
                                vdf.newVOP.Form._oValidator.removeError(oField, iValIndex, sGroupIdString);
                                this.localLayerIFrame(iErrorPaneHeight, true);
                            }
                        }
                        break;
                    case 'isGt':
                        if (vdf.newVOP.Form._oValidator.validateHasValue(oField) && (!oField.disabled)) {
                            if (!(oField.getValue().length > oIndividualValidation.sRuleValue)) {
                                vdf.newVOP.Form._oValidator.addError(oField, fieldErrorTitle, oIndividualValidation.sValidationMessage, iValIndex, sGroupIdString);
                                bFieldValid = false;
                                vdf.newVOP.Form._oValidator._validateAll = false;
                                this.localLayerIFrame(iErrorPaneHeight);
                                if (isFormHasSubmitted == '') {
                                    invoke_dcsMultiTrack();
                                    isFormHasSubmitted = '';
                                }
                            }
                            else {
                                vdf.newVOP.Form._oValidator.removeError(oField, iValIndex, sGroupIdString);
                                this.localLayerIFrame(iErrorPaneHeight, true);
                            }
                        }
                        break;
                    case 'isLT':
                        if ((!(oField.getValue().length < oIndividualValidation.sRuleValue)) && (!oField.disabled)) {
                            vdf.newVOP.Form._oValidator.addError(oField, fieldErrorTitle, oIndividualValidation.sValidationMessage, iValIndex, sGroupIdString);
                            bFieldValid = false;
                            vdf.newVOP.Form._oValidator._validateAll = false;
                            this.localLayerIFrame(iErrorPaneHeight);
                            if (isFormHasSubmitted == '') {
                                invoke_dcsMultiTrack();
                                isFormHasSubmitted = '';
                            }
                        }
                        else {
                            vdf.newVOP.Form._oValidator.removeError(oField, iValIndex, sGroupIdString);
                            this.localLayerIFrame(iErrorPaneHeight, true);
                        }
                        break;
                    case 'minLength':
                        if (((oField.getValue() != "") && (!(this.trimString(oField.getValue()).length >= oIndividualValidation.sRuleValue))) && (!oField.disabled)) {
                            vdf.newVOP.Form._oValidator.addError(oField, fieldErrorTitle, oIndividualValidation.sValidationMessage, iValIndex, sGroupIdString);
                            bFieldValid = false;
                            vdf.newVOP.Form._oValidator._validateAll = false;
                            this.localLayerIFrame(iErrorPaneHeight);
                            if (isFormHasSubmitted == '') {
                                invoke_dcsMultiTrack();
                                isFormHasSubmitted = '';
                            }
                        }
                        else {
                            vdf.newVOP.Form._oValidator.removeError(oField, iValIndex, sGroupIdString);
                            this.localLayerIFrame(iErrorPaneHeight, true);
                        }
                        break;
                    case 'maxLength':
                        if ((!(oField.getValue().length <= oIndividualValidation.sRuleValue)) && (!oField.disabled)) {
                            vdf.newVOP.Form._oValidator.addError(oField, fieldErrorTitle, oIndividualValidation.sValidationMessage, iValIndex, sGroupIdString);
                            bFieldValid = false;
                            vdf.newVOP.Form._oValidator._validateAll = false;
                            this.localLayerIFrame(iErrorPaneHeight);
                            if (isFormHasSubmitted == '') {
                                invoke_dcsMultiTrack();
                                isFormHasSubmitted = '';
                            }
                        }
                        else {
                            vdf.newVOP.Form._oValidator.removeError(oField, iValIndex, sGroupIdString);
                            this.localLayerIFrame(iErrorPaneHeight, true);
                        }
                        break;
                    case 'matchesField':
                        if (vdf.newVOP.Form._oValidator.validateHasValue(oField) && (!oField.disabled)) {
                            if (($(oIndividualValidation.sRuleValue).getValue()) && (oField.getValue() != $(oIndividualValidation.sRuleValue).getValue())) {
                                vdf.newVOP.Form._oValidator.addError(oField, fieldErrorTitle, oIndividualValidation.sValidationMessage, iValIndex, sGroupIdString);
                                bFieldValid = false;
                                vdf.newVOP.Form._oValidator._validateAll = false;
                                this.localLayerIFrame(iErrorPaneHeight);
                                if (isFormHasSubmitted == '') {
                                    invoke_dcsMultiTrack();
                                    isFormHasSubmitted = '';
                                }
                            }
                            else {
                                vdf.newVOP.Form._oValidator.removeError(oField, iValIndex, sGroupIdString);
                                this.localLayerIFrame(iErrorPaneHeight, true);
                            }
                        }
                        else {
                            vdf.newVOP.Form._oValidator.removeError(oField, iValIndex, sGroupIdString);
                            this.localLayerIFrame(iErrorPaneHeight, true);
                        }
                        break;
					case 'notmatchesField':
                        if (vdf.newVOP.Form._oValidator.validateHasValue(oField) && (!oField.disabled)) {
                            if (($(oIndividualValidation.sRuleValue).getValue()) && (oField.getValue() == $(oIndividualValidation.sRuleValue).getValue())) {
                                vdf.newVOP.Form._oValidator.addError(oField, fieldErrorTitle, oIndividualValidation.sValidationMessage, iValIndex, sGroupIdString);
                                bFieldValid = false;
                                vdf.newVOP.Form._oValidator._validateAll = false;
                                this.localLayerIFrame(iErrorPaneHeight);
                                if (isFormHasSubmitted == '') {
                                    invoke_dcsMultiTrack();
                                    isFormHasSubmitted = '';
                                }
                            }
                            else {
                                vdf.newVOP.Form._oValidator.removeError(oField, iValIndex, sGroupIdString);
                                this.localLayerIFrame(iErrorPaneHeight, true);
                            }
                        }
                        else {
                            vdf.newVOP.Form._oValidator.removeError(oField, iValIndex, sGroupIdString);
                            this.localLayerIFrame(iErrorPaneHeight, true);
                        }
                        break;
                    case 'customValidation':
                        if ((!(oIndividualValidation.sRuleValue(oField.getValue()))) && (!oField.disabled)) {
                            vdf.newVOP.Form._oValidator.addError(oField, fieldErrorTitle, oIndividualValidation.sValidationMessage, iValIndex, sGroupIdString);
                            bFieldValid = false;
                            vdf.newVOP.Form._oValidator._validateAll = false;
                            this.localLayerIFrame(iErrorPaneHeight);
                            if (isFormHasSubmitted == '') {
                                invoke_dcsMultiTrack();
                                isFormHasSubmitted = '';
                            }
                        }
                        else {
                            vdf.newVOP.Form._oValidator.removeError(oField, iValIndex, sGroupIdString);
                            this.localLayerIFrame(iErrorPaneHeight, true);
                        }
                        break;
                    }
                }
                if (bFieldValid) {
                    //oField.removeClassName(this._validationFailed);
                    this._oMessagePane.checkErrorBlock(oField.id, sGroupIdString);
                }
                else {
                    oField.addClassName(this._validationFailed);
                }
                return bFieldValid;
            }
        }
    },
	trimString: function(str) {
		while (str.charAt(0)==' ')
			str=str.substring(1);
		while (str.charAt(str.length - 1)==' ')
			str=str.substring(0,str.length - 1);
		return str;
	},
    validateAll: function (event) {
        var _this = this;
        var sHashKey;
        var temp;
        this._validateAll = true;
        _this.aRequireds.each(function (oField, iIndex) {
            if (sHashKey = _this.hasValidationInformation(oField)) {
                temp = _this.reFieldValidator(oField, iIndex);
            }
        });
        if (!this._validateAll && event) {
            Event.stop(event);
            _this._oMessagePane.focus;
        }
    },
    updateItemsToValidateArray: function () {
        var _this = vdf.newVOP.Form._oValidator ? vdf.newVOP.Form._oValidator : this;
        _this.aRequireds = $$('.' + _this._validateClass);
    },
    addError: function (oField, sErrorTitle, sError, iIndex, sGroupID) {
        this._oMessagePane.addErrorMessage(oField.id, sErrorTitle, sError, iIndex, sGroupID);
    },
    removeError: function (oField, iIndex, sGroupID) {
        var clearOfErrors = this._oMessagePane.removeErrorMessage(oField.id, iIndex, sGroupID);
    },
    validateHasValue: function (oField) {
        if (oField.nodeName === "SELECT") {
            if (!oField.selectedIndex) return false;
        }
        else if (oField.readAttribute('type') == 'checkbox') {
            if (!oField.checked) return false;
        }
		else if (oField.readAttribute('type') == 'radio') {
            if (!oField.checked) return false;
        }
        else if (!oField.present()) {
            return false;
        }
        return true;
    },
    validateNumeric: function (oField, iMinLength, iMaxLength) {
        var isNumericPattern = new RegExp('^[\\d\\s ().-]' + '{' + iMinLength + ',' + iMaxLength + '}' + '$');
        return isNumericPattern.test(oField.getValue());
    },
    validatePhoneNumber: function (oField, iMinLength, iMaxLength, startingWith) {
        var result = this.validateNumeric(oField, iMinLength, iMaxLength);
        if (result) {
            var startsWithPattern = new RegExp(startingWith + '[\\d\\s ().-]*$');
            result = startsWithPattern.test(oField.getValue());
        }
        return result;
    },
	localLayerIFrame : function (iErrorPaneHeight,option) {
		if (this.sMessagePaneReference === 'MessagePane') {
			if (option) {
				errorLayerIFrame(iErrorPaneHeight, 'yes');
			}
			else {
				errorLayerIFrame(iErrorPaneHeight);
			}
		}
	}
});
vdf.newVOP.PostcodeSearch = Class.create({
    initialize: function (requestURL) {
        var _this = this;
        this.url = requestURL;
        this.aAddressHash = [];
        this.serverTime = null;
        this.eBlankPreviousAddressBlock = null;
        this.aFullAddressBlocks = $$("fieldset.fullAddressBlock");
        var currentAddressBlock = this.aFullAddressBlocks[0].select('.addressBlock');
        vdf.newVOP.Form.disableFields(true, currentAddressBlock[0], true);
        this.previousAddressInit();
        this.aPostCodeSearchBoxes = $$("input.postCodeField");
        this.postCodeButtons = $$(".postCodeButton");
        this.addressBlock = $$("div.addressBlock");
        this.postCodeButtons.each(function (eSearchButton, index) {
            Event.observe(eSearchButton, "click", function (event) {
                event.stop();
                if (_this.aPostCodeSearchBoxes[index].present()) {
                    _this.postcodeSearch(this, index);
                }
            });
        });
    },
    previousAddressInit: function () {
        var _this = this;
        _this.aFullAddressBlocks[1].hide();
        vdf.newVOP.Form.disableFields(true, _this.aFullAddressBlocks[1], true);
        _this.eBlankPreviousAddressBlock = _this.aFullAddressBlocks[1].cloneNode(true);
        _this.updateAddressBlockFields(_this.aFullAddressBlocks[1], 1);
        $$("div.dateController").each(function (dateControllerItem, index) {
            _this.setUpDateController(dateControllerItem, index);
        });
    },
    postcodeSearch: function (oButton, iIndex) {
        oButton.writeAttribute('disabled', value = 'disabled');
        oButton.update('<span><span>Loading</span></span>');
        this.requestHandler(oButton, iIndex);
    },
    addActivityIndicator: function (oButton) {
        oButton.insert({
            "after": new Element("div", {
                "className": "postCodeLoader"
            }).update("<p>Loading</p>")
        });
    },
    requestHandler: function (oButton, iIndex) {
        var _this = this;
        var sSearchUrl = _this.url + '?' + _this.aPostCodeSearchBoxes[iIndex].value;
        new Ajax.Request(sSearchUrl, {
            method: 'get',
            contentType: 'application/xml',
            onSuccess: function (transport) {
                oButton.removeAttribute('disabled');
                oButton.update('<span><span>Find address</span></span>');
                _this.responseHandler(transport, iIndex);
                _this.serverTime = new Date(transport.getHeader("Date"));
            },
            onFailure: function () {
                alert('Something went wrong...')
            },
            onComplete: function () {}
        });
    },
    responseHandler: function (transport, iIndex) {
        var _this = this;
        var responseXML = transport.responseXML || (function () {
            alert("No address matching this postcode was found.")
        })();
        var prefix = 'address:';
        var addressXML = responseXML.getElementsByTagName(prefix + 'Address');
        if (!addressXML.length) {
            prefix = '';
            addressXML = responseXML.getElementsByTagName('Address');
        }
        $A(addressXML).each(function (item, index) {
            _this.aAddressHash[index] = new Hash();
            for (var i = 0, j = item.childNodes.length; i < j; i++) {
                if (item.childNodes[i].nodeType == 1) {
                    var node = item.childNodes[i];
                    var prefix = node.prefix;
                    switch (node.nodeName) {
                    case prefix + ":flat":
                        _this.aAddressHash[index].update({
                            "flat": node.textContent || node.text
                        })
                        break;
                    case prefix + ":houseNumber":
                        _this.aAddressHash[index].update({
                            "houseNumber": node.textContent || node.text
                        })
                        break;
                    case prefix + ":houseName":
                        _this.aAddressHash[index].update({
                            "houseName": node.textContent || node.text
                        })
                        break;
                    case prefix + ":streetLine1":
                        _this.aAddressHash[index].update({
                            "streetLine1": node.textContent || node.text
                        })
                        break;
                    case prefix + ":streetLine2":
                        _this.aAddressHash[index].update({
                            "streetLine2": node.textContent || node.text
                        })
                        break;
                    case prefix + ":city":
                        _this.aAddressHash[index].update({
                            "city": node.textContent || node.text
                        })
                        break;
                    case prefix + ":county":
                        _this.aAddressHash[index].update({
                            "county": node.textContent || node.text
                        })
                        break;
                    case prefix + ":country":
                        _this.aAddressHash[index].update({
                            "country": node.textContent || node.text
                        })
                        break;
                    case prefix + ":postcode":
                        _this.aAddressHash[index].update({
                            "postcode": node.textContent || node.text
                        })
                        break;
                    }
                }
            }
        })
        this.createAddressList(iIndex)
    },
    createAddressList: function (iIndex) {
        var _this = this;
        var stringHTML = "<span>* Select a possible match:</span>";
        var addressLabel = new Element("label", {
            "htmlFor": "addressMatch_" + iIndex,
            "className": "formBlock",
            id: "address_" + iIndex
        }).update(stringHTML);
        var addressList = new Element("select", {
            id: "addressMatch_" + iIndex,
            name: "addressMatch_" + iIndex
        });
        addressList.insert(new Element("option", {
            selected: "selected"
        }).update("Select your address..."));
        this.aAddressHash.each(function (item, index) {
            var addressHTML = "" + item.get("flat") + ", " + item.get("houseName") + item.get("houseNumber") + ", " + item.get("streetLine1") + ", " + item.get("streetLine2") + ", " + item.get("city") + ", " + item.get("county") + ", " + item.get("country");
            addressList.insert(new Element("option").update(addressHTML));
        })
        Event.observe(addressList, "change", function (e) {
            (this.selectedIndex) ? _this.updateAddress(this, iIndex) : _this.clearAddress(this);
        });
        addressLabel.insert(addressList);
        if ($("address_" + iIndex)) {
            $("address_" + iIndex).remove();
        }
        this.addressBlock[iIndex].insert({
            "top": addressLabel
        });
        vdf.newVOP.Form.disableFields(false, this.addressBlock[iIndex], true);
        vdf.Tools.Expander.expand(this.addressBlock[iIndex], this.addressBlock[iIndex].offsetHeight);
    },
    updateAddress: function (oSelectAddress, iIndex) {
        var aAddressFields = oSelectAddress.parentNode.nextSiblings();
        var currentAddress = this.aAddressHash[oSelectAddress.selectedIndex - 1];
        for (var i = 0, j = aAddressFields.length; i < j; ++i) {
            if ((field = aAddressFields[i].select("input#flatNumber" + iIndex)[0]) && !currentAddress.get("flat").blank()) {
                field.value = currentAddress.get("flat");
            }
            else if ((field = aAddressFields[i].select("input#houseNameOrNumber" + iIndex)[0]) && (!currentAddress.get("houseName").blank() || !currentAddress.get("houseNumber").blank())) {
                field.value = currentAddress.get("houseName");
            }
            else if ((field = aAddressFields[i].select("input#streetAddress" + iIndex)[0]) && (!currentAddress.get("streetLine1").blank() || !currentAddress.get("streetLine2").blank())) {
                field.value = currentAddress.get("streetLine1") + " " + currentAddress.get("streetLine2");
            }
            else if ((field = aAddressFields[i].select("input#townAddress" + iIndex)[0]) && !currentAddress.get("city").blank()) {
                field.value = currentAddress.get("city");
            }
            else if ((field = aAddressFields[i].select("input#countryAddress" + iIndex)[0]) && !currentAddress.get("country").blank()) {
                field.value = currentAddress.get("country");
            }
            else if ((field = aAddressFields[i].select("input#postCodeAddress" + iIndex)[0]) && !currentAddress.get("postcode").blank()) {
                field.value = currentAddress.get("postcode");
            }
        }
        vdf.newVOP.Form._oValidator.validateAll();
    },
    clearAddress: function (oSelectAddress) {
        var aAddressFields = oSelectAddress.parentNode.nextSiblings();
        var field;
        for (var i = 0, j = aAddressFields.length; i < j; ++i) {
            if (field = aAddressFields[i].select("input")[0]) {
                field.value = "";
            }
        }
    },
    setUpDateController: function (dateControllerItem, index) {
        var _this = this;
        var today = _this.serverTime || new Date();
        var threeYearsAgo = today.setFullYear(today.getFullYear() - 3, today.getMonth(), today.getDate());
        var moveDate = new Date();
        var aDateControllerItemSelects = dateControllerItem.select("select");
        var oMonth = aDateControllerItemSelects[0];
        var oYear = aDateControllerItemSelects[1];
        Event.observe(oMonth, "change", function (event) {
            if (this.selectedIndex && oYear.selectedIndex) {
                moveDate.setFullYear(parseInt(oYear.value), parseInt(this.value) - 1, today.getDate());
                if ((threeYearsAgo - moveDate) <= 0) {
                    _this.showPreviousAddressBlocks(_this.aFullAddressBlocks, index + 1);
                } else {
                    if (_this.aFullAddressBlocks[index + 1]) {
                        _this.hidePreviousAddressBlock(index + 1);
                    }
                }
            }
        });
        Event.observe(oYear, "change", function (event) {
            if (this.selectedIndex && oMonth.selectedIndex) {
                moveDate.setFullYear(parseInt(this.value), parseInt(oMonth.value) - 1, today.getDate());
                if ((threeYearsAgo - moveDate) <= 0) {
                    _this.showPreviousAddressBlocks(_this.aFullAddressBlocks, index + 1);
                } else {
                    if (_this.aFullAddressBlocks[index + 1]) {
                        _this.hidePreviousAddressBlock(index + 1);
                    }
                }
            }
        });
    },
    showPreviousAddressBlocks: function (aAddressBlocks, index) {
        var eAddressBlock = aAddressBlocks[index];
        this.updateDateControllerValues(eAddressBlock, aAddressBlocks[index - 1], index);
        eAddressBlock.show();
        vdf.newVOP.Form.disableFields(false, eAddressBlock, false);
        if (!aAddressBlocks[index + 1]) {
            this.createAddressBlock(aAddressBlocks, (index + 1));
        }
    },
    createAddressBlock: function (aAddressBlocks, index) {
        _this = this;
        var newAddressBlock = _this.eBlankPreviousAddressBlock.cloneNode(true);
        _this.updateAddressBlockFields(newAddressBlock, index);
        var aRequiredFields = newAddressBlock.select('.' + vdf.newVOP.Form._oValidator._validateClass);
        vdf.newVOP.Form._oValidator.updateItemsToValidateArray();
        vdf.newVOP.Form._oValidator.registerEvents(aRequiredFields);
        var eSearchButton = newAddressBlock.select(".postCodeButton")[0];
        Event.observe(eSearchButton, "click", function (event) {
            event.stop();
            if (_this.aPostCodeSearchBoxes[index].present()) {
                _this.postcodeSearch(this, index);
            }
        });
        $$('.previousAddressBlockContainer')[0].insert(newAddressBlock, {
            position: 'after'
        });
        _this.aFullAddressBlocks = $$("fieldset.fullAddressBlock");
        _this.addressBlock = $$("div.addressBlock");
        _this.aPostCodeSearchBoxes = $$("input.postCodeField");
        _this.setUpDateController(newAddressBlock.select("div.dateController")[0], index);
    },
    hidePreviousAddressBlock: function (index) {
        _this = this;
        _this.aFullAddressBlocks[index].hide();
        vdf.newVOP.Form.disableFields(true, _this.aFullAddressBlocks[index], true);
        vdf.newVOP.Form._oValidator.validateAll();
    },
    updateDateControllerValues: function (eTargetAddressBlock, eSourceAddressBlock, index) {
        var aPreviousDates = eSourceAddressBlock.select('#monthMoved' + (index - 1), '#yearMoved' + (index - 1));
        var aTargetDates = eTargetAddressBlock.select('#monthMoved' + (index), '#yearMoved' + (index));
        aTargetDates[0].selectedIndex = aPreviousDates[0].selectedIndex;
        aTargetDates[1].selectedIndex = aPreviousDates[1].selectedIndex;
    },
    updateAddressBlockFields: function (eAddressBlock, index) {
        eAddressBlock.select("input", "select").each(function (inputElement, elementIndex) {
            inputElement.writeAttribute('name', value = inputElement.readAttribute('name') + index);
            inputElement.writeAttribute('id', value = inputElement.readAttribute('id') + index);
        });
        eAddressBlock.select("label").each(function (labelElement, labelIndex) {
            labelElement.writeAttribute('for', value = labelElement.readAttribute('for') + index);
        });
    }
});

vdf.Tools.SubscriptionChecks = {
    _aSubscriptionCheckboxTargetLinks: [],
    _sSubscriptionBlockClass: '.subscriptionOption',
    _sSubscriptionCheckboxLinkClass: '.subscriptionCheckbox',
    _sSubscribedImage: '/en_GB/assets/sso/images/subscription_tick.gif',
    _sAddSubscriptionImage: '/en_GB/assets/sso/images/subscription_add.gif',
    _sRemoveSubscriptionImage: '/en_GB/assets/sso/images/subscription_remove.gif',
    _sLinkStateSubscribed: 'subscribed',
    _sLinkStateUnsubscribed: 'addSubscription',
    init: function (aSubscriptionCheckboxTargetLinks) {
        vdf.Tools.SubscriptionChecks._aSubscriptionCheckboxTargetLinks = aSubscriptionCheckboxTargetLinks;
        vdf.Tools.SubscriptionChecks._aSubscriptionCheckboxTargetLinks.each(function (element) {
            Event.observe(element, "click", vdf.Tools.SubscriptionChecks.callChangeCheckboxState.bind(element));
            Event.attachMouseEnter(element.parentNode.parentNode, function () {
                vdf.Tools.SubscriptionChecks.setSubscriptionCheckStyle('unsubscribe', element);
            });
            Event.attachMouseLeave(element.parentNode.parentNode, function () {
                vdf.Tools.SubscriptionChecks.setSubscriptionCheckStyle('subscribe', element);
            });
        });
    },
    callChangeCheckboxState: function (event) {
        if (vdf.Views.List.PanHandle._ePanHandle == null) {
            vdf.Tools.SubscriptionChecks.changeCheckboxState(event, this);
        }
    },
    changeCheckboxState: function (event, eThis) {
        if (event) {
            Event.stop(event);
        }
        if (!eThis) {
            eThis = this
        }
        var eParentBox = eThis.parentNode.parentNode;
        var eCheckbox = $(eParentBox).select('input[type~=checkbox]')[0];
        var eImage = eThis.select('img')[0];
        var eLabel = eParentBox.select('label')[0];
        var bSubscribe = !eCheckbox.checked;
        vdf.Tools.SubscriptionChecks.setCheckBoxState(bSubscribe, eCheckbox, eImage, eLabel);
    },
    setCheckBoxState: function (bSubscribe, eCheckbox, eImage, eLabel) {
        if (bSubscribe) {
            eCheckbox.checked = true;
            eImage.src = vdf.Tools.SubscriptionChecks._sSubscribedImage;
            eLabel.removeClassName(vdf.Tools.SubscriptionChecks._sLinkStateUnsubscribed);
            eLabel.addClassName(vdf.Tools.SubscriptionChecks._sLinkStateSubscribed);
            eLabel.innerHTML = 'Subscribed<br /><span>Untick to unsubscribe</span>';
        }
        else {
            eCheckbox.checked = false;
            eImage.src = vdf.Tools.SubscriptionChecks._sAddSubscriptionImage;
            eLabel.removeClassName(vdf.Tools.SubscriptionChecks._sLinkStateSubscribed);
            eLabel.removeClassName('removeSubscription');
            eLabel.addClassName(vdf.Tools.SubscriptionChecks._sLinkStateUnsubscribed);
            eLabel.innerHTML = 'Subscribe';
        }
    },
    setSubscriptionCheckStyle: function (sStyle, element) {
        var eParentBox = element.parentNode.parentNode;
        var eLabel = eParentBox.select('label')[0];
        if (eLabel.hasClassName('subscribed')) {
            var eImage = element.select('img')[0];
            if (sStyle == 'unsubscribe') {
                eImage.src = vdf.Tools.SubscriptionChecks._sRemoveSubscriptionImage;
                eLabel.addClassName('removeSubscription');
                eLabel.innerHTML = 'UnSubscribe';
            }
            else {
                eImage.src = vdf.Tools.SubscriptionChecks._sSubscribedImage;
                eLabel.removeClassName('removeSubscription');
                eLabel.innerHTML = 'Subscribed<br /><span>Untick to unsubscribe</span>';
            }
        }
    },
    createSubscriptionCheckLink: function (aElements) {
        aElements.each(function (element) {
            var eParentBox = element.parentNode.parentNode;
            var eCheckbox = eParentBox.select('input[type~=checkbox]')[0];
            var sID = eCheckbox.id;
            var eLabel = eParentBox.select('label')[0];
            eCheckbox.writeAttribute('id', sID + '_link');
            eLabel.writeAttribute('for', sID + '_link');
            Event.stopObserving(element, "click");
            Event.observe(element, "click", vdf.Tools.SubscriptionChecks.updateSubscriptionCheckLink.bind(element));
            Event.attachMouseEnter(element.parentNode.parentNode, function () {
                vdf.Tools.SubscriptionChecks.setSubscriptionCheckStyle('unsubscribe', element);
            });
            Event.attachMouseLeave(element.parentNode.parentNode, function () {
                vdf.Tools.SubscriptionChecks.setSubscriptionCheckStyle('subscribe', element);
            });
        });
    },
    removeSubscriptionCheckLink: function (aElements) {
        aElements.each(function (element) {
            Event.stopObserving(element, "click");
            element = null;
        });
    },
    updateSubscriptionCheckLink: function (event) {
        if (event) Event.stop(event);
        var eParentBox = this.parentNode.parentNode;
        var eCheckbox = $(eParentBox).select('input[type~=checkbox]')[0];
        var eImage = this.select('img')[0];
        var eLabel = eParentBox.select('label')[0];
        var bSubscribe = !eCheckbox.checked;
        vdf.Tools.SubscriptionChecks.setCheckBoxState(bSubscribe, eCheckbox, eImage, eLabel);
        var sID = eCheckbox.id;
        sID = sID.substr(0, sID.length - 5);
        var eOriginalCheckbox = $(sID);
        var eParentNode = eOriginalCheckbox.parentNode.parentNode;
        var eRealElement = $(eParentNode).select(vdf.Tools.SubscriptionChecks._sSubscriptionCheckboxLinkClass)[0];
        var eRealImage = eRealElement.select('img')[0];
        var eRealLabel = $(eParentNode).select('label')[0];
        vdf.Tools.SubscriptionChecks.setCheckBoxState(bSubscribe, eOriginalCheckbox, eRealImage, eRealLabel);
    }
};

vdf.Tools.Expander = {
    _sTogglersClass: ".toggler",
    _sResponderClass: ".responder",
    _sContractedClass: "toggler_closed",
    _aTogglers: [],
    _aResponders: [],
    _aResponderHeights: [],
    _aResponderDisplay: [],
    examplePublicProperty: null,
    init: function () {
        vdf.Tools.Expander._aTogglers = $$(vdf.Tools.Expander._sTogglersClass);
        vdf.Tools.Expander._aResponders = $$(vdf.Tools.Expander._sResponderClass);
        vdf.Tools.Expander._aTogglers.each(function (eArrayElement, iArrayIndex) {
            Event.observe(eArrayElement, 'click', function (event) {
                vdf.Tools.Expander.expandContract(iArrayIndex, this);
                Event.stop(event);
            });
        });
        $(vdf.Tools.Expander._aResponders).each(function (eArrayElement, iArrayIndex) {
            vdf.Tools.Expander._aResponderHeights[iArrayIndex] = $(eArrayElement).getHeight();
            if ($(eArrayElement).hasClassName(vdf.Tools.Expander._sContractedClass)) {
                $(eArrayElement).hide();
            }
        });
    },
    expandContract: function (iArrayIndex, eCurrentToggler) {
        var eResponder = vdf.Tools.Expander._aResponders[iArrayIndex];
        var iCurrentHeight = vdf.Tools.Expander._aResponderHeights[iArrayIndex];
        if (eResponder.style.display !== "none") {
            vdf.Tools.Expander.contract(eResponder, iCurrentHeight);
            $(eCurrentToggler).addClassName(vdf.Tools.Expander._sContractedClass);
        } else {
            vdf.Tools.Expander.expand(eResponder, iCurrentHeight);
            if ($(eCurrentToggler).hasClassName(vdf.Tools.Expander._sContractedClass)) {
                $(eCurrentToggler).removeClassName(vdf.Tools.Expander._sContractedClass);
            }
        }
        return false;
    },
    expand: function (eResponder, iCurrentHeight) {
        $(eResponder).tween({
            alpha: {
                time: 0,
                duration: 0.2,
                start: 20,
                stop: 100,
                transition: FX.quadInOut
            },
            height: {
                time: 0,
                duration: 0.2,
                start: 0,
                stop: iCurrentHeight,
                units: "px",
                transition: FX.quadInOut,
                onStop: function (element) {
                    $(element).setStyle({
                        height: "",
                        display: ""
                    });
                }
            }
        });
        Animate.play();
        return false;
    },
    contract: function (eResponder, iCurrentHeight) {
        eResponder.setStyle({
            overflow: "hidden"
        });
        eResponder.tween({
            alpha: {
                time: 0,
                duration: 0.2,
                start: 100,
                stop: 20,
                transition: FX.quadInOut
            },
            height: {
                time: 0,
                duration: 0.4,
                start: iCurrentHeight,
                stop: 0,
                units: "px",
                transition: FX.quadInOut,
                onStop: function (element) {
                    $(element).setStyle({
                        display: "none"
                    });
                }
            }
        });
        Animate.play();
        return false;
    },
    exampleMethod: function () {
        var iExampleInteger = 1;
        var sExampleString = "string";
        var bExampleBoolean = true;
        var eExampleElement = document.createElement("div");
        var oExampleObject = {};
        var aExampleArray = [];
        var fExampleFunction = vdf.Tools.Expander;
    }
};

vdf.newVOP.DeviceCarousel = {
    _eDeviceCarousel: null,
    _eDeviceCarouselList: null,
    _sDeviceCarousel: "div#devicesCarousel",
    _sLeftArrowImg: '/en_GB/assets/sso/images/carousel-arrow-left.gif',
    _sRightArrowImg: '/en_GB/assets/sso/images/carousel-arrow-right.gif',
    _iScrollAmmount: 49,
    _fHideControls: null,
    init: function () {
        var aCarouselObjects = $$(vdf.newVOP.DeviceCarousel._sDeviceCarousel);
        if (aCarouselObjects[0]) {
            vdf.newVOP.DeviceCarousel._eDeviceCarousel = aCarouselObjects[0];
            vdf.newVOP.DeviceCarousel._eDeviceCarouselList = aCarouselObjects[0].select('ul')[0];
            vdf.newVOP.DeviceCarousel.createScrollButtons(vdf.newVOP.DeviceCarousel._eDeviceCarousel);
            var aItems = vdf.newVOP.DeviceCarousel._eDeviceCarouselList.select('li');
            vdf.newVOP.DeviceCarousel._iScrollAmmount = aItems[1].getWidth();
            vdf.newVOP.DeviceCarousel._eDeviceCarouselList.setStyle({
                width: (aItems.length * vdf.newVOP.DeviceCarousel._iScrollAmmount + 17) + 'px'
            });
            Event.attachMouseEnter(vdf.newVOP.DeviceCarousel._eDeviceCarousel, function () {
                vdf.newVOP.DeviceCarousel.controlsFade(vdf.newVOP.DeviceCarousel._eDeviceCarousel, 'show');
            });
            Event.attachMouseLeave(vdf.newVOP.DeviceCarousel._eDeviceCarousel, function () {
                vdf.newVOP.DeviceCarousel.controlsFade(vdf.newVOP.DeviceCarousel._eDeviceCarousel, 'hide');
            });
        }
    },
    createScrollButtons: function (eDeviceCarousel) {
        var leftArrow = new Element('div', {
            'class': 'galleryLeft hidden'
        }).update('<a href="#"><img src="' + vdf.newVOP.DeviceCarousel._sLeftArrowImg + '" alt="Scroll Left"/></a>');
        var rightArrow = new Element('div', {
            'class': 'galleryRight hidden'
        }).update('<a href="#"><img src="' + vdf.newVOP.DeviceCarousel._sRightArrowImg + '" alt="Scroll Right"/></a>');
        leftArrow.observe("click", function (event) {
            Event.stop(event);
            vdf.newVOP.DeviceCarousel.moveAlong(eDeviceCarousel, 'reverse');
        });
        rightArrow.observe("click", function (event) {
            Event.stop(event);
            vdf.newVOP.DeviceCarousel.moveAlong(eDeviceCarousel, 'forward');
        });
        eDeviceCarousel.insert(leftArrow, {
            position: 'before'
        });
        eDeviceCarousel.insert(rightArrow, {
            position: 'before'
        });
    },
    moveAlong: function (eDeviceCarousel, sDirection) {
        var eGalleryContainer = vdf.newVOP.DeviceCarousel._eDeviceCarousel;
        var aGalleryImages = eDeviceCarousel.select('li');
        var iImageCount = aGalleryImages.length;
        var iCurrentPos = eGalleryContainer.scrollLeft;
        var iNewPos;
        switch (sDirection) {
        case 'forward':
            iNewPos = iCurrentPos + vdf.newVOP.DeviceCarousel._iScrollAmmount;
            vdf.newVOP.DeviceCarousel.scrollGalleryContent(eGalleryContainer, iCurrentPos, iNewPos);
            break;
        case 'reverse':
            iNewPos = iCurrentPos - vdf.newVOP.DeviceCarousel._iScrollAmmount;
            vdf.newVOP.DeviceCarousel.scrollGalleryContent(eGalleryContainer, iCurrentPos, iNewPos);
            break;
        }
    },
    scrollGalleryContent: function (eGalleryContainer, iCurrentPos, iNewPos) {
        eGalleryContainer.tween({
            scrollLeft: {
                time: 0,
                duration: 0.7,
                start: iCurrentPos,
                stop: iNewPos,
                transition: FX.quadInOut,
                onStop: vdf.newVOP.DeviceCarousel.refreshControls
            }
        });
        Animate.play();
        return false;
    },
    controlsFade: function (element, action) {
        var oLeftArrow = element.select(".galleryLeft")[0];
        var oRightArrow = element.select(".galleryRight")[0];
        var bShowLeftArrow;
        var bShowRightArrow;
        bShowLeftArrow = vdf.newVOP.DeviceCarousel._eDeviceCarousel.scrollLeft > 0;
        bShowRightArrow = (vdf.newVOP.DeviceCarousel._eDeviceCarousel.scrollLeft + vdf.newVOP.DeviceCarousel._eDeviceCarousel.getWidth() + 5) < vdf.newVOP.DeviceCarousel._eDeviceCarousel.scrollWidth;
        switch (action) {
        case 'show':
            if (bShowLeftArrow) {
                oLeftArrow.removeClassName('hidden');
            }
            if (bShowRightArrow) {
                oRightArrow.removeClassName('hidden');
            }
            break;
        case 'hide':
            oLeftArrow.addClassName('hidden');
            oRightArrow.addClassName('hidden');
            break;
        case 'refresh':
            if (bShowLeftArrow) {
                oLeftArrow.removeClassName('hidden');
            }
            else {
                oLeftArrow.addClassName('hidden');
            }
            if (bShowRightArrow) {
                oRightArrow.removeClassName('hidden');
            }
            else {
                oRightArrow.addClassName('hidden');
            }
            break;
        }
    },
    refreshControls: function () {
        vdf.newVOP.DeviceCarousel.controlsFade(vdf.newVOP.DeviceCarousel._eDeviceCarousel, 'refresh');
    }
};

vdf.Views = {
    init: function () {
        vdf.Views.List.init();
    }
};

vdf.Views.List = {
    _sListRollOverClassHolderName: "#listView",
    _sListItem: ".productList",
    _eListViewHolder: null,
    _iWrapperHeight: null,
    _iWrapperWidth: null,
    _oItemHeight: {},
    _oItemWidth: {},
    init: function () {
        vdf.Views.List._eListViewHolder = $$(vdf.Views.List._sListRollOverClassHolderName)[0];
        if (vdf.Views.List._eListViewHolder) {
            vdf.Views.List.Rollover.init();
            vdf.Views.List.PanHandle.init();
        }
    }
};

vdf.Views.List.PanHandle = {
    _sDetailsRef: ".details_panHandle",
    _sLightBoxID: "detailsLightBox",
    _sPanHandleWrapperRef: "panHandleWrapper",
    _sPanHandleRef: "panHandle",
    _sPanHandleInnerRef: "panHandleInner",
    _ePanHandleInfo: null,
    _ePanHandle: null,
    _oPageCache: {},
    _sCurrentHref: null,
    examplePublicProperty: null,
    init: function () {
        var aLightBoxes = $$(vdf.Views.List.PanHandle._sDetailsRef);
        aLightBoxes.each(function (element) {
            Event.observe(element, "click", vdf.Views.List.PanHandle.triggerPanHandle);
        });
    },
    triggerPanHandle: function (event) {
        if (!$(event.target).hasClassName("link_close") && !$(event.target.parentNode).hasClassName("link_close")) {
            if (vdf.Views.List.PanHandle._ePanHandle !== null) {
                vdf.Views.List.PanHandle.closeLightBox(event);
            }
            vdf.Views.List.PanHandle.createPanHandle(event, this);
        }
    },
    createPanHandle: function (event, eTrigger) {
        var eContainer = eTrigger.parentNode.parentNode;
        var panHandle = eContainer.cloneNode(true);
        vdf.Views.List.PanHandle._ePanHandle = panHandle;
        panHandle.id = "panHandle";
        panHandle.setStyle({
            zIndex: "999998",
            position: 'absolute',
            top: eContainer.positionedOffset()[1] + 'px',
            left: 0
        });
        var panHandleInfoWrapper = document.createElement("div");
        $(panHandleInfoWrapper).addClassName(vdf.Views.List.PanHandle._sPanHandleWrapperRef);
        var panHandleInfo = document.createElement("div");
        $(panHandleInfo).addClassName(vdf.Views.List.PanHandle._sPanHandleRef);
        vdf.Views.List.PanHandle._ePanHandleInfo = document.createElement("div");
        $(vdf.Views.List.PanHandle._ePanHandleInfo).addClassName(vdf.Views.List.PanHandle._sPanHandleInnerRef);
        vdf.Views.List.PanHandle._ePanHandleInfo.setStyle({
            height: "0px"
        });
        panHandleInfo.appendChild(vdf.Views.List.PanHandle._ePanHandleInfo);
        panHandleInfoWrapper.appendChild(panHandleInfo);
        panHandle.appendChild(panHandleInfoWrapper);
        eContainer.parentNode.appendChild(panHandle);
        $(vdf.Views.List.PanHandle._ePanHandleInfo).tween({
            height: {
                time: 0,
                duration: 0.3,
                start: 0,
                stop: 700,
                units: 'px',
                transition: FX.quadInOut,
                onStop: function (element) {
                    element.style.height = "";
                }
            }
        });
        Animate.play();
        vdf.Views.List.PanHandle.getPanHandleContents(eTrigger);
        $(document.body).observe("click", vdf.Views.List.PanHandle.bodyClick);
        Event.stop(event);
    },
    getPanHandleContents: function (element) {
        var link = $(element).select("a")[0];
        if (link.href) {
            vdf.Views.List.PanHandle._sCurrentHref = escape(link.href);
            if (vdf.Views.List.PanHandle._oPageCache[vdf.Views.List.PanHandle._sCurrentHref]) {
                vdf.Views.List.PanHandle.processContents(vdf.Views.List.PanHandle._oPageCache[vdf.Views.List.PanHandle._sCurrentHref]);
            } else {
                new Ajax.Request(link.href, {
                    method: 'get',
                    onSuccess: vdf.Views.List.PanHandle.processContents,
                    onFailure: vdf.Views.List.PanHandle.failureHandler
                });
            }
        }
    },
    processContents: function (response) {
        if (vdf.Views.List.PanHandle._ePanHandleInfo.style.height === "") {
            vdf.Views.List.PanHandle.insertContents(response.responseText);
        } else {
            window.setTimeout(function () {
                vdf.Views.List.PanHandle.processContents(response);
            }, 1);
        }
    },
    insertContents: function (response) {
        vdf.Views.List.PanHandle._oPageCache[vdf.Views.List.PanHandle._sCurrentHref] = {
            responseText: response
        };
        $(vdf.Views.List.PanHandle._ePanHandleInfo).removeClassName("loading");
        vdf.Views.List.PanHandle._ePanHandleInfo.style.height = "auto";
        vdf.Views.List.PanHandle._ePanHandleInfo.innerHTML = response;
        var fader = document.createElement("div");
        $(fader).setStyle({
            width: "100%",
            height: "100%",
            position: "absolute",
            top: "0px",
            left: "0px",
            background: "#fff"
        });
        vdf.Views.List.PanHandle._ePanHandleInfo.appendChild(fader);
        $(fader).tween({
            alpha: {
                time: 0,
                duration: 0.2,
                start: 100,
                stop: 0,
                transition: FX.quadInOut,
                onStop: function (element) {
                    element.parentNode.removeChild(element);
                }
            }
        });
        Animate.play();
        vdf.Views.List.PanHandle.applyClose();
    },
    applyClose: function () {
        var aSummaryLinks = vdf.Views.List.PanHandle._ePanHandle.select(".details_panHandle");
        aSummaryLinks.each(function (eThis) {
            eThis.addClassName("link_close");
            var link = eThis.select("a")[0];
            link.innerHTML = "Close";
        });
        var ePanHandle = $(vdf.Views.List.PanHandle._ePanHandle);
        ePanHandle.observe("click", vdf.Views.List.PanHandle.lightBoxAction);
        var aSubscriptionCheckboxTargetLinks = $(vdf.Views.List.PanHandle._ePanHandle).select(vdf.Tools.SubscriptionChecks._sSubscriptionCheckboxLinkClass);
        if (aSubscriptionCheckboxTargetLinks[0]) {
            vdf.Tools.SubscriptionChecks.createSubscriptionCheckLink(aSubscriptionCheckboxTargetLinks);
        }
        var helpHoverTargets = $(vdf.Views.List.PanHandle._ePanHandle).select('.helpHoverTarget');
        if (helpHoverTargets[0]) {
            vdf.Tools.HelpHover.init(helpHoverTargets);
        }
    },
    closeLightBox: function (event) {
        Event.stopObserving(document.body, "click", vdf.Views.List.PanHandle.bodyClick);
        Event.stopObserving(vdf.Views.List.PanHandle._ePanHandle, "click", vdf.Views.List.PanHandle.lightBoxAction);
        var aSubscriptionCheckboxTargetLinks = $(vdf.Views.List.PanHandle._ePanHandle).select(vdf.Tools.SubscriptionChecks._sSubscriptionCheckboxLinkClass);
        if (aSubscriptionCheckboxTargetLinks[0]) {
            vdf.Tools.SubscriptionChecks.removeSubscriptionCheckLink(aSubscriptionCheckboxTargetLinks);
        }
        vdf.Views.List.PanHandle._ePanHandle.parentNode.removeChild(vdf.Views.List.PanHandle._ePanHandle);
        vdf.Views.List.PanHandle._ePanHandle = null;
        Event.stop(event);
    },
    bodyClick: function (event) {
        var eCurrentNode = event.target;
        var bInPanHandle = false;
        while (eCurrentNode.parentNode && bInPanHandle === false) {
            if (eCurrentNode.parentNode.id === vdf.Views.List.PanHandle._sPanHandleRef) {
                bInPanHandle = true;
            }
            eCurrentNode = eCurrentNode.parentNode;
        }
        if (!bInPanHandle) {
            vdf.Views.List.PanHandle.closeLightBox(event);
        }
    },
    failureHandler: function () {
        var sFailureMessage = "<div class='lightBoxContent'><h3>Sorry! We are not able to process your request now, please try later.</h3></div>";
        vdf.Views.List.PanHandle.processContents({
            responseText: sFailureMessage
        });
    },
    lightBoxAction: function (event) {
        if ($(event.target).hasClassName("link_close") || $(event.target.parentNode).hasClassName("link_close")) {
            vdf.Views.List.PanHandle.closeLightBox(event);
        }
        if (event.target.href === "#") {
            Event.stop(event);
        }
    },
    exampleMethod: function () {
        var iExampleInteger = 1;
        var sExampleString = "string";
        var bExampleBoolean = true;
        var eExampleElement = document.createElement("div");
        var oExampleObject = {};
        var aExampleArray = [];
        var fExampleFunction = vdf.Views.List.PanHandle.exampleMethod;
    }
};

vdf.Views.List.Rollover = {
    _gridRollOverClassName: ".JSModule_product_rollover",
    _gridRollOverOnClassName: "JSModule_product_rollover_on",
    init: function () {
        if (vdf.Views.List._eListViewHolder) {
            var aRollovers = vdf.Views.List._eListViewHolder.select(vdf.Views.List.Rollover._gridRollOverClassName);
            aRollovers.each(function (element) {
                vdf.Views.List.Rollover.setRollOverBehaviours(element);
            });
        }
    },
    setRollOverBehaviours: function (element) {
        Event.observe(element, "mouseover", vdf.Views.List.Rollover.showExtraInfo);
        Event.observe(element, "mouseout", vdf.Views.List.Rollover.autoHideExtraInfo);
    },
    showExtraInfo: function () {
        var currentElement = $(this);
        var bIsScrolling = vdf.Tools.checkNoScroll();
        if (!currentElement.hasClassName(vdf.Views.List.Rollover._gridRollOverOnClassName) && bIsScrolling) {
            var currentLower = $(this).positionedOffset()[1] + $(this).getDimensions().height;
            this.parentNode.style.backgroundPosition = "0 " + currentLower + "px";
            currentElement.addClassName(vdf.Views.List.Rollover._gridRollOverOnClassName);
        }
        currentElement = null;
    },
    autoHideExtraInfo: function (event) {
        var tg = event.relatedTarget || event.toElement;
        if (!vdf.Tools.isChildOf(this, tg)) {
            vdf.Views.List.Rollover.hideRollOver(this);
        }
    },
    resetBehaviours: function (event) {
        var tg = event.relatedTarget || event.toElement;
        if (!vdf.Tools.isChildOf(this, tg)) {
            Event.stopObserving(this, "mouseout", vdf.Views.List.Rollover.resetBehaviours);
            vdf.Views.List.Rollover.setRollOverBehaviours(this);
        }
    },
    hideRollOver: function (eRolloverParent) {
        eRolloverParent.parentNode.style.backgroundPosition = "0 -100000px";
        $(eRolloverParent).removeClassName(vdf.Views.List.Rollover._gridRollOverOnClassName);
    },
    exampleMethod: function () {
        var iExampleInteger = 1;
        var sExampleString = "string";
        var bExampleBoolean = true;
        var eExampleElement = document.createElement("div");
        var oExampleObject = {};
        var aExampleArray = [];
        var fExampleFunction = spb.Template.exampleMethod;
    }
};

/* VMI - START - 28-01-2010 */
vdf.Tools.Tabs = {
    sActiveState: 'activeTabElement',
    oTabControllers: [],
    init: function (aTabs) {
        for (var i = 0, j = aTabs.length; i < j; i++) {
            vdf.Tools.Tabs.oTabControllers[i] = new vdf.Tools.Tabs.TabObject(aTabs[i]);
        }
        return false;
    }
};
vdf.Tools.Tabs.TabObject = function (eTabbedContentItem) {
    this.init = function ($eTabbedContentItem) {
        this.eTabbedContents = null;
        this.aTabBoxHeights = [];
        this.aTabListItems = [];
        this.aTabBoxes = [];
        this.iPreviousItem = 0;
        this.iSetHeight = false;
        var _this = this;
        var eTabList = null;
        var _fHeaderCreation = function (eItem, index) {
            var eSpan = new Element('span').update(eItem.innerHTML);
            var eLink = new Element('a', {
                'href': '#' + eItem.id
            }).insert(eSpan);
            var eLiItem = new Element('li').insert(eLink);
            eTabList.insert(eLiItem);
            $(eItem).hide();
        };
        var _fBindTabActions = function (eTabLink, i) {
            $(eTabLink).observe('click', function (event) {
                Event.stop(event);
                _this.resetAllTabs(eTabList);
                _this.selectTab.call(this);
                _this.hideContentBoxes();
                _this.showBox(i);
                _this.iPreviousItem = i;
                return false;
            });
        };
        var aCustomWidth = $eTabbedContentItem.readAttribute('class').match(/tabbedContentHeight_[A-Za-z0-9]*/);
        if (aCustomWidth) {
            this.iSetHeight = aCustomWidth[0].replace('tabbedContentHeight_', '');
        }
        eTabList = new Element('ul', {
            'class': 'tabList JSTabs'
        });
        $eTabbedContentItem.select('.tabLead, .tabHeader').each(_fHeaderCreation);
        $eTabbedContentItem.insert({
            top: eTabList
        });
        var eTabElements = $eTabbedContentItem.select('ul.tabList li, div.tabContentBox');
        var iActionNumbers = eTabElements.length / 2;
        this.aTabListItems = eTabElements.slice(0, iActionNumbers);
        this.aTabBoxes = eTabElements.slice(iActionNumbers);
        for (var k = 0, l = this.aTabBoxes.length; k < l; k++) {
            if (this.iSetHeight) {
                this.aTabBoxHeights[k] = this.iSetHeight;
            }
            else {
                this.aTabBoxHeights[k] = $(this.aTabBoxes[k]).getHeight();
            }
        }
        this.hideContentBoxes();
        $(this.aTabListItems[0]).addClassName(vdf.Tools.Tabs.sActiveState);
        this.show(this.aTabBoxes[0], this.aTabBoxHeights[0]);
        this.aTabListItems.each(_fBindTabActions);
        return this;
    };
    this.hideContentBoxes = function () {
        this.aTabBoxes.each(function (eElem, i) {
            eElem.hide();
        });
    };
    this.show = function (oTabBox, iHeight) {
        if (this.iSetHeight === false) {
            $(oTabBox).setStyle({
                height: this.aTabBoxHeights[this.iPreviousItem] + 'px',
                display: ''
            }).tween({
                height: {
                    time: 0,
                    duration: 0.2,
                    start: this.aTabBoxHeights[this.iPreviousItem],
                    stop: iHeight,
                    units: 'px',
                    transition: FX.quadInOut,
                    onStop: function (element) {
                        $(element).setStyle('height', 'auto');
                    }
                }
            });
            Animate.play();
        }
        else {
            $(oTabBox).setStyle({
                display: '',
                height: this.iSetHeight + 'px'
            });
        }
        return false;
    };
    this.resetAllTabs = function (eTabList) {
        $(eTabList).childElements().each(function (eElem, i) {
            eElem.writeAttribute('class', '').writeAttribute('className', '');
        });
    };
    this.selectTab = function (event) {
        $(this).addClassName(vdf.Tools.Tabs.sActiveState);
    };
    this.showBox = function (i) {
        this.show(this.aTabBoxes[i], this.aTabBoxHeights[i]);
    };
    return this.init(eTabbedContentItem);
}; /* VMI - END - 28-01-2010 */

vdf.Tools.MessageBlock = {
    _sMessagePaneID: 'errorPaneSR',
    _sMessageListID: 'paneErrorList',
    _sErrorMsg: "",
    _HTMLString: "",
    _HideErrorsString: "",
    eErrorPane: null,
    eErrorIntro:null,
    eErrorList: null,
    init: function (eForm) {
        
        this._sErrorMsg = "There seems to be a problem with your account. Please try again or contact our <a target=\"_blank\" href=\"http://help.vodafone.co.uk/system/selfservice.controller?CONFIGURATION=1164&PARTITION_ID=1&CMD=STARTPAGE&USERTYPE=1&LANGUAGE=en&COUNTRY=us\">help desk</a>.";
        this._HTMLString = '<h2>Sorry</h2><p class="error_pane_intro">' + this._sErrorMsg + '</p>';
		
		//check for current error container
		this.eErrorPane = $(this._sMessagePaneID);
		if (this.eErrorPane) {
			//set containers
			this.eErrorIntro = $('errorIntro');
			this.eErrorList = $(this._sMessageListID);
		}
		else {
			//create pane
			this.createMessagePane(eForm);
		}
        return this;
    },
    createMessagePane: function (eForm) {
        this.eErrorPane = new Element("div", {
            id: this._sMessagePaneID,
            tabindex: -1,
            'class': 'displayNone'
        });
		
		this.eErrorIntro = new Element("div", {
            id: 'errorIntro'
        });
        this.eErrorPane.appendChild(this.eErrorIntro);
		
		//if the progress meter exists then we should place the error block after it 
		var eProgressMeter = eForm.select('.progressMeter');
		var esrNotice = eForm.select('.srNotice');
		if (eProgressMeter[0]) {
			if (esrNotice[0]) {
				Element.insert(esrNotice[0], {'after': this.eErrorPane} );
			}
			else {
				Element.insert(eProgressMeter[0], {'after': this.eErrorPane} );
			}
		}
		else {
			Element.insert(eForm, {'top': this.eErrorPane} );
		}
		
        this.eErrorList = new Element("ul", {
            id: this._sMessageListID
        });
        this.eErrorPane.appendChild(this.eErrorList);
       
    },
    showMessagePane: function () {
	//Asha:  Added to disable the "set up my account" in registration step3
		if(document.getElementById('setUpMyAccount')){
			document.getElementById('setUpMyAccount').disabled = false;
		}
        if (vdf.Tools.MessageBlock.eErrorPane.hasClassName('displayNone')) {
			//add error text
			vdf.Tools.MessageBlock.eErrorIntro.update(this._HTMLString);
            vdf.Tools.MessageBlock.eErrorPane.removeClassName('displayNone');
        }
    },
    closeMessagePane: function () {
		//Asha:  Added to disable the "set up my account" in registration step3
		if(document.getElementById('setUpMyAccount')){
			document.getElementById('setUpMyAccount').disabled = true;
		}
        if (!vdf.Tools.MessageBlock.eErrorPane.hasClassName('displayNone')) {
			//add error text
			vdf.Tools.MessageBlock.eErrorIntro.update('');
			vdf.Tools.MessageBlock.eErrorPane.addClassName('displayNone');
        }
    },
    addErrorMessage: function (sIDvalue, sErrorTitle, sError, iIndex, sGroupID) {

    	if(document.getElementById('errorPaneSRServer')){
    		document.getElementById('errorPaneSRServer').style.display = 'none';
		}
			
        var sMainErrorID;
        if (sGroupID && sGroupID !== '') {
            sMainErrorID = sGroupID;
        }
        else {
            sMainErrorID = sIDvalue;
        }
        var aErrorMessage = vdf.Tools.MessageBlock.eErrorList.select('li.val_' + sMainErrorID);
		
        if (!aErrorMessage[0]) {
            vdf.Tools.MessageBlock.showMessagePane();
            vdf.Tools.MessageBlock.addErrorHeader(sMainErrorID, sErrorTitle, iIndex);
            var errorUL = new Element("ul", {
                'class': 'val_' + sMainErrorID
            }).update('<li class="valItem_' + sIDvalue + iIndex + '">' + sError + '</li>');
            vdf.Tools.MessageBlock.eErrorList.appendChild(errorUL);
        }
        else {
            var aErrorMessageLI = vdf.Tools.MessageBlock.eErrorList.select('li.valItem_' + sIDvalue + iIndex);
            if (!aErrorMessageLI[0]) {
                var aErrorMessageUL = vdf.Tools.MessageBlock.eErrorList.select('ul.val_' + sMainErrorID);
                var errorlink = new Element("li", {
                    'class': 'valItem_' + sIDvalue + iIndex
                }).update(sError);
                aErrorMessageUL[0].appendChild(errorlink);
            }
        }
    },
    addErrorHeader: function (sIDvalue, sErrorTitle, iIndex) {
        var errorHeadingText = '<a onclick="javascript:document.getElementById(\''+sIDvalue+'\').focus();" href="javascript:void 0;"><span>' + sErrorTitle + '</span></a>';
        var errorHeading = new Element("li", {
            'class': 'val_' + sIDvalue
        }).update(errorHeadingText);
        vdf.Tools.MessageBlock.eErrorList.appendChild(errorHeading);
    },
    removeErrorMessage: function (sIDvalue, iIndex, sGroupID) {
        var sMainErrorID;
        if (sGroupID) {
            sMainErrorID = sGroupID;
        }
        else {
            sMainErrorID = sIDvalue;
        }
        var aErrorUL = vdf.Tools.MessageBlock.eErrorList.select('ul.val_' + sMainErrorID)[0];
        if (aErrorUL) {
            var aErrorMessage = aErrorUL.select('li.valItem_' + sIDvalue + iIndex);
            if (aErrorMessage.length !== 0) {
                aErrorMessage[0].remove();
                return true;
            }
        }
        return false;
    },
    checkErrorBlock: function (sIDvalue, sGroupID) {
        var sMainErrorID;
        if (sGroupID) {
            sMainErrorID = sGroupID;
        }
        else {
            sMainErrorID = sIDvalue;
        }
        var aErrorUL = vdf.Tools.MessageBlock.eErrorList.select('ul.val_' + sMainErrorID)[0];
        if (aErrorUL) {
            var aValItems = aErrorUL.select('li');
            var bRemainingErrors = true;
            if (aErrorUL.select('li').length === 0) {
                aErrorUL.remove();
                vdf.Tools.MessageBlock.fadeOutErrorMessage(vdf.Tools.MessageBlock.eErrorList.select('li.val_' + sMainErrorID)[0]);
                return true;
            }
            else {
                for (var i = 0, k = aValItems.length; i < k; i++) {
                    var startsWithPattern = new RegExp('valItem_' + sIDvalue);
                    bRemainingErrors = startsWithPattern.test(aValItems[i].getAttribute('class'));
                    if (bRemainingErrors) {
                        break;
                    }
                }
            }
            return !bRemainingErrors;
        }
    },
    checkForOpenErrors: function () {
        var iInvisibleErrors = vdf.Tools.MessageBlock.eErrorList.select('li').length;
        if (iInvisibleErrors === 0) {
            vdf.Tools.MessageBlock.closeMessagePane();
            return true;
        }
        return false;
    },
    fadeOutErrorMessage: function (eErrorMessageItem) {
        if (eErrorMessageItem) {
			eErrorMessageItem.remove();
			vdf.Tools.MessageBlock.checkForOpenErrors();   
        }
    }
};
