// Main ready function to initialise all aspects of the page
$(document).ready(function() {
    // Check the window size, and attach the refit function to the resize event
    RefitPageBackground();
    // Make sure that the featured background images in article list items can act as links - lazy, but I need a solution
    jQuery.each($('.articleRow'), function(i, val) {
        var destURL = $('.read a', this)[0].href;
        $(this).css({ 'position': 'relative' }).prepend('<a href="' + destURL + '" style="text-decoration: none; position: absolute; z-index: 3;  top:0;left:0; display: block; width: 135px; height: 105px;">&nbsp;</a>');
    });

    var lightBoxScriptLoaded = false;

    // Attach magnifiers to productrows
    if ($('div.productRow').length > 0) {
        $.getScript('/Javascript/jquery.lightbox-0.5.pack.js', function() {
            lightBoxScriptLoaded = true;
            $('<link rel="stylesheet" type="text/css" href="/css/jquery.lightbox-0.5.css" />').appendTo("head");
            jQuery.each($('.productRow'), function(i, val) {
                if ($('div.wideImage').length == 0) {
                    var imageUrl = String($('img.rowImage', this)[0].src).replace('/small/', '/verylarge/')
                    $(this).css({ 'position': 'relative' }).prepend('<a href="' + imageUrl + '" class="lightbox" style="text-decoration: none; position: absolute; top: 125px; left: 100px; z-index: 3; display: block; width: 16px; height:16px; background: url(/images/icons/magnify.png) no-repeat; ">&nbsp;</a>');
                }
            });

            $('div.productRow .lightbox').lightBox({ disableNavbarLinks: true, displayTitle: false });
        });
    }

    // Attach magnifier to single product
    if ($('#MainImage').length > 0) {
        if (!lightBoxScriptLoaded) {
            $('<link rel="stylesheet" type="text/css" href="/css/jquery.lightbox-0.5.css" />').appendTo("head");
            $.getScript('/Javascript/jquery.lightbox-0.5.pack.js', function() {
                addProductLightBox();
            });
        } else {
            addProductLightBox();
        }
        lightBoxScriptLoaded = true;
    };


    $(window).resize(RefitPageBackground);
    $('input').focus(function() { if (this.value == this.title || this.value == "[" + this.title + "]") { this.value = ""; } });
    $('#ShippingCheck').click(function() { if (this.checked) { $('#ShippingAddress').css('display', 'block'); } else { $('#ShippingAddress').css('display', 'none'); } });
    $('.validator').click(ValidateRegistrationForm);

    // Set up pop-up windows
    initPopUpWindowLinks();

    //Load validation functions
    ValidateTextboxAndEmail();
    ValidateMediaCodeSelection();

    $('#UploadForm').submit(function(e) {

        var MandatoryInputs = $('.frmMan').children('input');
        var MandatorySelects = $('.frmMan').children('select');
        var FormComplete = true;

        for (var n=0; n<MandatoryInputs.length; n++) {
            if (MandatoryInputs[n].value == '') {
                FormComplete = false;
            }
        }

        for (var n=0; n<MandatorySelects.length; n++) {
            if (MandatorySelects[n].selectedIndex < 0) {
                FormComplete = false;
            }
        }

        if (!FormComplete) {
            e.preventDefault();
            alert('At least one required field has not been completed. Please check your entry and correct where required.');
        }
    });
});

function addProductLightBox() {
    var imageUrl = String($('#MainImage')[0].src).replace('/large/', '/verylarge/');
    $('#MainImage').css({ 'position': 'relative' });
    $('#MainImageParagraph').append('<a href="' + imageUrl + '" class="lightbox" style="text-decoration: none; position: relative; left: 180px; margin-top: -22px; display: block; width: 16px; height:16px; background: url(/images/icons/magnify.png) no-repeat; ">&nbsp;</a>');
    $('#MainImageParagraph .lightbox').lightBox({ disableNavbarLinks: true, displayTitle: false });
}

function RefitPageBackground() {
    var pageBorder = $('#PageBorder');

    if ($(window).width() < 1174) {
        // Need to turn off the flanking columns
        if ($(pageBorder).width() != 974) {
            $(pageBorder).css({ "width": $(window).width() + "px" });
        }
    } else {
        if ($(pageBorder).width() != 1174) {
            $('#PageBorder').css({ "width": "1174px" });
        }
    }
}

