var IE6FLAG = ($.browser.msie && parseFloat($.browser.version) < 7) ? true : false;

// For debugging
function trace (msg) {
    if (this.console && typeof console.log != "undefined")
        console.log(msg);
}

// JavaScript Document
$(function () {

    //JQuery for the global search box
    $('#header .globalSearch .text').val('Search the Everest site :').focus(function () {
        $(this).parent().css('backgroundPosition', 'bottom');
        $(this).val('');
    }).blur(function () {
        $(this).parent().css('backgroundPosition', 'top');
        if ($(this).val() == '') $(this).val('Search the Everest site :');
    });

    //Hover menu
    /*$('.menuShadow').css({ left: '8px', display: 'none' });
    $('.menu').css({ display: 'block' });

    if (IE6FLAG) $('.menuShadow').css({ padding: '0', margin: '0' }).find('menu, ul, li').css({ padding: '0', margin: '0' });
    if (IE6FLAG) $('#globalNav .menuShadow').css({ left: '0' });*/

    if ($('.flashBannerContainer').length > 0 && $('.flashBannerContainer').html().length < 5) $('.flashBannerContainer').remove();

    $("#header ul.topNav li, #header ul#globalNav li")
        .mouseenter(
            function () {
                //if (!IE6FLAG) $(this).find('a').addClass('keepWhite');
                $(this).find('.menu').show();
                $(this).find('.menuShadow').show(); //.stop(true, true).fadeIn();
            }
        );
    $("#header ul.topNav li, #header ul#globalNav li")
        .mouseleave(
            function () {
                //$(this).find('a').removeClass('keepWhite');
                $(this).find('.menuShadow').hide(); //.stop(true, true).fadeOut();
            }
        );
    $("#header ul.topNav li")
        .mouseleave(
            function () {
                if (!IE6FLAG) Cufon.replace($(this).find('a'), { hover: true });
            }
        );

    $("#header ul.topNav li .menu, #header ul#globalNav li .menu").mouseenter(
        function () {
            $(this).parent().prev().addClass('menuHover');
        }
    );
    $("#header ul.topNav li .menu, #header ul#globalNav li .menu").mouseleave(
        function () {
            $(this).parent().prev().removeClass('menuHover');
        }
    );


    // PopBox Function
    $(".JQPopBox .cta,.JQPopBox2 .cta,.JQPopBox3 .cta")
        .mouseenter(
            function () {
                $(this).find('.noShow').stop(true).animate({ opacity: 1 }, 'slow');
                $(this).find('.inner').stop(true).animate({ opacity: 0.9, height: '105px' }, 'slow');
            });
    $(".JQPopBox .cta, .JQPopBox2 .cta,.JQPopBox3 .cta")
        .mouseleave(
            function () {
                $(this).find('.noShow').stop(true).animate({ opacity: 0 }, 'slow');
                $(this).find('.inner').stop(true).animate({ opacity: 0.8, height: '40px' }, 'slow');
            });

    /** version  3 **/
    if (document.getElementById('fasterPrev')) {
        var scroller = $('.scroller').css({ position: 'absolute', left: '0px' });
        var scrollWidth = $('.scrollerContainer').width();
        var scrollElements = $('.scroller li');
        var elementWidths = scrollElements[0].offsetWidth + 5;
        var scrollerPosition = 0;

        var timer = null;
        var speed = 20;
        var startSpeed = speed;
        var faster = 2;
        var direction = 'left';
        var waitTime = 3000;
        for (var i = 1, len = scrollElements.length; i < len; i++) elementWidths = elementWidths + scrollElements.eq(i).width() + 5;
        scroller.css({ width: elementWidths + 'px' });

        $('#fasterPrev').click(function () { return false; }).mouseenter(function () { clearTimeout(timer); scroller.stop(); scroll('right', faster); });
        $('#fasterNext').click(function () { return false; }).mouseenter(function () { clearTimeout(timer); scroller.stop(); scroll('left', faster); });
        $('#fasterNext, #fasterPrev').mouseleave(function () { scroller.stop(); scroll(null, startSpeed); });

        scroller.hover(function () { clearTimeout(timer); scroller.stop(); }, function () { scroll(); });

        function scroll(inDirection, inSpeed) {
            if (elementWidths - scrollWidth < 20) return false;
            if (inDirection) direction = inDirection;
            if (inSpeed) speed = inSpeed;
            clearTimeout(timer);

            var timeLeft = (elementWidths - scrollWidth + parseInt(scroller.css('left'))) * speed;
            var timeRight = (parseInt(scroller.css('left')) * -1) * speed;
            var rightLimit = parseInt((elementWidths - scrollWidth) * -1) + 5;

            if (direction == 'left')
                scroller.animate({ left: rightLimit + 'px' }, timeLeft, 'linear',
                    function () {
                        direction = 'right';
                        if (speed > 2) timer = setTimeout(function () { scroll(); }, waitTime);
                    }
                );
            else
                scroller.animate({ left: '0px' }, timeRight, 'linear',
                    function () {
                        direction = 'left';
                        if (speed > 2) timer = setTimeout(function () { scroll(); }, waitTime);
                    }
                );
        }

        if (elementWidths - scrollWidth > 20) {
            $('#fasterPrev,#fasterNext').show();
            scroll('left', startSpeed);
        }
        else {
            $('.scrollPod').css({ paddingRight: 0 });
            $('#fasterPrev,#fasterNext').remove();
        }
    }

    $('.accordionButton').click(function () {
        $('.accordionButton').removeClass('on');
        $('.accordionContent').slideUp('normal');
        if ($(this).next().is(':hidden') == true) {
            $(this).addClass('on');
            $(this).next().slideDown('normal');
        }
        return false;
    });

    $('.accordionButton')
        .mouseover(function () { $(this).addClass('over'); })
        .mouseout(function () { $(this).removeClass('over'); });
    $('.accordionContent').hide();

    var pageIdInUrl = window.location.hash;
    if (pageIdInUrl) {
        preopenedFaq = $(document.getElementById(pageIdInUrl.replace("#", "")));
        preopenedFaq.addClass('on');
        preopenedFaq.next().slideDown('normal');
    }


    /*** Sitemap ***/
    //Splits the sitemap into two columns
    /*var topLevel = $('#sitemap > ul > li')
    var totalTLE = topLevel.length;
    topLevel.each(function () {
    if ((totalTLE / 2) > topLevel.index(this)) {
    $(this).addClass('colOne')
    } else {
    $(this).addClass('colTwo')
    }
    });*/

    colTwoHeight = $('.colTwo').outerHeight();
    $('.colTwo').first().css('marginTop', '-' + colTwoHeight + 'px');

    //created the dynamic tree
    $('#sitemap ul li ul').each(
        function () {
            var theUL = $(this);
            var plusBTN = $('<img class="toggleBTN" src="/images/plus.gif" alt="plus symbol" title="Expand selection" />');
            var minusBTN = $('<img class="toggleBTN" src="/images/minus.gif" alt="minus symbol" title="Collapse selection" />');

            plusBTN.prependTo(theUL.parent());
            theUL.parent().css('margin-left', '-12px');
            theUL.hide();

            plusBTN.click(function (e) {
                minusBTN.prependTo(theUL.parent()).hide();
                //e.stopPropagation();
                theUL.slideDown('slow');
                $(this).hide();
                minusBTN.show().click(function () {
                    theUL.slideUp('slow');
                    $(this).hide();
                    plusBTN.show();
                });
            });
        }
    );

    if (document.getElementById('scrollPodSmall')) {
        var scrollerSm = $('.scrollerSmall').css({ position: 'absolute', left: '0px' });
        var scrollWidthSm = $('.scrollerContainerSmall').width();
        var scrollElementsSm = $('.scrollerSmall li');
        var elementWidthsSm = 0;
        var scrollerPositionSm = 0;

        var timerSm = null;
        var speedSm = 10;
        var startSpeedSm = speedSm;
        var fasterSm = 2;
        var directionSm = 'left';
        var waitTimeSm = 3000;

        for (var i = 0, len = scrollElementsSm.length; i < len; i++) { elementWidthsSm = elementWidthsSm + scrollElementsSm.eq(i).width() + 12; }
        scrollerSm.css({ width: elementWidthsSm + 'px' });
        scrollElementsSm.filter(':last').css({ marginRight: 0 });

        $('#scrollBack').click(function () { return false; }).mouseenter(function () { clearTimeout(timerSm); scrollerSm.stop(); scrollSm('right'); });
        $('#scrollNext').click(function () { return false; }).mouseenter(function () { clearTimeout(timerSm); scrollerSm.stop(); scrollSm('left'); });
        $('#scrollNext, #scrollBack').mouseleave(function () { scrollerSm.stop(); });

        $('#scrollPodSmall li a').click(function () {
            $('.scrollingGallery .slideShow img').attr('src', $(this).attr('rel'));
            $('#scrollPodSmall li.active').removeClass('active');
            $(this).parent().addClass('active');
            return false;
        });


        function scrollSm(inDirection, inSpeed) {
            if (elementWidthsSm < scrollWidthSm) return false;
            if (inDirection) directionSm = inDirection;
            speedSm = (inSpeed) ? inSpeed : 5;
            clearTimeout(timerSm);

            var timeLeft = (elementWidthsSm - scrollWidthSm + parseInt(scrollerSm.css('left'))) * speedSm;
            var timeRight = (parseInt(scrollerSm.css('left')) * -1) * speedSm;
            var rightLimit = ((elementWidthsSm - scrollWidthSm) * -1) - 7;

            if (directionSm == 'left') scrollerSm.animate({ left: rightLimit + 'px' }, timeLeft, 'linear');
            else scrollerSm.animate({ left: '19px' }, timeRight, 'linear');
        }

        if (elementWidthsSm > scrollWidthSm) {
            $('#scrollBack,#scrollNext').show();
        }
        else {
            $('.scrollPodSmall').css({ paddingRight: 0 });
            $('#scrollBack,#scrollNext').remove();
        }
    }
    // creates bigger cta links
    $('.standardPodBox .cta').css('cursor', 'pointer').click(function () {
        window.location = ($(this).find('h3 a').attr('href'));
    });
    $('.itemWrapper').css('cursor', 'pointer').click(function () {
        window.location = ($(this).find('a').attr('href'));
    });
    $('.four-up .cell').css('cursor', 'pointer').click(function () {
        window.location = ($(this).find('a').attr('href'));
    });
});                                               
//end document ready