function ValidateRegistrationForm() {

    var MandatoryInputs = $('.frmMan').children('input');
    var MandatorySelects = $('.frmMan').children('select');
    var DifferentShipping = false;
    var LoginName = '';
    var LoginCheck = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/;

    if ($('#ShippingCheck').length > 0) {
        if ($('#ShippingCheck')[0].checked) {
            DifferentShipping = true;
        }
    }

    for (var n=0; n<MandatoryInputs.length; n++) {
        if ((MandatoryInputs[n].name.substring(0,4) != 'Ship') || ((DifferentShipping) && (MandatoryInputs[n].name.substring(0,4) == 'Ship'))) {
            if (MandatoryInputs[n].value == '') {
                alert(MandatoryInputs[n].parentNode.getElementsByTagName('label')[0].innerHTML.replace(':', '') + ' is not filled in. Please ensure all fields marked with a * are completed.');
                return false;
            }
        }
    }

    for (var n=0; n<MandatorySelects.length; n++) {
        if (((MandatorySelects[n].selectedIndex < 0) || (MandatorySelects[n].options[MandatorySelects[n].selectedIndex].value == '')) && (MandatorySelects[n].id.substring(0,3) != 'pca')) {
            alert(MandatorySelects[n].parentNode.getElementsByTagName('label')[0].innerHTML.replace(':', '') + ' is not selected. Please ensure all fields marked with a * are completed.');
            return false;
        }
    }

    LoginName = document.getElementById('loginname').value;
    if (!LoginName.match(LoginCheck)) {
        alert('The email address you have entered is not valid. Please check this and correct as required.');
        return false;
    }

    if (document.getElementById('password') && document.getElementById('AccountConfPass')) {
        if (document.getElementById('password').value != document.getElementById('AccountConfPass').value) {
            alert('The passwords you have entered do not match. Please check this and correct as required.');
            return false;
        } else {
            if (document.getElementById('password').value.length < 6) {
                alert('The password you have entered is too short. Passwords must be at least 6 characters in length.');
                return false;
            }
        }
    }
}

// Any anchor or image map area that has the class popupOpener will cause the link to appear within a window
// additional classes can be used to affect the size of the window.  Please keep to standard sizes where possible
function initPopUpWindowLinks() {
	$('A.popupOpener,area.popupOpener').click( function() {
		var winName = 'maxi_PopupMedium';
		var xSize = 800;
		var ySize = 600;

		if ($(this).hasClass('320x240Window')) {
			winName = 'maxi_320x240Window';
			xSize = 320;
			ySize = 240;
		} else if ($(this).hasClass('smallWindow')) {
			winName = 'maxi_PopupSmall';
			xSize = 640;
			ySize = 480;
		} else if ($(this).hasClass('bigWindow')) {
			winName = 'maxi_PopupBig';
			xSize = 1024;
			ySize = 768;
		} else if ($(this).hasClass( 'trainingAnimation')) {
			winName = 'trainingAnimation';
			xSize = 180;
			ySize = 140;
		} else if ($(this).hasClass( 'newWindow')) {
			window.open($(this).attr('href'));
			xSize = 0

		}

		if (xSize > 0) {
			var xPos = (screen.width) ? (screen.width - xSize)/2 : 0;
			var yPos = (screen.height) ? (screen.height - ySize)/2 : 0;
			var winSetts = 'height=' + ySize + ',width=' + xSize + ',top=' + yPos + ',left=' + xPos + ',scrollbars=yes,resizable';
			var newWin = window.open($(this).attr('href'),winName,winSetts);

			if (!newWin.opener) {
				newWin.opener = self;
			}
			if (window.focus) {
				newWin.focus();
			}
		}

		return false;
	});
}