/*** CUFON ***/
$.each(['h1', 'h2:not(.tabContainer h2)', '.cufon', '#appointmentForm2 h3'],
    function (i, value) {
        Cufon.replace(value, { fontFamily: 'helvetica-light' });
    }
);

$.each(['h1', '.sup', 'h1', '.sub', 'h1 span.transforming', 'h2 span.offerHeading2', '#transform-house h1 span'],
    function(i, value) {
        Cufon.replace( value, { fontFamily: 'helvetica-roman' });
    }
);

if (!IE6FLAG) Cufon.replace('#header .topNav li a, h3.cufon', { hover: true, fontFamily: 'helvetica-roman' });

/*** Form utils ***/

function showJsError(msg) {
    $("#jsErrorContainer").css('display', 'block');
    $("#jsErrorMessage").html(msg);
    $('html,body').animate({ scrollTop: ($('#jsErrorContainer').offset().top-10) });
}

// align buttons vertically based on height of container div
$(function(){
    $(".alignButtons").each(function () {
        var containerDivHeight = $(this).height();
        $(this).find("> div.threeUp").each(function () {
            $(this).height(containerDivHeight - 39);
        });
    });
});

//Material and colour selector
var SwatchSelector = function () {
    this.detailInner = $('.swatches .detailInner')
    this.detail = $('.swatches .detail');
    this.detailWidth = this.detail.outerWidth(true);
    this.detailCount = this.detail.length;
    this.clicks = 0;
    this.theLink = $('.swatchThumbs a');
    this.detailInner.css('width', this.detailWidth * this.detailCount + 'px');
    this.arrowRight = ""
    this.arrowLeft = ""
    this.arrowRight = $('<span class="arrowRight">&lt;</span>').prependTo('.swatches .detailOuter');
    this.arrowLeft = $('<span class="arrowLeft">&lt;</span>').prependTo('.swatches .detailOuter');
}
//Change the displayed item
SwatchSelector.prototype.moveDetail = function() {
    if (this.clicks >= 0 && this.clicks < this.detailCount) {
        this.detailInner.css('left', '-'+this.detailWidth * this.clicks + 'px');
    };
};
//Move right
SwatchSelector.prototype.right = function () {
    var obj = this;
    obj.arrowRight.click(function (e) {
        e.preventDefault();
        if (obj.clicks < obj.detailCount - 1) { obj.clicks++; }
        obj.moveDetail();
        obj.highlight($('.swatchThumbs a[rel="' + (obj.clicks + 1) + '"]').find('div').first());
        obj.highlightTab();        
    });
}
//Move Left
SwatchSelector.prototype.left = function () {
    var obj = this;
        obj.arrowLeft.click(function (e) {
            e.preventDefault();
            if (obj.clicks > 0) { obj.clicks--; }
            obj.moveDetail();
            obj.highlight($('.swatchThumbs a[rel="' + (obj.clicks + 1) + '"]').find('img').first());
            obj.highlightTab();
        });
}
//jump to item
SwatchSelector.prototype.picker = function () {
    var obj = this;
    obj.theLink.click(function (e) {
        e.preventDefault();
        obj.clicks = $(this).attr('rel') - 1;
        obj.moveDetail();
        obj.highlight($(this).find('.border-d'))
    });
}
//switch tabs to show highted item
SwatchSelector.prototype.highlightTab = function () {
    var obj = this;
    var currentTabNo = obj.theLink.find('.border-a').parents('.tabContents>div').attr('class').charAt(3);
    var currentTab = $('.tabContents .tab' + currentTabNo)
    var tabCount = $('.tabContainer a').length;
    currentTab.parent().parent().find('.tab' + tabCount + 'up-active').removeClass().addClass('tab' + tabCount + 'up');
    $('.tabContainer .tab' + tabCount + 'up[rel="' + currentTabNo + '"]').removeClass().addClass('tab' + tabCount + 'up-active');
    $('.tabContents>div').hide();
    currentTab.show();
}
//highlight swatch
SwatchSelector.prototype.highlight = function (item) {
    var item = item;
    this.theLink.find('.border-a').removeClass('border-a').addClass('border-d');
    item.removeClass('border-d').addClass('border-a');
}
//generate tabs
SwatchSelector.prototype.tabs = function () {
    //unhide tabs
    $('.tabContainer').show();
    //hide inactive tab containers
    $('.tab2').hide();
    $('.tab3').hide();
    $('.tab4').hide();
    //count tabs
    var tabCount = $('.tabContainer a').length;
    //show clicked tab
    $('.tabContainer a').click(function () {
        var tabNo = $(this).attr('rel');
        $(this).parent().find('.tab' + tabCount + 'up-active').removeClass().addClass('tab' + tabCount + 'up');
        $(this).removeClass().addClass('tab' + tabCount + 'up-active');
        $('.tabContents>div:visible').hide();
        var currentTab = $('.tabContents .tab' + tabNo);
        currentTab.show();
        currentTab.find('.swatchThumbs li:first a').click();
    });

}
//initialise object
SwatchSelector.prototype.init = function () {
    this.tabs();
    this.left();
    this.right();
    this.picker();
    this.highlight(this.theLink.find('.border-d').first());
}
$(function () {
    var ss = new SwatchSelector();
    ss.init();
});