(function($) {
    $.fn.ToneTypeAhead = function(settings) {
        var config = { 'deleteKeyHidesSearchOptions': true,
            'searchOptionsStartTop': 42,
            'jumpToURLonCompletion': true
        };

        var searchOptions = [{ 'text': 'start', 'options': [1] },			     
                                        { 'text': 'I want to', 'options': [2, 3] },
					
					{ 'text': 'lose weight', 'options': [4,5,6,7,8,9,10], 'plan' : 'SculptressSlim', 'day' : 3 },
					{ 'text': 'tone up', 'options': [16,17,18,19,20,21,22], 'plan' : 'DefinityTone', 'day' : 3 },
										
                                        { 'text': 'for my wedding.', 'options': [11,12,13,14,15], 'event': 'mywedding' },
                                        { 'text': 'for a wedding.', 'options': [11,12,13,14,15], 'event': 'awedding' },
                                        { 'text': 'for a holiday.', 'options': [11,12,13,14,15], 'event': 'holiday' },
                                        { 'text': 'for a party.', 'options': [11,12,13,14,15], 'event': 'party' },
                                        { 'text': 'for my well being.', 'options': [11,12,13,14,15], 'event': 'wellbeing' },
                                        { 'text': 'for myself.', 'options': [11,12,13,14,15], 'event': 'myself' },
                                        { 'text': 'to stay in shape.', 'options': [11,12,13,14,15], 'event': 'stayinshape' },
					
					{ 'text': 'I weigh less than 60Kg', 'weight': '<60', 'meal': 1200 },
                                        { 'text': 'I weigh 61Kg - 70Kg', 'weight': '61-70', 'meal': 1400  },
                                        { 'text': 'I weigh 71Kg - 80Kg', 'weight': '71-80', 'meal': 1600  },
                                        { 'text': 'I weigh 81Kg - 90Kg', 'weight': '81-90', 'meal': 1800  },
                                        { 'text': 'I weigh more than 90Kg', 'weight': '91+', 'meal': 2000},

					{ 'text': 'for my wedding.', 'options': [23,24,25,26], 'event': 'mywedding' },
                                        { 'text': 'for a wedding.', 'options': [23,24,25,26], 'event': 'awedding' },
                                        { 'text': 'for a holiday.', 'options': [23,24,25,26], 'event': 'holiday' },
                                        { 'text': 'for a party.', 'options': [23,24,25,26], 'event': 'party' },
                                        { 'text': 'for my well being.', 'options': [23,24,25,26], 'event': 'wellbeing' },
                                        { 'text': 'for myself.', 'options': [23,24,25,26], 'event': 'myself' },
                                        { 'text': 'to stay in shape.', 'options': [23,24,25,26], 'event': 'stayinshape' },
										
					{ 'text': 'I weigh less than 60Kg', 'weight': '<60', 'meal': 1400},
                                        { 'text': 'I weigh 61Kg - 70Kg', 'weight': '61-70', 'meal': 1600},
                                        { 'text': 'I weigh 71Kg - 80Kg', 'weight': '71-80', 'meal': 1800 },
                                        { 'text': 'I weigh 81Kg - 90Kg', 'weight': '81-90', 'meal': 2000 }                                        
					
				    
				];
   /*
    
     var searchOptions = [{ 'text': 'start', 'options': [1, 23, 32] },
			{ 'text': 'I want to', 'options': [2, 24, 33] },
			{ 'text': 'lose weight', 'options': [3, 4, 5, 6, 7, 8, 9], 'day': 3 },
			{ 'text': 'from everywhere', 'options': [10, 11, 12, 13, 14, 15, 16], 'plan': 'Wholebody' },
			{ 'text': 'from my arms', 'options': [10, 11, 12, 13, 14, 15, 16], 'plan': 'StomachArms' },
			{ 'text': 'from my legs', 'options': [10, 11, 12, 13, 14, 15, 16], 'plan': 'HipsThighsBum' },
			{ 'text': 'from my hips', 'options': [10, 11, 12, 13, 14, 15, 16], 'plan': 'HipsThighsBum' },
			{ 'text': 'from my thighs', 'options': [10, 11, 12, 13, 14, 15, 16], 'plan': 'HipsThighsBum' },
			{ 'text': 'from my tummy', 'options': [10, 11, 12, 13, 14, 15, 16], 'plan': 'HipsThighsBum' },
			{ 'text': 'from my bum', 'options': [10, 11, 12, 13, 14, 15, 16], 'plan': 'HipsThighsBum' },
			{ 'text': 'for my wedding.', 'options': [17], 'event': 'mywedding' },
			{ 'text': 'for a wedding.', 'options': [17], 'event': 'awedding' },
			{ 'text': 'for a holiday.', 'options': [17], 'event': 'holiday' },
			{ 'text': 'for a party.', 'options': [17], 'event': 'party' },
			{ 'text': 'for my well being.', 'options': [17], 'event': 'wellbeing' },
			{ 'text': 'for myself.', 'options': [17], 'event': 'myself' },
			{ 'text': 'to stay in shape.', 'options': [17], 'event': 'stayinshape' },
			{ 'text': 'I weigh', 'options': [18, 19, 20, 21, 22] },
			{ 'text': 'less than 60Kg', 'weight': '<60', 'meal': 1200 },
			{ 'text': '61Kg - 70Kg', 'weight': '61-70', 'meal': 1400 },
			{ 'text': '71Kg - 80Kg', 'weight': '71-80', 'meal': 1600 },
			{ 'text': '81Kg - 90Kg', 'weight': '81-90', 'meal': 1800 },
			{ 'text': 'more than 90Kg', 'weight': '91+', 'meal': 2000 },
			{ 'text': 'I\'d like to', 'options': [2, 24, 33] },
			{ 'text': 'tone up', 'options': [25, 26, 27, 28, 29, 30, 31], 'day': 3 },
			{ 'text': 'my whole body', 'options': [10, 11, 12, 13, 14, 15, 16], 'plan': 'Wholebody' },
			{ 'text': 'my legs', 'options': [10, 11, 12, 13, 14, 15, 16], 'plan': 'HipsThighsBum' },
			{ 'text': 'my hips', 'options': [10, 11, 12, 13, 14, 15, 16], 'plan': 'HipsThighsBum' },
			{ 'text': 'my thighs', 'options': [10, 11, 12, 13, 14, 15, 16], 'plan': 'HipsThighsBum' },
			{ 'text': 'my arms', 'options': [10, 11, 12, 13, 14, 15, 16], 'plan': 'StomachArms' },
			{ 'text': 'my tummy', 'options': [10, 11, 12, 13, 14, 15, 16], 'plan': 'StomachArms' },
			{ 'text': 'my bum', 'options': [10, 11, 12, 13, 14, 15, 16], 'plan': 'HipsThighsBum' },
			{ 'text': 'I\'m going to', 'options': [2, 24, 33] },
			{ 'text': 'get fit', 'options': [37,38, 39, 40,41], 'plan': 'Diet' },

			{ 'text': 'for a', 'options': [37, 38, 39, 41] },
			{ 'text': 'post pregnancy.', 'event': 'postpregnancy', 'options': [42] },
			{ 'text': 'to drop a dress size.', 'event': 'dresssize', 'options': [42] },

			{ 'text': 'for a skiing holiday', 'event': 'skiingholiday','plan': 'Endurance1400', 'options': [46] },
			{ 'text': 'for a running event', 'event': 'running', 'options': [50, 51, 52, 53] },
			{ 'text': 'for a rowing event', 'event': 'rowing', 'plan': 'Endurance1400', 'options': [46] },
			{ 'text': 'for a swimming event', 'event': 'swimming', 'plan': 'Endurance1400', 'options': [46] },
			{ 'text': 'for a cycling event', 'event': 'cycling', 'plan': 'Endurance1400', 'options': [46] },

			{ 'text': 'I weigh', 'options': [43, 44, 45] },
			{ 'text': 'less than 60Kg', 'weight': '<60', 'meal': 1600, 'options': [46] },
			{ 'text': '61Kg - 70Kg', 'weight': '61-70', 'meal': 1800, 'options': [46] },
			{ 'text': 'more than 70Kg', 'weight': '71-80', 'meal': 2000, 'options': [46] },

			{ 'text': 'and train', 'options': [47, 48, 49] },
			{ 'text': '3 days a week.', 'day': 3 },
			{ 'text': '4 days a week.', 'day': 4 },
			{ 'text': '5 days a week.', 'day': 5 },

			{ 'text': 'thats 5K.', 'plan': '5kwk01', 'meal': 1600 },
			{ 'text': 'thats 10K.', 'plan': '10kwk01', 'meal': 1600 },
			{ 'text': 'thats a half marathon.', 'plan': 'halfmarathonwk01', 'meal': 1600 },
			{ 'text': 'thats a marathon.', 'plan': 'marathonwk01', 'meal': 1600 }
		      ];
   */
        if (settings) $.extend(config, settings);
        var hasFocus = false;
        var obj;

        var trainingPlan = '';
        var mealPlan = '';
        var noDays = 3;
        var event = '';
        var weight = ''


        // Set up the event handlers needed for the TypeAhead, as well as initial state
        this.each(function() {
            // element-specific code here
            obj = $(this);
            $('.searchInput', obj).click(handleSearchClick);
            $('.searchInput', obj).dblclick(handleDoubleClick);
            $(document).keypress(handleKeyPress);
            $(document).click(handleBlur);

            $('#SelectionOptions', obj).click(handleOptionClick);
            $("#SelectionOptions").hide();
        });


        // The main div has been clicked, show the options at the correct position
        function handleSearchClick(e) {
            // Calculate the position of where to show the selection list
            $('#TypeAhead .searchInput img').remove();

            var spanCount = $('span', obj).length;
            var positionToShow = 0
            var clickedItem = e.srcElement || e.originalTarget

            if (clickedItem.tagName == 'SPAN' && spanCount > 1) {
            	// We have clicked on a span, so remove items after that
            	var followingItems = $(clickedItem).nextAll()
            	spanCount -= followingItems.length
            	$(followingItems).remove()
            	$(clickedItem).remove();
		
            }

            if (spanCount > 0) {
                // Each span in the selected list has a class as n-m where n is the parent node and m is the current node
                var tailDetails = $('span:last-child', obj).attr('class').split('-');
                positionToShow = tailDetails[1];    // Get the current node
            }

            updateSearchOptions(positionToShow);
            hasFocus = true;
	    e.preventDefault()
            e.stopPropagation();
        }

        // Event handler for the selection of an item within the list
        function handleOptionClick(e) {
            var target = $(e.target)[0];
            var urlFragment = getFragmentOfUrl(target.href);
            var selectedOption = urlFragment.split('-');

            // Add the selected option to the list of displayed spans
            addSearchNode(selectedOption[0] + '-' + selectedOption[1], searchOptions[selectedOption[1]].text)

            // See if the selected option has any data associated, certain nodes can affect the outcome of the destination url
            if (searchOptions[selectedOption[1]].plan) {
                trainingPlan = searchOptions[selectedOption[1]].plan
            }
            if (searchOptions[selectedOption[1]].meal) {
                mealPlan = searchOptions[selectedOption[1]].meal
            }
            if (searchOptions[selectedOption[1]].day) {
                noDays = searchOptions[selectedOption[1]].day
            }
            if (searchOptions[selectedOption[1]].event) {
                event = searchOptions[selectedOption[1]].event
            }
            if (searchOptions[selectedOption[1]].weight) {
                weight = searchOptions[selectedOption[1]].weight
            }

            updateSearchOptions(selectedOption[1]);
            e.stopPropagation();
        }

        // Search has been doubled clicked, so remove all the spans
        function handleDoubleClick() {
            $('span', obj).remove();
            $("#SelectionOptions").css({ "left": +getLastSpanPosition() + "px", "top": +config.searchOptionsStartTop + "px" });
            hideSearchOptions();
        }

        function handleKeyPress(e) {
            if (!hasFocus) { return }

            // Delete or left arrow key has been pressed
            if (e.which == 8 || e.keyCode == 37) {
                if ($('span', obj).length > 0) {    // Is there anything to remove?
                    // Get the reference class of the last node, especially wrt the parent node
                    var tailDetails = $('span:last-child', obj).attr('class').split('-');
                    removeLastSearchNode();

                    if (config.deleteKeyHidesSearchOptions) {
                        hideSearchOptions();
                    } else {
                        // Show the search options for the entry prior to the one deleted
                        updateSearchOptions(tailDetails[0]);
                    }
                } else {
                    hideSearchOptions();
                }
                e.stopPropagation();
            }
        }

        // Something else on the page has got the users, attention so tidy everything up
        function handleBlur(e) {
            hasFocus = false;
            hideSearchOptions();
        }

        // Need to populate the list of options, based on a parent passed in
        function updateSearchOptions(parentLevel) {
            var spanCount = $('span', obj).length
            if (spanCount == 0 || (searchOptions[parentLevel].options && searchOptions[parentLevel].options.length > 0)) {
                var left = 0;
                var top = config.searchOptionsStartTop;

                if (spanCount > 0) {
                    left = getLastSpanPosition();
                }

                //show the menu directly underneath the last placeholder
                var listHtml = ""
                var nodeRef;
                var currentOption;

                for (var i = 0; i < searchOptions[parentLevel].options.length; i++) {
                    currentOption = searchOptions[parentLevel].options[i]
                    nodeRef = parentLevel + '-' + currentOption
                    listHtml = listHtml + "<li><a href=\"#" + nodeRef + "\">" + searchOptions[currentOption].text + "</a></li>"
                }
                $("#SelectionOptions").html(listHtml);

                showSearchOptions(left, top);
            } else if (!(searchOptions[parentLevel].options)) {
                // if the last selected node has a url then handle the jump to it
                hideSearchOptions();
                if (config.jumpToURLonCompletion) {		    		
                    var targetURL = '/plans/' + trainingPlan + mealPlan + 'x' + noDays + '.html?'
		    if (searchOptions[parentLevel].url) {
			targetURL = searchOptions[parentLevel].url + '?'
		    }
		    
                    if (weight.length > 0) { targetURL = targetURL + 'weight=' + weight + '&'; }
                    if (event.length > 0) { targetURL = targetURL + 'event=' + event + '&'; }
		    if (noDays.length > 0) { targetURL = targetURL + 'noDays=' + noDays + '&'; }

                    targetURL = targetURL.substring(0, targetURL.length - 1);
                    window.location.href = targetURL;
                }
            } else {
                hideSearchOptions();
            }
        }

        // Animates adding a new entry to the list
        function addSearchNode(nodeReference, nodeText) {
            $('#TypeAhead .searchInput img').remove();
            $('#TypeAhead .searchInput').append('<span class="' + nodeReference + '">' + nodeText + "</span> ")
        }

        // Animates the removal of a search option
        function removeLastSearchNode() {
            $('span:last-child', obj).remove();
        }

        // Animates turnng on the search option selection list
        function showSearchOptions(x, y) {
            if ($.browser.msie) {
                // Can't fix the flash overlay bug for IE7, so just display it above
                y = y - $('#SelectionOptions').outerHeight() - $('#TypeAhead .searchInput').outerHeight();
                $("#SelectionOptions").css({ "left": $("#SelectionOptions").css("left"), "top": +y + "px" });
            }

            if ($('#SelectionOptions').css('display') == 'none') {
                $("#SelectionOptions").css({ "left": x + "px", "top": +y + "px" });
                $('#SelectionOptions').show()
            } else {
                $("#SelectionOptions").animate({
                    "left": x + "px", "top": +y + "px"
                }, 500);
            }
        }

        // Animates the turning off of the search options selection list
        function hideSearchOptions() {
            $('#SelectionOptions').hide()
        }

        function getLastSpanPosition() {
            var lastSpan = $('span:last-child', obj)
            var pos = $(lastSpan).offset();
            var parentPos = $(lastSpan).offsetParent().offset();

            return pos.left - parentPos.left + lastSpan.outerWidth();
        }

        // Given a particular url, then this function will return the fragment, i.e. everything after the #
        function getFragmentOfUrl(url) {
            if (url.indexOf('#') > -1) {
                return url.substring(url.indexOf('#') + 1);
            } else {
                return false
            }
        }

        return this;
    };

})(jQuery);

function ValidateTextboxAndEmail() {
    $('form.frmValidateMandatory').submit( function(e) {
        var EmailCheck = /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}/;
        var target = $(e.target)[0];
        var MandatoryInputs = $('p.frmMan input', target)

        //Check for mandatory inputs
        for (var n=0; n<MandatoryInputs.length; n++) {
            if (MandatoryInputs[n].value == '') {
                alert(MandatoryInputs[n].parentNode.getElementsByTagName('label')[0].innerHTML.replace(':', '') + ' is not filled in. Please ensure all fields marked with an * are completed.');
                e.preventDefault();
                return false;
            }
        }

        var EmailFields = $('p.frmEmail input', target)

        //Check for valid emails
        for (var n=0; n<EmailFields.length; n++) {
            if (!EmailFields[n].value.match(EmailCheck)) {
                alert(EmailFields[n].parentNode.getElementsByTagName('label')[0].innerHTML.replace(':', '') + ' is not a valid email address. Please check this and correct as required.');
                e.preventDefault();
                return false;
            }
        }
    })
}

function ValidateMediaCodeSelection() {
    $('form.frmMediaCodeSelection').submit( function(e) {
        var target = $(e.target)[0];
        var MandatoryInputs = $('input.frmMan', target)
        var MediaCodeValidated = false;
        var ElementChildren;

        //Check for mandatory inputs
        for (var n=0; n<MandatoryInputs.length; n++) {
            if (MandatoryInputs[n].checked) {
                ElementChildren = MandatoryInputs[n].parentNode.getElementsByTagName("ul");
                if (ElementChildren.length == 0) {
                    MediaCodeValidated = true;
                    break;
                }
            }
        }

        if (!MediaCodeValidated) {
            alert("Please select where you heard about us from the list");
            e.preventDefault();
            return false;
        }
    })
}