// Tab selector for MCSelect section
$(function () {
    $('#MCSelector .tabContents>div').hide();
    $('#MCSelector .tabContents>div:first').show();
    $('#MCSelector .clear').show();
    //as these are not links, disable any actions set by the swatch function
    $('#MCSelector .swatchThumbs a').click(function () { $(this).find('img.border-a').removeClass().addClass('border-d'); return; }).find('img.border-a').removeClass().addClass('border-d');
    //count tabs
    var tabCount = $('#MCSelector .tabContainer a').length;
    //show clicked tab
    $('#MCSelector .tabContainer a').click(function () {
        var tabNo = $(this).attr('rel');
        $(this).parent().find('.tab' + tabCount + 'up-active').removeClass().addClass('tab' + tabCount + 'up');
        $(this).removeClass().addClass('tab' + tabCount + 'up-active');
        $('#MCSelector .tabContents>div:visible').hide();
        $('#MCSelector .tabContents .tab' + tabNo).show();
        $('#MCSelector .clear').show();
    });
});


//transforming homes slider
$(function () {

    if ($('#transform-house-wrapper').length) {

        //add slider elements
        var newHouse = $('<div id="newHouse"><img src="/images/transform-house/house1-new.jpg" width="780" height="486" alt="" id="newHouseImage" /></div>');
        $('#draggable-area').append(newHouse);

        var newSlider = $('<div id="slider"></div>');
        $('#draggable-area').append(newSlider);
        $('#slider').fadeIn('slow');

        var newTooltip = $('<div id="tooltip"><p>Drag slider to transform this home</p>');
        $('#draggable-area').append(newTooltip);
        $('#tooltip').fadeIn('slow');

        //highlight thumbnail and swap images
        $('#thumbs li').click(function () {
            $('#thumbs li').removeClass('selected');
            $(this).addClass('selected');
            var newOldImage = $(this).find('img').attr('src').replace('thumb', 'old');
            var newNewImage = $(this).find('img').attr('src').replace('thumb', 'new');
            $("#newHouseImage").attr({ src: newNewImage });
            $("#oldHouseImage").attr({ src: newOldImage });
            //$("#slider").css('left', 203);
            //$("#newHouse").width(246);
            _gaq.push(['_trackEvent', 'UI', 'Transform Banner', 'House']);

        });

        $('#thumbs a').click(function (e) {
            e.preventDefault();
        });
        var fireOnce = true;
        $("#slider").draggable({
            axis: "x",
            containment: "parent",
            cursor: "pointer",
            drag: function (event, ui) {
                var newWidth = (ui.position.left);
                $("#newHouse").width(newWidth + 43);
                $("#tooltip").fadeOut(350);

                if (fireOnce == true) {
                    _gaq.push(['_trackEvent', 'UI', 'Transform Banner', 'Slider']);
                    fireOnce = false;
                }
            }
        });

        $('#slider').mouseup(function () {
            fireOnce = true;
        });

    };
    //Add GA tracking to the transform form (fire only once)
    var offerFormClicked = false;
    $('#offerForm .inputBlock').click(function () {
        if (offerFormClicked == false) {
             _gaq.push(['_trackPageview', 'VPV / Campaigns / Transform / Make An Appointment']);
            offerFormClicked = true;
        }
    });
});
// adds a leading zero to a number if required
function lz(number, length) {
    var str = '' + number;
    while (str.length < length) { str = '0' + str;  }  
    return str;
}

$(function () {
    // Everest Transform countdown timer
    var CDContainer = $('#countdown');
    var secondsRemainingH = CDContainer.find('.secondsRemaining');

    if (secondsRemainingH.length) { // offer still active?...

        var secondsRemainingTotal = Math.floor(secondsRemainingH.html());
        var daysH = $('<div class="days"></div>').appendTo(CDContainer);
        var hoursH = $('<div class="hours"></div>').appendTo(CDContainer);
        var minsH = $('<div class="mins"></div>').appendTo(CDContainer);
        var secsH = $('<div class="secs"></div>').appendTo(CDContainer);

        CDContainer.add('.offerRoundel').show();    // show timer and roundel

        // extended offer? (hard coded dates!)
        var now = new Date();
        //var extStart = new Date("September 21, 2011 15:00:00");
        //var extStop = new Date("October 5, 2011 00:01:00");
        //(now > extStart && now < extStop) ? $("#offerExtendedStamp").show() : $("#offerExtendedStamp").hide();

        var getTime = function () {
            secondsRemainingTotal--;
            var days = Math.floor(secondsRemainingTotal / 86400);
            if (secondsRemainingTotal > 0) {
                var hours = Math.floor((secondsRemainingTotal % 86400) / 3600);
                var minutes = Math.floor(((secondsRemainingTotal % 86400) % 3600) / 60);
                var seconds = Math.floor(((secondsRemainingTotal % 86400) % 3600) % 60);
                daysH.html('<span>' + lz(days, 1) + '</span>');
                hoursH.html('<span>' + lz(hours, 2) + '</span>');
                minsH.html('<span>' + lz(minutes, 2) + '</span>');
                secsH.html('<span>' + lz(seconds, 2) + '</span>');
            }
            else if (days < 0) {
                CDContainer.hide();
            }
            else {
                daysH.html('<span>00</span>');
                hoursH.html('<span>00</span>');
                minsH.html('<span>00</span>');
                secsH.html('<span>00</span>');
            }
        };
        secondsRemainingH.remove();
        setInterval(function () { getTime(); }, 1000);
    }
});