//$(document).ready(function() {
//    // Set up the carousel
//    if ($('div.carousel').length) { $('div.carousel').mmCarousel({'autoAnimate' : true }); }
//});

//// Maximuscle Carousel functionality
//(function($) {
//    $.fn.mmCarousel = function(settings) {
//        var config = { 'positionChangeSpeed': 750, 'animateEasing': 'easeOutExpo', 'autoAnimate' : false, 'animateDelay' : 3000  };
//        var carousel
//        var listToMove
//        var widthOfContainer
//        var widthOfElement
//        var noElementsInCarousel
//        var maxPosition
//	
//	var animateDirection;
//	var animateTimer;
//	
//        if (settings) $.extend(config, settings);

//        function fadeNavigation(newPosition) {
//            var listPos = $(listToMove).position().left + newPosition
//            var showNextArrow = false
//            var showPrevArrow = false
//            var nextArrow = carousel.find('span.nextArrow')[0]
//            var prevArrow = carousel.find('span.prevArrow')[0]

//            if (listPos <= 0) { showPrevArrow = true }
//            if (listPos >  maxPosition) { showNextArrow = true }

//            if (showNextArrow) { $(nextArrow).fadeIn(); } else { $(nextArrow).fadeOut() }
//            if (showPrevArrow) { $(prevArrow).fadeIn(); } else { $(prevArrow).fadeOut() }
//        }
//	
//	function animateCarousel() {	    	
//	    fadeNavigation(widthOfElement * animateDirection * -1)
//	    
//	    $(listToMove).animate({ 'left': $(listToMove).position().left - widthOfElement * animateDirection + "px" }, config.positionChangeSpeed , function() {
//		var listPos = $(listToMove).position().left