// form tooltip
$(function () {
    //$('#appointmentForm2 .tip').bgiframe();

    $('#appointmentForm2 .tip').css('visibility', 'hidden');

    $('#appointmentForm2 a.help').mouseover(function () {
        $(this).next().css('visibility', 'visible');
        if (trackTooltip)
            trackTooltip($(this).attr('title'));
    });
    $('#appointmentForm2 a.help').mouseout(function () {
        $(this).next().css('visibility', 'hidden');
    });
});

var playedOnce = false;
var player = null;
var videoId = null;

function onYouTubePlayerReady(playerId) {
    player = document.getElementById('ytPlayer');
    if (!player)
        return;

    player.addEventListener('onStateChange', 'youtubeEvent');
}

// This event is fired whenever the player's state changes. 
// Possible values are unstarted (-1), ended (0), playing (1), paused (2), buffering (3), video cued (5). 
// When the SWF is first loaded it will broadcast an unstarted (-1) event. 
// When the video is cued and ready to play it will broadcast a video cued event (5).
function youtubeEvent(state) {
    var videoUrl = player.getVideoUrl();
    if (videoId == null)
        videoId = getVideoId(videoUrl);
    
    if (state == -1) {
        _gaq.push(['_trackEvent', 'Video', videoId, 'video player loaded']);
    }
    else if (state == 1) {
        if (!playedOnce) {
            playedOnce = true;
            _gaq.push(['_trackEvent', 'Video', videoId, 'first play']);
        } else {
            _gaq.push(['_trackEvent', 'Video', videoId, 'play']);
        }
    }
    else if (state == 2) {
        _gaq.push(['_trackEvent', 'Video', videoId, 'video paused']);
    }
    else if (state == 5) {
        _gaq.push(['_trackEvent', 'Video', videoId, 'video cued']);
    }
    else if (state == 0) {
        _gaq.push(['_trackEvent', 'Video', videoId, 'ended']);
    }
}

function getVideoId(url) {
    var videoIdRegex = new RegExp('[\\?&]v=([^&#]*)');
    var results = videoIdRegex.exec(url);
    if (results == null)
        return "";
    else
        return results[1];
}

// modal postcode lookup
$(function () {

    $('#postcodeLookup .btnNext, #postcodeLookup .btnClose, #postcodeLookup .btnCancel').live('click', function () {
        hideModal();
    });


    //handle browser resize 
    $(window).bind('resize', function () {
        $('#postcodeLookup').centerContent();
    });

});

/* Modal Popup Control */

function showModal() {
    //check if specified ID exists
    var overlayHeight = $(document).height();

    if ($('#overlay').length) {
        $('#overlay').height(overlayHeight);
        //$('#overlay').bgiframe();
        $('#overlay').css('visibility', 'visible');
        $('#overlay').css('opacity', '0.4');
        $('#postcodeLookup').css('visibility', 'visible');
        $('#postcodeLookup').centerContent();
        $('html, body').animate({ scrollTop: 0 }, 0);
        }
    else {
        var theForm = $('<div id="overlay"></div><div id="postcodeLookup"><h3 class="cufon">Please select address from the list</h3><a href="#" class="btnClose">Close window</a><input class="btnNext" type="submit" value="submit" /><p>Can\'t find your address above? <a href="#" class="btnCancel">Click Here</a></p></div>');
        $('body').append(theForm);
        $('#overlay').height(overlayHeight);
        //$('#overlay').bgiframe();
        $('#overlay').css('visibility', 'visible');
        $('#overlay').css('opacity', '0.4');
        $('#postcodeLookup').centerContent();
        $('#postcodeLookup').css('visibility', 'visible');
        Cufon.replace('#postcodeLookup h3', { fontFamily: 'helvetica-light' });
        $('html, body').animate({ scrollTop: 0 }, 0);
    }
}