//		if (listPos >= 0 || listPos <= maxPosition) { animateDirection *= -1; }		
//	    });

//	    animateTimer = setTimeout(animateCarousel, config.animateDelay)
//	}

//        this.each(function() {
//            carousel = $(this);
//            widthOfContainer = carousel.width();
//            widthOfElement = carousel.find('li:first').width()
//            noElementsInCarousel = carousel.find('li').length
//            maxPosition = (noElementsInCarousel - (widthOfContainer / widthOfElement)) * widthOfElement * -1

//            listToMove = carousel.find('ul:first')
//	    
//	    if (config.autoAnimate) {
//		// Need to start the animation of the carousel
//		animateDirection = 1
//                animateTimer = setTimeout(animateCarousel, config.animateDelay)
//            }
//	    
//            if (noElementsInCarousel * widthOfElement + 50 > widthOfContainer) {
//                $(listToMove).css('width', noElementsInCarousel * widthOfElement + 50 + "px")
//                carousel.append('<span class="prevArrow" style="display: none;">Prev</span>');
//                carousel.append('<span class="nextArrow">Next</span>');

//                carousel.click(function(e) {
//                    if (carousel.find('ul:animated').length == 0) {
//                        if ($(e.target).hasClass('nextArrow')) {
//                            fadeNavigation(widthOfElement * -1)
//                            $(listToMove).animate({ 'left': $(listToMove).position().left - widthOfElement + "px" }, { duration: config.positionChangeSpeed });
//                        }
//                        if ($(e.target).hasClass('prevArrow')) {
//                            fadeNavigation(widthOfElement)
//                            $(listToMove).animate({ 'left': $(listToMove).position().left + widthOfElement + "px" }, { duration: config.positionChangeSpeed });
//                        }
//                    }
//                })
//		
//		carousel.mouseover(function(e) {
//		    if (config.autoAnimate) { 
//			config.autoAnimate = false;			
//                        clearTimeout(animateTimer);
//                    }		    
//		})
//            }
//	    
//        })
//    }
//})(jQuery);

//Function to track, through Google Analytics, when an object with div class="clickTracker" has been clicked
$(document).ready(function() {
    $('div.clickTracker').click(function(e) {
        var target = e.target;
        var text = '';

        //Get the text from the clicked object
        if (target.tagName == 'IMG') {//If the clicked target is an image...
            text = target.alt;
        } else if (target.tagName == 'A') {//If the clicked target is an anchor...
            text = target.outerText;
            if (text == '' || text == null) {
                text = target.text;
            }
            if (text == '' || text == null) {
                text = target.href;
            }
        } else if (target.tagName == 'SPAN') {//If the clicked target is a span...
            text = target.textContent;
        }

        if (text == '' || text == null) {//If text is empty, record the page and element type (tag) that was clicked
            text = 'Element of type "' + target.tagName + '" on page "' + document.location + '" was clicked';
        }

        //Track the object using Google Analytics
        pageTracker._trackEvent(document.title, 'Object Click', text);
    });
});

// Carousel v2
var _DisplayWidthModules;
var _ModuleSize;

var _SteppingToRight = true;
var _LeftSideModule = 0;
var _Offset = 0;
var _StepTick = 3000;
var _AutoAnimationOn = false;
var _AutoStep = 500;
var _ManualStep = 250;

jQuery(function ($) {

	$(document).ready(function() {
		if ($('#CarouselStrip'))
            InitialiseCarousel();
	});
})