function hideModal() {
    //check if specified ID exists
    if ($('#overlay').length) {
        $('#overlay').css('visibility', 'hidden');
        $('#postcodeLookup').css('visibility', 'hidden');
    }
    else {
        return false;
    }
}

function validateContactPreference_ClientValidate(sender, args) {
    var validation = $(sender);
    var telephoneTxt = $('input[name$="TelephoneTxt"]');
    var mobileTxt = $('input[name$="MobileTxt"]');

    if (args.Value == "none") {
        args.IsValid = false;
        validation.html('Please select your contact preference');
    }
    else if (args.Value == telephoneTxt.attr('title') && telephoneTxt.val().length == 0) {
        args.IsValid = false;
        validation.html('Please enter a ' + args.Value + ' to select this option');
    }
    else if (args.Value == mobileTxt.attr('title') && mobileTxt.val().length == 0) {
        args.IsValid = false;
        validation.html('Please enter a ' + args.Value + ' to select this option');
    }
    else
        args.IsValid = true;
}

/****** PLUGINS *******/

(function ($) {

    /** jQuery centerContent (modal pop-up) plugin **/

    $.fn.centerContent = function() {
        return this.each(function() {
            var top = ($(window).height() - $(this).outerHeight()) / 2;
            var left = ($(window).width() - $(this).outerWidth()) / 2;
            $(this).css({ position: 'absolute', margin: 0, top: (top > 0 ? top : 0) + 'px', left: (left > 0 ? left : 0) + 'px' });
        });

    };
    
    /** jQuery Glossary List **/
    $.fn.glossaryNav = function(options) {
        var opts = $.extend({}, $.fn.glossaryNav.defaults, options);
        var letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
        var activeList = null;
        var activeLink = null;
        
        return this.each(function() {
            var navContainer, listContainer, emptyContainer;
            listContainer = $(this);
            
            function init() {
                emptyContainer = $(opts.emptyContainerId);
                navContainer = $(opts.navContainerId);
                
                listContainer.children('dl').each(function (i, item) {
                    $(item).hide();
                });

                navContainer.find('a').click(function() {
                    var letter = $(this).text();
                    if(activeList != null)
                        activeList.hide();
                    
                    if(activeLink != null)
                        activeLink.parent().removeClass('selected');

                    activeLink = $(this);
                    activeLink.parent().addClass('selected');

                    activeList = listContainer.children('#' + letter);
                    if(activeList.children().length == 0)
                        emptyContainer.show();
                    else {
                        activeList.show();
                        emptyContainer.hide();
                    }

                    return false;
                });
                
                showDefault();
            };
            
            function showDefault() {
                activeLink = navContainer.find('a:has(span:contains("'+opts.initLetter+'")):first');
                if(!activeLink.hasClass('selected'))
                    activeLink.addClass('selected');

                activeList = listContainer.children('#' + opts.initLetter);
                activeList.show();
            }
            
            init();
        });
    };
    
    $.fn.glossaryNav.defaults = {
        initLetter: 'A',
        navContainerId: '#glossaryNav',
        emptyContainerId: '#noItems'
    };

})(jQuery);