// Initialise the carousel
function InitialiseCarousel()
{
    var StripWidth = 0;
    var ViewportWidth = parseInt($('#CarouselStrip').css('width'));

    // Get the width of the last module in the list (avoids margin issues)
    _ModuleSize = (parseInt($('#CarouselStrip ul li:last').css('margin-left')) + 
        parseInt($('#CarouselStrip ul li:last').css('width')) + 
        parseInt($('#CarouselStrip ul li:last').css('margin-right')));

    // Get the total width of the strip by adding all list item widths and left and right margins and set the strip width
    _DisplayWidthModules = 0;
    $('#CarouselStrip ul li').each(function(index) {
        StripWidth += (parseInt($(this).css('margin-left')) + 
            parseInt($(this).css('width')) + 
            parseInt($(this).css('margin-right')));
        
        if (StripWidth <= ViewportWidth) {
            _DisplayWidthModules++;
        }
    });
    $('#CarouselStrip ul').css('width',StripWidth + "px");


    // if we have more modules than the width of the viewport, set for interaction and start the auto animation
    if ($('#CarouselStrip ul li').length > _DisplayWidthModules)
    {
        $('#CarouselStrip').append('<span class="prevArrow" style="display: none;">Prev</span>');
        $('#CarouselStrip').append('<span class="nextArrow">Next</span>');



        // if we click on the carousel, stop auto animation and scroll if required
        $('#CarouselStrip').click(function(e) {
            _AutoAnimationOn = false;
            if ($(e.target).hasClass('nextArrow')) {
                HandleAnimation(true, _ManualStep);
            }
            if ($(e.target).hasClass('prevArrow')) {
                HandleAnimation(false, _ManualStep);
            }
        });

        $('#CarouselStrip').mouseover(function(e) {
            _AutoAnimationOn = false;
        });
        
        if ($('#CarouselStrip').hasClass('autoAnimate')) {
            _AutoAnimationOn = true;
            setTimeout('HandleAnimationTick()', _StepTick);
        }
    }
}

function HandleAnimationTick()
{
    // Are we running on auto? If so then handle and reset
    if (_AutoAnimationOn)
    {
        // Do the animation
        HandleAnimation(_SteppingToRight, _AutoStep);

        // Check if we are at the limits and reverse the direction accordingly
        if (_LeftSideModule < 1) {
            _SteppingToRight = true;
        }
        else if ((_LeftSideModule + _DisplayWidthModules) >= $('#CarouselStrip ul li').length) {
            _SteppingToRight = false;
        }

        // Set the timeout for the next tick
        setTimeout('HandleAnimationTick()', _StepTick);
    }
}

function HandleAnimation(MoveRight, AnimationSpeed)
{
    var StepSize = 0;
    
    // Step the module and offset
    if ((MoveRight) && ((_LeftSideModule + _DisplayWidthModules) < $('#CarouselStrip ul li').length)) {
        _LeftSideModule++;
        StepSize = -_ModuleSize;
        
        // if we have hit the right hand end, fade out the move right arrow
        if ((_LeftSideModule + _DisplayWidthModules) == $('#CarouselStrip ul li').length) {
            $('#CarouselStrip span.nextArrow').fadeOut();
        }
        // if we have left the left hand end, fade in the move left arrow
        if (_LeftSideModule == 1) {
            $('#CarouselStrip span.prevArrow').fadeIn();
        }
    }
    else if ((!MoveRight) && (_LeftSideModule > 0)) {
        _LeftSideModule--;
        StepSize = _ModuleSize;

        // if we have hit the left hand end, fade out the move left arrow
        if (_LeftSideModule == 0) {
            $('#CarouselStrip span.prevArrow').fadeOut();
        }
        // if we have left the right hand end, fade in the move right arrow
        if ((_LeftSideModule + _DisplayWidthModules) == ($('#CarouselStrip ul li').length - 1)) {
            $('#CarouselStrip span.nextArrow').fadeIn();
        }
    }

    // Animate
    _Offset += StepSize;
    $('#CarouselStrip ul').animate({left: (_Offset) + 'px'}, {duration: AnimationSpeed, easing: 'linear', complete: function(){}});
}
// End carousel v2