/**
* @author peter.fields
* @author sunny.virk
*/

var $j = jQuery.noConflict();

//var ageGroupSet = null;
//var programSet = null;
//var mktSet = null;
var gh = {};


var efInitalize = function () {

    gh.globals = {
        ageGroupAjaxInitiated: 0,
        programsAjaxInitiated: 0,
        contactAjaxInitiated: 0,
        ageGroupCounter: 0,
        ageGroupSet: null,
        programSet: null,
        mktSet: null,
        error404: 'Please contact the web administrator, something went wrong',
        globalHeaderOpenClose: false,
        funnelContent: false,
        contactContent: false,
        ageGroupHttp: null,
        programListsHttp: null,
        programDetailsHttp: null,
        productNameLine1: null,
        productNameLine2: null,
        googleMapsScript: false,
        agegroupTracker: 'unknown',
        productTracker: 'unknown',
        globalcontent: 'unknown',
        infoBubble: false,
        trackerCall: '1',
        fireEvent: 'false',
        trackerEnabled: true
    };

    // Generic Global Header Functions
    gh.generic = {

        // Global Mask
        globalMask: function (state) {
            if (state === 0) {
                $j("#global-mask").fadeTo(600, 0, function () {
                    $j(this).hide();
                });
            } else {
                $j("#global-mask").fadeTo(600, 0.5);
            }
        }, // end globalMask()

        // Function for opening and closing globalHeader
        closeGlobalHeader: function () {
            if (gh.globals.globalHeaderOpenClose === true) {
                if (gh.globals.funnelContent === true) {
                    if (gh.globals.programsAjaxInitiated === 0) {
                        $j('#age-group-options').slideToggle();
                    } else {
                        $j('#global-content').slideToggle(700);
                    }
                    gh.globals.funnelContent = false;
                }
                if (gh.globals.contactContent === true) {
                    $j('#global-contact-us').slideToggle(700);
                    gh.globals.contactContent = false;
                }
                gh.generic.globalMask(0);
                gh.globals.globalHeaderOpenClose = false;
                $j('#global-links ul li').removeClass('current');
            }
        }, // end closeGlobalHeader()

        switchContent: function () {
            if (gh.globals.funnelContent === true) {
                if (gh.globals.programsAjaxInitiated === 0) {
                    $j('#age-group-options').slideToggle(700);
                } else {
                    $j('#global-content').slideToggle(700);
                }
                gh.globals.funnelContent = false;
            }
            if (gh.globals.contactContent === true) {
                $j('#global-contact-us').slideToggle(700);
                gh.globals.contactContent = false;
            }
            $j('#global-links ul li').removeClass('current');
        },

        // Set up a ajax GetXmlHttpObject 
        GetXmlHttpObject: function () {
            if (window.XMLHttpRequest) {
                // code for IE7+, Firefox, Chrome, Opera, Safari
                return new XMLHttpRequest();
            }
            if (window.ActiveXObject) {
                // code for IE6, IE5
                return new ActiveXObject("Microsoft.XMLHTTP");
            }
            return null;
        }, // end GetXmlHttpObject()

        // general helper functions to tidy up html after load
        helperFunctions: function () {
            return {

                optionsLastChild: function (target) {
                    $j(target).addClass('last');
                }, // end optionsLastChild()

                optionsLength: function (target) {
                    var length = $j(target).length;
                    var width = 0;
                    $j(target).closest('ul').addClass('module-length-' + length);
                    if (length === 1) {
                        $j(target).closest('div').hide();
                        if ($j(target).closest('div').parent().parent().attr('id') === 'product-contact-us') {
                            if (!$j('html').hasClass('ie6')) {
                                $j('#product-contact-us #contact-info div.map-container').css({ 'top': '-251px' });
                            } else {
                                $j('#product-contact-us #contact-info div.map-container').css({ 'top': '-230px' });
                            }
                        } else if ($j(target).closest('div').parent().parent().attr('id') === 'global-content-container') {
                            $j('#global-contact-us').css({ 'height': '588px' });
                        }
                    }
                }, // end optionsLength()

                optionsHeights: function (target, paddingType) {
                    var anchorHeight = 0;
                    $j(target).each(function () {
                        if (anchorHeight < $j(this).height()) {
                            anchorHeight = $j(this).height();
                        }
                    });
                    $j(target).each(function () {
                        if (paddingType === 'funnelling') {
                            if ($j(this).height() < parseInt(anchorHeight, 10)) {
                                if (anchorHeight === 30) {
                                    $j(this).css({ 'padding': '24px 20px 23px' });
                                }
                                if (anchorHeight === 28) {
                                    $j(this).css({ 'padding': '23px 20px 23px' });
                                }
                            } else if ($j(this).height() < 28) {
                                $j(this).css({ 'padding': '23px 20px 23px' });
                            }
                        } else if (paddingType === 'contact-us') {
                            if ($j(this).height() < parseInt(anchorHeight, 10)) {
                                if (anchorHeight === 30) {
                                    $j(this).css({ 'padding': '24px 10px 23px' });
                                }
                                if (anchorHeight === 28) {
                                    $j(this).css({ 'padding': '23px 10px 23px' });
                                }
                            } else if ($j(this).height() < 28) {
                                $j(this).css({ 'padding': '23px 10px 23px' });
                            }
                        }
                    });
                }, // end optionsHeights()

                destinationLength: function () {
                    $j('#program-details div:first > div').not(':first').each(function () {
                        if ($j(this).find('.duration ul li').length > 1) {
                            if ($j(this).find('.duration ul li:nth-child(2n)').text() === '') {
                                $j(this).find('.duration ul li:first').addClass('singleItem');
                            }
                        }
                        if ($j(this).find('.program-destinations p').length > 1) {
                            var destChar = $j(this).find('.program-destinations p').not(':first').html();
                            if (destChar.length > 156) {
                                var hiddenText = '<p class="hiddenText">' + destChar + '<a href="#">X</a></p>';
                                var newDestChar = destChar;
                                newDestChar = newDestChar.substring(0, 150) + '... <a class="read-more-ht png_bg" href="#"></a>';
                                $j(this).find('.program-destinations p').not(':first').html(newDestChar);
                                $j(this).find('.program-destinations').append(hiddenText);
                            }
                        }
                    });
                }, // end destinationLength()

                siteInEnglish: function () {
                    if ($j('#in-english-site').length > 0) {
                        $j('#in-english-site').each(function () {
                            var siteParentObj = $j(this).parent().parent();
                            var siteParentId = siteParentObj.attr('id');
                            $j(this).addClass(siteParentId + 'englishSiteText');
                            siteParentObj.find('#product-site a').addClass('englishSiteButton').attr('data-es-path', siteParentId);
                        });
                    }
                }

            };
        }, // end helperFunctions()

        universalLinks: function () {
            $j('#universal-links-box').hide();
            $j('#universalLinksButton').click(function () {
                $j('#universal-links-box').slideToggle();
                return false;
            });
        }, // end universalLinks()

        trackerSetUp: function () {
            var siteRoot = $j('#contact-button').attr('data-root');
            var ghOmniTrackerUrl = '/sitecore/__/_handlers/GHOmnitureHandler.ashx?GetOmniture=1&product=' + gh.globals.productTracker + '&agegroup=' + gh.globals.agegroupTracker + '&globalcontent=' + gh.globals.globalcontent + '&siterootId=' + siteRoot;
            var trackerHttp = gh.generic.GetXmlHttpObject();
            gh.generic.tracker(trackerHttp, ghOmniTrackerUrl, null);
        },

        contactTrackerSetUp: function () {
            var siteRoot = $j('#contact-button').attr('data-root');
            var ghOmniTrackerUrl = '/sitecore/__/_handlers/ContactOverlayHandler.ashx?GetOmniture=1&globalcontent=' + gh.globals.globalcontent + '&siterootId=' + siteRoot + "&fireevent=" + gh.globals.fireEvent;
            var trackerHttp = gh.generic.GetXmlHttpObject();
            gh.generic.tracker(trackerHttp, ghOmniTrackerUrl, null);
        },

        exitLinkTrackerSetUp: function (exitLinkUrl) {
            var exitLinkOmniTrackerUrl = '/sitecore/__/_handlers/ExitLinkOmnitureHandler.ashx?GetOmniture=1&exitlink=' + exitLinkUrl;
            var exitLinktrackerHttp = gh.generic.GetXmlHttpObject();
            gh.generic.tracker(exitLinktrackerHttp, exitLinkOmniTrackerUrl, exitLinkUrl);
        },

        tracker: function (httpRequest, url, redirectUrl) {
            if (httpRequest === null) {
                alert('Your browser does not support XMLHTTP!');
                return;
            }
            httpRequest.onreadystatechange = function () {
                if (httpRequest.readyState === 4) {
                    if (httpRequest.status === 200) {
                        if ($j('#gh-omnidiv').length === 1) {
                            $j('#gh-omnidiv').html(httpRequest.responseText);
                        } else {
                            $j('#global-container').append('<div id="gh-omnidiv">' + httpRequest.responseText + '</div>');
                        }
                        if (redirectUrl !== null) {
                            window.location = redirectUrl;
                        }
                        gh.globals.fireEvent = 'false';
                    } else if (httpRequest.status === 404) {
                        // 404 error
                    }
                }
            };
            httpRequest.open("GET", url, true);
            httpRequest.send();
        },

        setCookie: function (name, value, days) {
            var expires = null;
            if (days) {
                var date = new Date();
                date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
                expires = "; expires=" + date.toGMTString();
            } else {
                expires = "";
            }
            document.cookie = name + "=" + value + expires + "; path=/";
        },

        getCookie: function (name) {
            var nameEQ = name + "=";
            var ca = document.cookie.split(';');
            var i = 0;
            for (i = 0; i < ca.length; i++) {
                var c = ca[i];
                while (c.charAt(0) === ' ') {
                    c = c.substring(1, c.length);
                }
                if (c.indexOf(nameEQ) === 0) {
                    return c.substring(nameEQ.length, c.length);
                }
            }
            return null;
        },

        deleteCookie: function (name) {
            gh.generic.setCookie(name, "", -1);
        }

    };


    gh.funnelling = {
        initalize: function () {
            
            /*
            gh.globals.ageGroupSet = gh.generic.getCookie('ageGroupEF');
            gh.globals.mktSet = gh.generic.getCookie('mktEF');
            */

            if (pageNameVar === 'smallmarkets') {
                $j('#global-content').hide();
                $j('#programs-container').show();
            }

            $j("#all-programs-button a").live('click', function (event) {
                if (gh.globals.ageGroupSet !== null && pageNameVar !== 'smallmarkets' && marketcode === gh.globals.mktSet) {
                    gh.funnelling.slideToggleGlobalContent($j('#all-programs-button a'), '#age-group-options', null, true);
                } else {
                    if (gh.globals.contactContent === true) {
                        gh.generic.switchContent();
                    }
                    if (pageNameVar === 'smallmarkets') {
                        if ($j(this).parent().hasClass('current')) {
                            gh.generic.globalMask(0);
                            gh.globals.globalHeaderOpenClose = false;
                            gh.globals.funnelContent = false;
                        } else {
                            gh.generic.globalMask(1);
                            gh.globals.globalHeaderOpenClose = true;
                            gh.globals.funnelContent = true;
                        }
                        $j(this).parent().toggleClass('current');
                        $j('#global-content').slideToggle(700);
                        $j('#age-group-options').addClass('flat-market');
                        $j('#programs-container').addClass('flat-market-lists');
                        if (gh.globals.programsAjaxInitiated === 0) {
                            var url = '/fp/gheader/age-groups/';
                            var smallGroupHttp = gh.generic.GetXmlHttpObject();
                            gh.funnelling.animateAJAXContent(event, smallGroupHttp, url, '#programs-container', '#programs-container', null);
                        }
                    } else {
                        gh.funnelling.slideToggleGlobalContent($j(this), '#age-group-options', event, false);
                    }
                    if (gh.globals.globalHeaderOpenClose === true) {
                        gh.globals.globalcontent = 'funnel';
                        gh.globals.agegroupTracker = 'unknown';
                        gh.globals.productTracker = 'unknown';
                        gh.globals.trackerEnabled = true;
                    }
                }
                event.stopPropagation();
                return false;
            });

            $j("#error-browse-programs").live('click', function (event) {
                $j('html').animate({
                    scrollTop: $j('#global-container').offset().top
                }, 400, function () {
                    if (gh.globals.contactContent === true) {
                        gh.generic.switchContent();
                    }
                    if (pageNameVar === 'smallmarkets') {
                        if ($j('#all-programs-button a').parent().hasClass('current')) {
                            gh.generic.globalMask(0);
                            gh.globals.globalHeaderOpenClose = false;
                            gh.globals.funnelContent = false;
                        } else {
                            gh.generic.globalMask(1);
                            gh.globals.globalHeaderOpenClose = true;
                            gh.globals.funnelContent = true;
                        }
                        $j('#all-programs-button a').parent().toggleClass('current');
                        $j('#global-content').slideToggle(700);
                        $j('#age-group-options').addClass('flat-market');
                        $j('#programs-container').addClass('flat-market-lists');
                        if (gh.globals.programsAjaxInitiated === 0) {
                            var url = '/fp/gheader/age-groups/';
                            var smallGroupHttp = gh.generic.GetXmlHttpObject();
                            gh.funnelling.animateAJAXContent(event, smallGroupHttp, url, '#programs-container', '#programs-container', null);
                        }
                    } else {
                        gh.funnelling.slideToggleGlobalContent($j('#all-programs-button a'), '#age-group-options', event, false);
                    }
                    if (gh.globals.globalHeaderOpenClose === true) {
                        gh.globals.globalcontent = 'funnel';
                        gh.globals.agegroupTracker = 'unknown';
                        gh.globals.productTracker = 'unknown';
                        gh.globals.trackerEnabled = true;
                        // gh.generic.trackerSetUp();
                    }
                });
                event.stopPropagation();
                return false;
            });

            $j("#age-group-options ul li a").live('click', function (event) {
                gh.funnelling.slideToggleGlobalContent($j(this), '#programs-container', event, false);
                gh.globals.globalcontent = 'funnel';
                gh.globals.agegroupTracker = $j(this).attr('id');
                gh.globals.productTracker = 'unknown';
                gh.globals.trackerEnabled = true;
                /*
                gh.generic.setCookie('ageGroupEF', $j(this).attr('id'), 30);
                gh.generic.setCookie('mktEF', marketcode, 30);
                */
                event.stopPropagation();
                return false;
            });

            $j('#programs-container #program-list ul li a').live('click', function (event) {
                gh.funnelling.chooseProgram($j(this), event);
                gh.globals.globalcontent = 'funnel';
                gh.globals.agegroupTracker = $j(this).closest('div').attr('id');
                gh.globals.productTracker = $j(this).attr('href').substring(1);
                gh.generic.trackerSetUp();
                event.stopPropagation();
                return false;
            });

            $j('#global-mask').click(function (event) {
                gh.generic.closeGlobalHeader();
                event.stopPropagation();
                return false;
            });

            $j('#global-content-container #closeButton').live('click', function (event) {
                gh.generic.closeGlobalHeader();
                event.stopPropagation();
                return false;
            });

            $j('.read-more-ht').live('click', function (event) {
                $j(this).parent().next().fadeIn(400);
                event.stopPropagation();
                return false;
            });

            $j('p.hiddenText a').live('click', function (event) {
                $j(this).parent().fadeOut(400);
                event.stopPropagation();
                return false;
            });

            $j('#global-content ul.buttons li#product-site').live('click', function () {
                var exitLinkHref = $j(this).find('a').attr('href');
                var exitLinkRegEx = /http/i;
                if (exitLinkHref.match(exitLinkRegEx)) {
                    var exitLinkUrl = exitLinkHref.substring(exitLinkHref.indexOf('http'));
                    gh.generic.exitLinkTrackerSetUp(exitLinkUrl);
                } else {
                    return true;
                }
                return false;
            });

            $j('#product-site a').live('hover', function () {
                if ($j(this).hasClass('englishSiteButton')) {
                    var esPath = $j(this).attr('data-es-path');
                    $j('.' + esPath + 'englishSiteText').stop(true, true).fadeToggle();
                }
            });

        }, // end initalize()

        // set up a global function for ajax calls passing various parameter for targets and url
        ajaxCall: function (httpRequest, url, target, programTarget, preload) {
            if (httpRequest === null) {
                alert('Your browser does not support XMLHTTP!');
                return;
            }
            httpRequest.onreadystatechange = function () {
                // animate content once ready, may require a lot of work later
                if (httpRequest.readyState === 4) {
                    if (httpRequest.status === 200) {
                        if (pageNameVar === 'smallmarkets') {
                            $j(target).find('.loading').fadeOut();
                            $j(target).queue(function () {
                                $j(this).html(httpRequest.responseText);
                                $j(this).find('div div:first').fadeIn();
                                $j(this).dequeue();
                            });
                            $j(target).queue(function () {
                                $j(target).find('.programs-landing p').prepend('&lt; ');
                                $j(target).find('.programs-landing').fadeIn();
                                $j(this).dequeue();
                            });
                            var progHelperFunc = gh.generic.helperFunctions();
                            progHelperFunc.destinationLength();
                            progHelperFunc.siteInEnglish();
                        } else {
                            if (target === '#programs-container') {
                                $j(target).queue(function () {
                                    $j(programTarget).find('.loading').fadeOut();

                                    $j(this).find(programTarget).prepend(httpRequest.responseText);
                                    $j(this).find(programTarget).find('div:first').fadeIn();
                                    $j(this).find(programTarget).find('div:first').find('div:first').fadeIn();
                                    if (programTarget === '#program-details') {
                                        var progHelperFunc = gh.generic.helperFunctions();
                                        progHelperFunc.destinationLength();
                                        progHelperFunc.siteInEnglish();
                                    }
                                    $j(this).dequeue();
                                    if (programTarget === '#program-list') {
                                        gh.globals.programListsHttp = null;
                                    }
                                    if (programTarget === '#program-details') {
                                        gh.globals.programDetailsHttp = null;
                                    }
                                });
                            } else {
                                $j(target).find('.loading').fadeOut();
                                $j(target).queue(function () {
                                    $j(this).html('<div class="age-group-content">' + httpRequest.responseText + '</div>');
                                    $j(this).append('<a id="closeButton" href="#">X</a>');
                                    $j(this).find('div').fadeIn();
                                    var ageHelperFunc = gh.generic.helperFunctions();
                                    ageHelperFunc.optionsLastChild('#age-group-options ul li:last-child');
                                    ageHelperFunc.optionsLength('#age-group-options ul li');
                                    ageHelperFunc.optionsHeights('#age-group-options ul li a', 'funnelling');
                                    $j(this).dequeue();
                                });
                                if (preload === true) {
                                    $j('#age-group-options ul li a').each(function () {
                                        var idVal = $j(this).attr('id');
                                        if (idVal === gh.globals.ageGroupSet) {
                                            $j(this).parent().addClass('current');
                                        }
                                    });
                                    $j('#age-group-options p.header2').animate({ 'height': '0', 'opacity': '0' });
                                    $j('#age-group-options a#closeButton').animate({ 'opacity': '0' });
                                    gh.funnelling.slideToggleGlobalContent($j('#all-programs-button a'), '#programs-container', null, true);
                                }
                            }
                        }
                        preload = false;
                        if (gh.globals.trackerEnabled === true) {
                            gh.generic.trackerSetUp();
                            gh.globals.trackerEnabled = false;
                        }
                    } else if (httpRequest.status === 404) {
                        $j(target).queue(function () {
                            $j(this).html('<p class="error404">Error ' + httpRequest.status + ': ' + gh.globals.error404 + '</p>');
                            $j(this).find('div').fadeIn();
                            $j(this).dequeue();
                        });
                    }
                }
            };
            httpRequest.open("GET", url, true);
            httpRequest.send();
        }, // end ajaxCall()

        // what to slide you decide
        // slide global content depending on what variables are set
        slideToggleGlobalContent: function (el, target, event, preload) {
            // if any programs are loaded slide global content to full height
            if (gh.globals.programsAjaxInitiated === 1) {
                if (target === '#programs-container') {
                    gh.funnelling.setUpProgramsContent(el, event, target, preload);
                } else {
                    if (el.parent().hasClass('current')) {
                        gh.generic.globalMask(0);
                        gh.globals.globalHeaderOpenClose = false;
                        gh.globals.funnelContent = false;
                    } else {
                        gh.generic.globalMask(1);
                        gh.globals.globalHeaderOpenClose = true;
                        gh.globals.funnelContent = true;
                    }
                    el.parent().toggleClass('current');
                    $j('#global-content').slideToggle(700);
                }
            } else {
                // if no programs are loaded we will slide what ever the target agegroup if nothing is open, or programs is agegroup is open
                if (preload === true && target === '#age-group-options') {
                    $j('#age-group-options').css({ 'height': '62px' }).addClass('preloaded-age-group');
                    if (el.parent().hasClass('current')) {
                        gh.generic.globalMask(0);
                        gh.globals.globalHeaderOpenClose = false;
                        gh.globals.funnelContent = false;
                    } else {
                        gh.generic.globalMask(1);
                        gh.globals.globalHeaderOpenClose = true;
                        gh.globals.funnelContent = true;
                    }
                    el.parent().toggleClass('current');
                }
                if (preload !== true) {
                    $j(target).slideToggle(400);
                    if (el.parent().hasClass('current')) {
                        gh.generic.globalMask(0);
                        gh.globals.globalHeaderOpenClose = false;
                        gh.globals.funnelContent = false;
                    } else {
                        gh.generic.globalMask(1);
                        gh.globals.globalHeaderOpenClose = true;
                        gh.globals.funnelContent = true;
                    }
                    el.parent().toggleClass('current');
                } else {
                    $j(target).slideToggle(300);
                }

                // if the target is age group (nothing opened yet)
                // we grab the url of the click, create GetXmlHttpObject and call the ajaxCall function using the new GetXmlHttpOject and pass uniqure parameters to it
                if (target === '#age-group-options') {
                    if (gh.globals.ageGroupAjaxInitiated === 0) {
                        var url = '/fp/gheader/age-groups/';
                        if (!gh.globals.ageGroupHttp) {
                            gh.globals.ageGroupHttp = gh.generic.GetXmlHttpObject();
                        } else if (gh.globals.ageGroupHttp.readyState !== 0) {
                            gh.globals.ageGroupHttp.about();
                        }
                        gh.funnelling.animateAJAXContent(event, gh.globals.ageGroupHttp, url, target, null, preload);
                    }
                } else {
                    if (preload !== true) {
                        $j('#age-group-options p.header2').animate({ 'height': '0', 'opacity': '0' });
                        $j('#age-group-options').animate({ 'height': '62px' });
                        $j('#age-group-options a#closeButton').animate({ 'opacity': '0' });
                    }
                    // if our target is programs 
                    // we grab the url of the click, create GetXmlHttpObject and call the ajaxCall function using the new GetXmlHttpOject and pass uniqure parameters to it
                    // For example if we choose HIGH, we will AJAX the high content
                    gh.funnelling.setUpProgramsContent(el, event, target, preload);
                }
            }
        }, // end slideToggleGlobalContent()

        // set up the programs content
        setUpProgramsContent: function (el, event, target, preload) {
            var dataExists = false;
            var idValueOriginal = null;
            var idValueLower = null;
            var url = null;
            if (preload === true) {
                url = gh.globals.ageGroupSet;
            } else {
                url = el.attr('id');
                el.parent().addClass('current').siblings().removeClass('current');
            }
            $j('#programs-container #program-list div').each(function () {
                idValueOriginal = $j(this).attr('id');
                idValueLower = $j(this).attr('id');
                if (idValueLower === url) {
                    dataExists = true;
                    return false;
                }
            });
            if (dataExists === false) {
                if (!gh.globals.programListsHttp) {
                    gh.globals.programListsHttp = gh.generic.GetXmlHttpObject();
                } else if (gh.globals.programListsHttp.readyState !== 0) {
                    gh.globals.programListsHttp.abort();
                }
                if (!gh.globals.programDetailsHttp) {
                    gh.globals.programDetailsHttp = gh.generic.GetXmlHttpObject();
                } else if (gh.globals.programDetailsHttp.readyState !== 0) {
                    gh.globals.programDetailsHttp.abort();
                }
                gh.funnelling.animateAJAXContent(event, gh.globals.programListsHttp, '/fp/gheader/left-navigation/?agegroup=' + url, target, '#program-list', preload);
                gh.funnelling.animateAJAXContent(event, gh.globals.programDetailsHttp, '/fp/gheader/programs/?agegroup=' + url, target, '#program-details', preload);

            } else {
                $j('#programs-container #program-list > div:visible').not('#filter').fadeOut(300, function () {
                    $j('#programs-container #program-list').find('#' + idValueOriginal).fadeIn();
                });
                $j('#programs-container #program-details > div:visible').fadeOut(300, function () {
                    $j('#programs-container #program-details').find('#programs-' + idValueOriginal).fadeIn();
                });
            }
        }, // end setUpProgramsContent()

        // animate before ajaxCall
        animateAJAXContent: function (event, httpRequest, url, target, programTarget, preload) {
            var progressBarWhite = 'http://media.ef.com/Funneling/images/global-header/ajax-loader_white.gif';
            var progressBarBlue = 'http://media.ef.com/Funneling/images/global-header/ajax-loader_blue.gif';
            if (pageNameVar === 'smallmarkets') {
                gh.globals.ageGroupAjaxInitiated = 1;
                gh.globals.programsAjaxInitiated = 1;
                gh.funnelling.ajaxCall(httpRequest, url, target, programTarget, preload);
                $j('#program-list').html("<div class='loading'><img src='" + progressBarBlue + "' /></div>");
                $j('#program-details').html("<div class='loading'><img src='" + progressBarWhite + "' /></div>");
            } else {
                if (target === '#programs-container') {
                    gh.globals.programsAjaxInitiated = 1;
                    if ($j(programTarget).find('> div').is(':visible')) {
                        var fadeoutcontainer = $j(programTarget).find('> div:visible');
                        fadeoutcontainer.fadeOut(function () {
                            $j(programTarget).find('.loading').show();
                            gh.funnelling.ajaxCall(httpRequest, url, target, programTarget);
                        });
                    } else {
                        if (programTarget === '#program-list') {
                            $j(programTarget).prepend("<div class='loading'><img src='" + progressBarBlue + "' /></div>");
                        } else {
                            $j(programTarget).prepend("<div class='loading'><img src='" + progressBarWhite + "' /></div>");
                        }
                        gh.funnelling.ajaxCall(httpRequest, url, target, programTarget, preload);
                    }
                } else {
                    $j(target).html("<div class='loading'><img src='" + progressBarBlue + "' /></div>");
                    gh.globals.ageGroupAjaxInitiated = 1;
                    gh.funnelling.ajaxCall(httpRequest, url, target, programTarget, preload);
                }
            }
        }, // end animateAJAXContent()

        // selecting a program
        chooseProgram: function (el, event) {
            var ageCategoryId = '#' + el.closest('div').attr('id');
            var ageCategoryTarget = '#programs-' + el.closest('div').attr('id');
            var programCode = '#' + el.attr('href').split('#')[1];
            $j('#programs-container #program-list').find(ageCategoryId).find('ul li').each(function () {
                if ($j(this).hasClass('current')) {
                    $j(this).removeClass('current');
                }
            });
            el.parent().addClass('current');
            if ($j('#program-details').find(ageCategoryTarget).find('> div').is(':visible')) {
                $j('#program-details').find(ageCategoryTarget).find('> div:visible').fadeOut(300, function () {
                    $j('#program-details').find(ageCategoryTarget).find(programCode).fadeIn();
                });
            } else {
                $j('#program-details').find(ageCategoryTarget).find(programCode).fadeIn();
            }

        } // end chooseProgram()

    }; // end funnelling{}


    gh.contactUs = {
        initalize: function () {
            $j('#global-links ul li#contact-button a').live('click', function (event) {
                var dataRoot = $j(this).parent().attr('data-root');
                var dataAltLink = $j(this).parent().attr('data-altlink');
                if (dataAltLink === 'true') {
                    if (gh.globals.funnelContent === true) {
                        gh.generic.switchContent();
                    }
                    gh.contactUs.slideToggleContactInfo($j(this), dataRoot);
                    event.stopPropagation();
                    if (gh.globals.globalHeaderOpenClose === true) {
                        gh.globals.globalcontent = 'contact';
                        gh.globals.agegroupTracker = 'unknown';
                        gh.globals.productTracker = 'unknown';
                        gh.generic.contactTrackerSetUp();
                    }
                    return false;
                } else {
                    return true;
                }
            });

            $j('#global-content-container #contact-us-options ul li a').live('click', function (event) {
                gh.contactUs.animateContactContent($j(this), '#global-content-container');
                event.stopPropagation();
                return false;
            });

            $j('#global-content-container #agent-options p').live('click', function (event) {
                gh.contactUs.showAgentsList($j(this));
                event.stopPropagation();
                return false;
            });

            $j('#global-content-container #agent-options ul li a').live('click', function (event) {
                gh.contactUs.selectAgent($j(this), '#global-content-container', '#agent-options', '#agent-data');
                event.stopPropagation();
                return false;
            });

            $j('#global-content-container #contact-details-container #contact-info .info-header').live('click', function (event) {
                gh.contactUs.infoPanelSwitch($j(this));
                event.stopPropagation();
                return false;
            });

        }, // End initalize()


        slideShow: function (targetID) {
            var targetSlideShowCont = targetID.find('.map-container .office-slideshow');
            var imageCount = targetSlideShowCont.find('.slide-images li').length;
            targetSlideShowCont.find('.slide-images li').not(':first').hide();
            targetSlideShowCont.find('.slide-next-prev .image-count .image-count-current').html('1');
            targetSlideShowCont.find('.slide-next-prev .image-count .image-count-length').html('/' + imageCount);
            if (imageCount === 1) {
                targetSlideShowCont.find('.slide-next-prev .prev').hide();
                targetSlideShowCont.find('.slide-next-prev .next').hide();
            } else {
                targetSlideShowCont.find('.slide-next-prev a').click(function (event) {
                    gh.contactUs.animateSlideShow($j(this), targetSlideShowCont, imageCount);
                    return false;
                });
            }
            targetSlideShowCont.find('.office-close a').click(function (event) {
                targetSlideShowCont.hide();
                return false;
            });

        },

        animateSlideShow: function (el, targetSlideShowCont, imageCount) {
            var type = el.parent().attr('class');
            var index = targetSlideShowCont.find('.image-container ul.slide-images li.active').index();
            imageCount = imageCount - 1;
            var targetIndex = 0;
            if (type === 'next') {
                if (index === imageCount) {
                    targetIndex = 0;
                } else {
                    targetIndex = index + 1;
                }
                targetSlideShowCont.find('.slide-next-prev .image-count .image-count-current').html(targetIndex + 1);
            } else if (type === 'prev') {
                if (index === 0) {
                    targetIndex = imageCount;
                } else {
                    targetIndex = index - 1;
                }
                targetSlideShowCont.find('.slide-next-prev .image-count .image-count-current').html(targetIndex + 1);
            }
            targetSlideShowCont.find('.image-container ul.slide-images li.active').removeClass('active').fadeOut(function () {
                var targetObject = targetSlideShowCont.find('.image-container ul.slide-images li').eq(targetIndex);
                targetObject.fadeIn().addClass('active');
            });
        }, // End animateSlideShow();


        infoPanelSwitch: function (el) {
            if (gh.globals.googleMapsScript === false) {
                gh.loadScripts.loadPlugins();
            }
            if (!el.hasClass('current')) {
                el.siblings('p').removeClass('current');
                el.addClass('current');
                el.siblings('div').slideToggle(function () {
                    if ($j(this).hasClass('map-container')) {
                        if (!$j(this).hasClass('map-activated')) {
                            var targetID = $j(this).parent();
                            var dataLat = $j(this).attr('data-lat');
                            var dataLng = $j(this).attr('data-lng');
                            var directions = $j(this).attr('data-directions');
                            var streetview = $j(this).attr('data-streetview');
                            var dataOptions = '<ul class="gmap-options clearfix"><li><a href="#" class="directions">' + directions + '</a></li><li><a href="#" class="streetview">' + streetview + '</a></li><li><a href="#" class="office">Office</a></li></ul>';
                            var dataInfo1 = '<h3>' + $j(this).parent().find('div.contact-info-container p.header3').html() + '</h3>';
                            var dataInfo2 = '<p>' + $j(this).parent().find('div.contact-info-container p.contact-address').html() + '</p>';
                            var dataInfo3 = '<p>' + $j(this).parent().find('div.contact-info-container p.contact-tel').html() + '</p>';
                            var dataInfo = '<div class="gmap-info-window">' + dataOptions + dataInfo1 + '</div>';
                            gh.googlemaps.setMap(targetID, dataLat, dataLng, dataInfo);
                            gh.contactUs.slideShow(targetID);
                            $j(this).addClass('map-activated');
                        }
                    }
                });
            }
        },

        showAgentsList: function (el) {
            el.next().fadeToggle(200);
        }, // End showAgentsList()

        selectAgent: function (el, container, options, data) {
            var agentName = el.text();
            var agentPos = el.parent().index();
            options = ' ' + options;
            data = ' ' + data;
            $j(container + options + ' p').text(agentName);
            $j(container + options + ' ul').fadeToggle(200);
            $j(container + data + ' > div:visible').fadeOut(200, function () {
                $j(container + data + ' > div').eq(agentPos).fadeIn(400);
            });
        }, // End selectAgent()

        animateContactContent: function (el, container) {
            var target = '#' + el.attr('id') + '-info';
            $j(container + ' #contact-us-options ul li').removeClass('current');
            $j(el).parent().addClass('current');
            $j(container + ' #contact-info > div:visible').fadeOut(function () {
                $j(target).fadeIn(function () {
                    if (container === '#product-contact-us') {
                        gh.productContactUs.loadMap(el);
                    }
                });
            });
        }, // End animateContactContent()

        slideToggleContactInfo: function (el, dataRoot) {
            $j('#global-content-container #global-contact-us').slideToggle(700);
            gh.globals.contactContent = true;
            if (el.parent().hasClass('current')) {
                gh.generic.globalMask(0);
                gh.globals.globalHeaderOpenClose = false;
                gh.globals.contactContent = false;
            } else {
                gh.generic.globalMask(1);
                gh.globals.globalHeaderOpenClose = true;
                gh.globals.contactContent = true;
            }
            el.parent().toggleClass('current');
            if (gh.globals.contactAjaxInitiated === 0) {
                var url = '/fp/gheader/contact/?rootID=' + dataRoot;
                var contactHttp = gh.generic.GetXmlHttpObject();
                var target = '#global-content-container #global-contact-us';
                gh.contactUs.animateAJAXContent(contactHttp, url, target);
            }
        }, // End slideToggleContactInfo()


        // animate before ajaxCall
        animateAJAXContent: function (httpRequest, url, target) {
            var progressBarBlue = 'http://media.ef.com/Funneling/images/global-header/ajax-loader_blue.gif';
            $j(target).html("<div class='loading'><img src='" + progressBarBlue + "' /></div>");
            gh.globals.contactAjaxInitiated = 1;
            gh.contactUs.ajaxCall(httpRequest, url, target);
        }, // end animateAJAXContent()

        // set up a global function for ajax calls passing various parameter for targets and url
        ajaxCall: function (httpRequest, url, target) {
            if (httpRequest === null) {
                alert('Your browser does not support XMLHTTP!');
                return;
            }
            httpRequest.onreadystatechange = function () {
                // animate content once ready, may require a lot of work later
                if (httpRequest.readyState === 4) {
                    if (httpRequest.status === 200) {
                        if (target === '#global-content-container #global-contact-us') {
                            $j(target).find('.loading').fadeOut();
                            $j(target).queue(function () {
                                $j(this).html(httpRequest.responseText);
                                $j(this).find('> div').fadeIn();
                                var contactOptionsHelperFunc = gh.generic.helperFunctions();
                                contactOptionsHelperFunc.optionsLastChild('#global-content-container #contact-us-options ul li:last-child');
                                contactOptionsHelperFunc.optionsLength('#global-content-container #contact-us-options ul li');
                                contactOptionsHelperFunc.optionsHeights('#global-content-container #contact-us-options ul li a', 'contact-us');
                                $j(this).find('#contact-info > div').not(':first').hide();
                                $j(this).find('#contact-us-options ul li:first').addClass('current');
                                $j(this).find('#agent-data > div').not(':first').hide();

                                if ($j('html').hasClass('ie6')) {
                                    $j(this).find('#contact-info div.map-container').hide().prev().hide();
                                }

                                var contactFormUrl = '/fp/gheader/contact-form/';
                                // var contactFormUrl = '/Funneling/sublayouts/globalheader/contact-panel.html';
                                var contactFormHttp = gh.generic.GetXmlHttpObject();
                                var contactFormTarget = '#global-content-container #global-contact-us #contact-form';
                                gh.contactUs.animateAJAXContent(contactFormHttp, contactFormUrl, contactFormTarget);
                                $j(this).dequeue();
                            });
                        } else {
                            $j(target).find('.loading').fadeOut();
                            $j(target).queue(function () {
                                $j(this).html(httpRequest.responseText);
                                $j(this).find('> div').fadeIn();
                                $j(this).dequeue();
                            });
                        }
                    } else if (httpRequest.status === 404) {
                        $j(target).queue(function () {
                            $j(this).html('<p class="error404">Error ' + httpRequest.status + ': ' + gh.globals.error404 + '</p>');
                            $j(this).find('div').fadeIn();
                            $j(this).dequeue();
                        });
                    }
                }
            };
            httpRequest.open("GET", url, true);
            httpRequest.send();
        } // end ajaxCall()

    }; // end contactUs{}



    gh.productHeader = {
        initalize: function () {
            gh.globals.productNameLine1 = $j("#product-name-line1");
            gh.globals.productNameLine2 = $j("#product-name-line2");
            if (splitType === "char") {
                //Remember check for Asian characters and arabic when splitting via number of chars
                gh.productHeader.splitTextByChar();
            }
            if (splitType === "word") {
                gh.productHeader.splitTextByWord();
            }
        },

        splitTextByChar: function () {
            if (gh.globals.productNameLine1.text().length > splitCount) {
                //Split Text at the character requested
                var line1 = gh.globals.productNameLine1.text().slice(0, splitCount);
                var line2 = gh.globals.productNameLine1.text().slice(splitCount);
                gh.globals.productNameLine1.text(line1);
                gh.globals.productNameLine2.text(line2);
            }
        },

        splitTextByWord: function () {
            var line1 = "";
            var line2 = "";
            var i = 0;
            //Get all the words in an array
            var wordsArray = gh.globals.productNameLine1.text().split(" ");
            //check if number of words is not the same as the number of words to split by 
            if (splitCount < wordsArray.length) {
                for (i = 0; i < wordsArray.length; i++) {
                    if (i < splitCount) {
                        line1 += wordsArray[i] + " ";
                    }
                    if (i >= splitCount) {
                        line2 += wordsArray[i] + " ";
                    }
                }
            }
            gh.globals.productNameLine1.text(line1); //Put number of words in line 1
            gh.globals.productNameLine2.text(line2); //Put remaining words in line 2
        }
    };

    gh.nonproductHeader = {
        initalize: function (characterLimit) {
            var textLength = $j("#site-name").text().length;
            if (textLength > characterLimit) {
                $j("#site-name").addClass("multilineSiteName");
            }
        }
    };


    gh.loadScripts = {
        loadPlugins: function () {
            if (!$j('html').hasClass('ie6')) {
                var script1 = document.createElement("script");
                script1.src = "http://media.ef.com/Funneling/scripts/infobubble.js";
                script1.type = "text/javascript";
                document.getElementsByTagName("head")[0].appendChild(script1);
            } else {
                gh.loadScripts.loadmap();
            }
        },

        loadGoogleMapsScripts: function () {
            var script = document.createElement("script");
            script.src = "http://maps.googleapis.com/maps/api/js?sensor=true&callback=gh.loadScripts.loadmap";
            script.type = "text/javascript";
            document.getElementsByTagName("head")[0].appendChild(script);
            gh.globals.googleMapsScript = true;
        },

        loadmap: function () {
            if ($j('#product-contact-us').length === 1) {
                gh.productContactUs.initalize();
            }
        }
    };



    gh.googlemaps = {
        setMap: function (targetID, dataLat, dataLng, dataInfo) {
            var mapContainer = targetID.find('div.map-wrapper > div').attr('id');
            if (!$j('html').hasClass('ie6')) {
                var directionsDisplay = new google.maps.DirectionsRenderer();
                var directionsService = new google.maps.DirectionsService();
                latlng = new google.maps.LatLng(dataLat, dataLng);
                var myOptions = {
                    zoom: 17,
                    center: latlng,
                    streetViewControl: true,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };
                var map = new google.maps.Map(document.getElementById(mapContainer), myOptions);
                map.panBy(50, -50);
                directionsDisplay.setMap(map);
                directionsDisplay.setPanel(document.getElementById("mapDirPanelText"));
                var image = new google.maps.MarkerImage('/sitecore/__/_images/ef_googlemap_icon.png',
                    new google.maps.Size(35, 43),
                    new google.maps.Point(0, 0),
                    new google.maps.Point(18, 41));
                if (gh.globals.infoBubble === true) {
                    var infowindow = new InfoBubble({
                        content: dataInfo,
                        shadowStyle: 1,
                        padding: 20,
                        backgroundColor: 'rgb(255,255,255)',
                        borderRadius: 0,
                        arrowSize: 15,
                        borderWidth: 1,
                        borderColor: '#d4d4d4',
                        disableAutoPan: true,
                        hideCloseButton: false,
                        arrowPosition: 2,
                        backgroundClassName: 'infowindow',
                        arrowStyle: 2,
                        minWidth: 250,
                        minHeight: 60,
                        maxWidth: 250,
                        maxHeight: 60
                    });
                } else {
                    var infowindow = new google.maps.InfoWindow({
                        content: dataInfo
                    });
                }
                if (targetID.attr('id') === 'agent-product-info') {
                    var agentCount = 0;
                    targetID.find('#agent-data div').each(function () {
                        var aLat = $j(this).attr('data-lat');
                        var aLng = $j(this).attr('data-lng');
                        var aDirections = $j(this).attr('data-directions');
                        var aStreetview = $j(this).attr('data-streetview');
                        var aIndex = $j(this).index();
                        var aDataOptions = '<ul class="gmap-options clearfix"><li><a href="#" class="directions">' + aDirections + '</a></li><li><a href="#" class="streetview">' + aStreetview + '</a></li></ul>';
                        var aDataInfo1 = '<h3>' + $j(this).parent().prev().find('ul li').eq(aIndex).html() + '</h3>';
                        var aDataInfo2 = '<p>' + $j(this).html() + '</p>';
                        var aDataInfo = '<div class="gmap-info-window pos' + aIndex + '">' + aDataOptions + aDataInfo1 + '</div>';
                        var aLatlng = new google.maps.LatLng(aLat, aLng);
                        var marker = new google.maps.Marker({
                            position: aLatlng,
                            map: map,
                            icon: image
                        });
                        if (agentCount === 0) {
                            infowindow.open(map, marker);
                        }
                        google.maps.event.addListener(marker, 'click', function () {
                            infowindow.close();
                            infowindow.setContent(aDataInfo);
                            infowindow.open(map, marker);
                            latlng = new google.maps.LatLng(aLat, aLng);
                            var infowindowPos = infowindow.content.substring(32, 34).replace(/"/, '');
                            var agentName = $j('#contact-details-container #contact-info #agent-product-info #agent-options ul li').eq(infowindowPos).find('a').text();
                            var agentPos = infowindowPos;
                            $j('#contact-details-container #contact-info #agent-product-info #agent-options p').text(agentName);
                            $j('#product-contact-us #agent-data > div:visible').fadeOut(200, function () {
                                $j('#product-contact-us #agent-data > div').eq(agentPos).fadeIn(400);
                            });
                        });
                        $j('#agent-options ul li').eq(aIndex).find('a').click(function () {
                            infowindow.close();
                            infowindow.setContent(aDataInfo);
                            infowindow.open(map, marker);
                            latlng = new google.maps.LatLng(aLat, aLng);
                            map.panTo(latlng);
                            map.panBy(50, -50);
                        });
                        $j('#' + mapContainer + ' .gmap-info-window.pos' + aIndex + ' .streetview').live('click', function () {
                            panorama = map.getStreetView();
                            panorama.setPosition(aLatlng);
                            panorama.setPov({
                                heading: 265,
                                zoom: 1,
                                pitch: 0
                            });
                            var toggle = panorama.getVisible();
                            if (toggle === false) {
                                panorama.setVisible(true);
                            } else {
                                panorama.setVisible(false);
                            }
                            return false;
                        });
                        agentCount++;
                    });
                } else {
                    var marker = new google.maps.Marker({
                        position: latlng,
                        map: map,
                        icon: image
                    });
                    if (gh.globals.infoBubble === true) {
                        var infowindow = new InfoBubble({
                            content: dataInfo,
                            shadowStyle: 1,
                            padding: 20,
                            backgroundColor: 'rgb(255,255,255)',
                            borderRadius: 0,
                            arrowSize: 15,
                            borderWidth: 1,
                            borderColor: '#d4d4d4',
                            disableAutoPan: true,
                            hideCloseButton: false,
                            arrowPosition: 2,
                            backgroundClassName: 'infowindow',
                            arrowStyle: 2,
                            minWidth: 250,
                            minHeight: 60,
                            maxWidth: 250,
                            maxHeight: 60
                        });
                    } else {
                        var infowindow = new google.maps.InfoWindow({
                            content: dataInfo
                        });
                    }
                    infowindow.open(map, marker);
                    google.maps.event.addListener(marker, 'click', function () {
                        infowindow.open(map, marker);
                    });
                    $j('#' + mapContainer + ' .gmap-info-window .streetview').live('click', function () {
                        panorama = map.getStreetView();
                        panorama.setPosition(latlng);
                        panorama.setPov({
                            heading: 265,
                            zoom: 1,
                            pitch: 0
                        });
                        var toggle = panorama.getVisible();
                        if (toggle === false) {
                            panorama.setVisible(true);
                        } else {
                            panorama.setVisible(false);
                        }
                        return false;
                    });
                    $j('#' + mapContainer + ' .gmap-info-window .office').live('click', function () {
                        $j('#' + mapContainer).parent().next().show();
                        return false;
                    });
                }
                $j('#' + mapContainer + ' .gmap-info-window .directions').live('click', function () {
                    gh.googlemaps.showHideDirs(targetID);
                    return false;
                });
                var openCloseDirectionButton = targetID.find('#mapDirPanelCls');
                openCloseDirectionButton.click(function () {
                    gh.googlemaps.showHideDirs(targetID);
                    return false;
                });
                var getDirectionInput = targetID.find('#mapDirPanelEntry input#get-directions-button');
                getDirectionInput.click(function () {
                    gh.googlemaps.getDirections($j(this), marker.position, directionsService, directionsDisplay, targetID, map);
                    return false;
                });
            } else {
                $j('#' + mapContainer).html("<img src='http://media.ef.com/sitecore/__~/media/efcom/funneling/contact/worldwide-banner.jpg' />");
            }
        }, // End setMap()

        showHideDirs: function (targetID) {
            var elmnt = targetID.find('.map-dir-panel');
            var openCloseButton = elmnt.find('#mapDirPanelCls');
            if (elmnt.css("left") === "0px") {
                elmnt.animate({ "left": "-=220px" }, "fast");
                openCloseButton.addClass("panelHidden");
            } else {
                elmnt.animate({ "left": "+=220px" }, "slow");
                openCloseButton.removeClass("panelHidden");
            }
        },

        getDirections: function (el, latlng_current, directionsService, directionsDisplay, targetID, map) {
            var gOrigin = el.parent().find('#dirOrigin').attr('value').replace(/(\r\n|[\r\n])/g, ',');
            var request = {
                origin: gOrigin,
                destination: latlng_current,
                travelMode: gh.googlemaps.qualifyTravelMode(el)
            };
            directionsService.route(request, function (response, status) {
                if (status === google.maps.DirectionsStatus.OK) {
                    var divTarget = targetID.find('.mapDirPanelText').attr('id');
                    directionsDisplay.setMap(map);
                    directionsDisplay.setPanel(document.getElementById(divTarget));
                    directionsDisplay.setDirections(response);
                }
            });
        },

        qualifyTravelMode: function (el) {
            var travelMode = el.parent().find('#travelMode');
            switch (travelMode.find('option:selected').attr('value')) {
                case "Bicycling":
                    return google.maps.DirectionsTravelMode.BICYCLING;
                case "Driving":
                    return google.maps.DirectionsTravelMode.DRIVING;
                case "Walking":
                    return google.maps.DirectionsTravelMode.WALKING;
            }
        }

    }; // End gh.googlemaps()


    gh.productContactUs = {
        initalize: function () {

            var contactOptionsHelperFunc = gh.generic.helperFunctions();
            contactOptionsHelperFunc.optionsLastChild('#product-contact-us  #contact-us-options ul li:last-child');
            contactOptionsHelperFunc.optionsLength('#product-contact-us  #contact-us-options ul li');
            contactOptionsHelperFunc.optionsHeights('#product-contact-us  #contact-us-options ul li a', 'contact-us');

            $j('#product-contact-us #global-contact-us #agent-data > div').not(':first').hide();


            /*
            $j('#product-contact-us ul li').each(function () {
            var el = $j(this).find('a');
            var text = el.html().replace('St. ', '').replace(/ /gi, '').toLowerCase();
            el.attr('class', text);
            });




            // check url for a office, if it matches a office on the page then load correct office
            var locationUrl = document.location;
            console.log(locationUrl);
           
            var loadDefault = true;
            $j('#product-contact-us ul li').each(function () {
            var elIndex = $j(this).index();
            var elClass = $j(this).find('a').attr('class');
            if (elClass === locationUrl) {
            $j('#product-contact-us #global-contact-us #contact-info > div').hide();
            $j('#product-contact-us #global-contact-us #contact-info > div').eq(elIndex).show();
            $j('#product-contact-us #global-contact-us #contact-us-options ul li').removeClass('current').eq(elIndex).addClass('current');
            $j('#product-contact-us #global-contact-us #contact-info > div').eq(elIndex).show(function () {
            $j(this).find('div.map-container').show(function () {
            gh.productContactUs.loadMapFunction($j(this));
            });
            });
            loadDefault = false;
            return false;
            } else {
            loadDefault = true;
            }
            });

            // If no specific office url entered then default to first office
            if (loadDefault === true) {
            */
            $j('#product-contact-us #global-contact-us #contact-info > div').not(':first').hide();
            $j('#product-contact-us #global-contact-us #contact-us-options ul li:first').addClass('current');
            $j('#product-contact-us #contact-info div:first div.map-container').show(function () {
                gh.productContactUs.loadMapFunction($j(this));
            });
            /*
            }
            */


            $j('#product-contact-us #contact-us-options ul li a').live('click', function (event) {
                gh.contactUs.animateContactContent($j(this), '#product-contact-us');
                event.stopPropagation();
                return false;
            });

            $j('#product-contact-us #agent-options p').live('click', function (event) {
                gh.contactUs.showAgentsList($j(this));
                event.stopPropagation();
                return false;
            });

            $j('#product-contact-us  #agent-options ul li a').live('click', function (event) {
                gh.contactUs.selectAgent($j(this), '#product-contact-us', '#agent-options', '#agent-data');
                event.stopPropagation();
                return false;
            });

        }, // End initalize()

        loadMap: function (el) {
            var targetID = $j('#' + el.attr('id') + '-info');
            var mapContainer = targetID.find('.map-container');
            if (!mapContainer.hasClass('map-activated')) {
                gh.productContactUs.loadMapFunction(mapContainer);
            }
        },

        loadMapFunction: function (el) {
            var targetID = el.parent();
            var dataLat, dataLng, directions, streetview, dataOptions, dataInfo1, dataInfo2, dataInfo3, dataInfo;
            if (targetID.attr('id') === 'agent-product-info') {
                dataLat = targetID.find('#agent-data > div:first').attr('data-lat');
                dataLng = targetID.find('#agent-data > div:first').attr('data-lng');
                directions = targetID.find('#agent-data > div:first').attr('data-directions');
                streetview = targetID.find('#agent-data > div:first').attr('data-streetview');
                dataOptions = '<ul class="gmap-options clearfix"><li><a href="#" class="directions">' + directions + '</a></li><li><a href="#" class="streetview">' + streetview + '</a></li></ul>';
                dataInfo1 = '<h3>' + targetID.find('#agent-options ul li:first').html() + '</h3>';
                dataInfo2 = '<p>' + targetID.find('#agent-data > div:first').html() + '</p>';
                dataInfo = '<div class="gmap-info-window">' + dataOptions + dataInfo1 + '</div>';
            } else {
                dataLat = el.attr('data-lat');
                dataLng = el.attr('data-lng');
                directions = el.attr('data-directions');
                streetview = el.attr('data-streetview');
                dataOptions = '<ul class="gmap-options clearfix"><li><a href="#" class="directions">' + directions + '</a></li><li><a href="#" class="streetview">' + streetview + '</a></li></ul>';
                dataInfo1 = '<h3>' + el.parent().find('div.contact-info-container p.header3').html() + '</h3>';
                dataInfo2 = '<p>' + el.parent().find('div.contact-info-container p.contact-address').html() + '</p>';
                dataInfo3 = '<p>' + el.parent().find('div.contact-info-container p.contact-tel').html() + '</p>';
                dataInfo = '<div class="gmap-info-window">' + dataOptions + dataInfo1 + '</div>';
            }
            gh.googlemaps.setMap(targetID, dataLat, dataLng, dataInfo);
            el.addClass('map-activated');
        }
    }; // end productContactUs{}


    gh.lightbox = {
        initalize: function () {
            $j('.office-images li a').click(function (event) {
                gh.lightbox.overlay($j(this));
                return false;
            });

            $j('#global-mask').click(function (event) {
                $j('#ef-lightbox-overlay').animate({ 'opacity': '0' }).css({ 'z-index': '-1' });
                $j('#global-mask').css({ 'z-index': '9998' });
                $j('#ef-lightbox-overlay .img-container ul.new-data').empty().css({ 'visibility': 'hidden' });
            });

            $j('#ef-lightbox-overlay .img-container ul.new-data li a').live('click', function () {
                return false;
            });

            $j('#ef-lightbox-overlay ul.next-prev li a').live('click', function (event) {
                gh.lightbox.animateSlideShow($j(this));
                return false;
            });

            $j('#ef-lightbox-overlay p.close-lightbox a').live('click', function (event) {
                gh.generic.closeGlobalHeader();
                $j('#ef-lightbox-overlay').animate({ 'opacity': '0' }).css({ 'z-index': '-1' });
                $j('#global-mask').css({ 'z-index': '9998' });
                $j('#ef-lightbox-overlay .img-container ul.new-data').empty().css({ 'visibility': 'hidden' });
                event.stopPropagation();
                return false;
            });

            $j('#ef-lightbox-overlay').live('click', function (event) {
                gh.generic.closeGlobalHeader();
                $j('#ef-lightbox-overlay').animate({ 'opacity': '0' }).css({ 'z-index': '-1' });
                $j('#global-mask').css({ 'z-index': '9998' });
                $j('#ef-lightbox-overlay .img-container ul.new-data').empty().css({ 'visibility': 'hidden' });
                event.stopPropagation();
                return false;
            });
        }, // End initalize();


        overlay: function (el) {
            var index = el.parent().index();
            var htmlData = el.parent().parent().html();
            if ($j('#ef-lightbox-overlay').length !== 1) {
                $j("#wrapper").append('<div id="ef-lightbox-overlay"><div class="img-container"><ul class="new-data"></ul><p class="close-lightbox"><a href="#">X</a></p><ul class="next-prev"><li class="prev"><a href="#">Prev</a></li><li class="next"><a href="#">Next</a></li></ul></div> </div>');
            } else {
                $j('#ef-lightbox-overlay').animate({ 'opacity': '1' }).css({ 'z-index': '10000' });
            }
            $j('#ef-lightbox-overlay .img-container ul.new-data').html(htmlData);

            if ($j('#ef-lightbox-overlay .img-container ul.new-data li a div').hasClass('imageBorder')) {
                $j('#ef-lightbox-overlay .img-container ul.new-data li a div').removeClass('imageBorder curved');
            }
            var image = $j('#ef-lightbox-overlay .img-container ul.new-data li').eq(index).find('img');
            var imageWidth = image.width();
            var imageHeight = image.height();
            if (imageWidth === 0) {
                imageWidth = 912;
                imageHeight = 608;
            }
            $j('#ef-lightbox-overlay .img-container').animate({
                height: imageHeight,
                width: imageWidth
            }, function () {
                $j('#ef-lightbox-overlay .img-container ul.new-data').css({ 'visibility': 'visible' });
                $j('#ef-lightbox-overlay .img-container ul.new-data li').hide();
                $j('#ef-lightbox-overlay .img-container ul.new-data li').eq(index).fadeIn().addClass('active');
            });
            $j('#ef-lightbox-overlay ul.next-prev').animate({
                width: imageWidth + 20
            }, function () {
                $j('#ef-lightbox-overlay ul.next-prev').css({ 'visibility': 'visible' });
            });
            gh.generic.globalMask(1);
            gh.globals.globalHeaderOpenClose = true;
            $j('#global-mask').css({ 'z-index': '9999' });
        }, // End overlay();


        animateSlideShow: function (el) {
            var type = el.parent().attr('class');
            var index = $j('#ef-lightbox-overlay .img-container ul.new-data li.active').index();
            var length = $j('#ef-lightbox-overlay .img-container ul.new-data li').length - 1;
            var targetIndex = 0;
            if (type === 'next') {
                if (index === length) {
                    targetIndex = 0;
                } else {
                    targetIndex = index + 1;
                }
            } else if (type === 'prev') {
                if (index === 0) {
                    targetIndex = length;
                } else {
                    targetIndex = index - 1;
                }
            }
            $j('#ef-lightbox-overlay .img-container ul.new-data li.active').removeClass('active').fadeOut(function () {
                var targetObject = $j('#ef-lightbox-overlay .img-container ul.new-data li').eq(targetIndex);
                targetObject.show().css({ 'visibility': 'hidden' });
                var image = targetObject.find('img');
                var imageWidth = image.width();
                var imageHeight = image.height();
                $j('#ef-lightbox-overlay .img-container').animate({
                    height: imageHeight,
                    width: imageWidth
                }, function () {
                    targetObject.hide().css({ 'visibility': 'visible' });
                    targetObject.fadeIn().addClass('active');
                });
                $j('#ef-lightbox-overlay ul.next-prev').animate({
                    width: imageWidth + 20
                });
            });

        } // End animateSlideShow();

    }; // End lightbox{};



    gh.contactFormData = {
        FirstName: '',
        LastName: '',
        HomePhone: '',
        MobilePhone: '',
        Email: '',
        CountryCode: '',
        Comments: '',
        State: '',
        PostalCode: '',
        NickNameFirst: '',
        NickNameLast: '',
        MobileEmail: ''
    };

    gh.validateErrors = {
        information: false
    };

    gh.contactFormValidation = {
        initalize: function () {
            $j('#contact-form .buttonLink input').live('click', function (event) {
                var parentID = $j(this).closest('#global-contact-us').parent().attr('id');
                gh.contactFormValidation.collectFormData($j(this), parentID);
                return false;
            });
        },

        collectFormData: function (el, parentID) {
            for (field in gh.contactFormData) {
                gh.contactFormData[field] = gh.contactFormValidation.checkFormFieldsExists(field, gh.contactFormData, parentID);
            }
            gh.contactFormValidation.validatePersonalInformation(gh.contactFormData, parentID);
        },

        checkFormFieldsExists: function (fieldName, storageCont, parentID) {
            var fieldID = $j("#" + parentID + " #" + fieldName);
            if ($j(fieldID).length > 0) {
                return gh.contactFormValidation.getFormFieldData(fieldName, parentID);
            } else {
                return storageCont[fieldName];
            }
        },

        getFormFieldData: function (fieldName, parentID) {
            var fieldID = '#' + parentID + ' #' + fieldName;
            var fieldType = gh.contactFormValidation.getFieldType(fieldID);
            if (fieldType == 'radio') {
                if ($j(fieldID).attr('checked')) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return $j(fieldID).val() || "";
            }
        },

        getFieldType: function (fieldID) {
            var fieldType = "";
            if ($j(fieldID).is(":radio")) {
                //Check if input is a radio button
                fieldType = "radio";
            } else if ($j(fieldID).is("select")) {
                //Check is input is a select dropdown 
                fieldType = "select";
            } else {
                // Default everything else to Textbox 
                fieldType = "text";
            }
            return fieldType;
        },

        validatePersonalInformation: function (storageCont, parentID) {
            for (field in storageCont) {
                var fieldID = $j("#" + parentID + " #" + field);
                var fieldType = gh.contactFormValidation.getFieldType(fieldID);
                if ($j(fieldID).length > 0) {
                    if (storageCont[field] === '' && $j(fieldID).hasClass('required')) {
                        // add error highlight
                        $j(fieldID).addClass('error-field');
                        gh.validateErrors.information = false;
                    } else {
                        $j(fieldID).removeClass('error-field');
                        if ($j(fieldID).hasClass("HomePhone") || $j(fieldID).hasClass("MobilePhone")) {
                            var regex = /^(\(?\+?\d*)[0-9](|.*\(?\)?\d*[0-9]|)*$/;
                            var str = storageCont[field];
                            if (!str.match(regex)) {
                                if (!$j(fieldID).hasClass('required') && storageCont[field] !== '') {
                                    $j(fieldID).addClass('error-field');
                                    gh.validateErrors.information = false;
                                } else if ($j(fieldID).hasClass('required')) {
                                    $j(fieldID).addClass('error-field');
                                    gh.validateErrors.information = false;
                                }
                            } else {
                                $j(fieldID).removeClass('error-field');
                                gh.validateErrors.information = true;
                            }
                        } else if ($j(fieldID).hasClass("Email")) {
                            var regex = /\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
                            var str = storageCont[field];
                            if (!str.match(regex)) {
                                $j(fieldID).addClass('error-field');
                                gh.validateErrors.information = false;
                            } else {
                                $j(fieldID).removeClass('error-field');
                                gh.validateErrors.information = true;
                            }
                        }
                    }
                }
            }
            gh.validateErrors.information = true;
            for (field in storageCont) {
                var fieldID = $j("#" + parentID + " #" + field);
                if ($j(fieldID).length > 0) {
                    if ($j(fieldID).hasClass('error-field')) {
                        gh.validateErrors.information = false;

                    }
                }
            }

            if (gh.validateErrors.information === true) {
                if (parentID === 'global-content-container') {
                    var formQueryString = "?";
                    for (field in gh.contactFormData) {
                        formQueryString += field + "=" + gh.contactFormData[field] + "&";
                    }
                    var siteRootID = $j('#global-links ul li#contact-button a').parent().attr('data-root');
                    formQueryString += "siteRootID=" + siteRootID;
                    var contactFormThankYouUrl = '/sitecore/__/Funneling/handler/FormSubmissionHandler.ashx' + formQueryString;
                    var contactFormThankYouHttp = gh.generic.GetXmlHttpObject();
                    var contactFormThankYouTarget = '#global-content-container #global-contact-us #contact-form';
                    gh.contactFormValidation.animateAJAXContent(contactFormThankYouHttp, contactFormThankYouUrl, contactFormThankYouTarget);
                    gh.globals.fireEvent = 'true';
                    gh.generic.contactTrackerSetUp();

                } else {
                    $j('#main #contact-form .buttonLink #submit').trigger();
                }
            }

        },

        animateAJAXContent: function (httpRequest, url, target) {
            var progressBarBlue = 'http://media.ef.com/Funneling/images/global-header/ajax-loader_blue.gif';

            $j(target).find('form').fadeOut(function () {
                $j(target).html("<div class='loading'><img src='" + progressBarBlue + "' /></div>");
            });
            gh.contactFormValidation.ajaxCall(httpRequest, url, target);
        }, // end animateAJAXContent()

        // set up a global function for ajax calls passing various parameter for targets and url
        ajaxCall: function (httpRequest, url, target) {
            if (httpRequest === null) {
                alert('Your browser does not support XMLHTTP!');
                return;
            }
            httpRequest.onreadystatechange = function () {
                // animate content once ready, may require a lot of work later
                if (httpRequest.readyState === 4) {
                    if (httpRequest.status === 200) {

                        $j(target).find('.loading').fadeOut();
                        $j(target).queue(function () {
                            $j(this).html(httpRequest.responseText);
                            $j(this).find('> div').fadeIn();
                            $j(this).dequeue();
                        });
                    } else if (httpRequest.status === 404) {
                        $j(target).queue(function () {
                            $j(this).html('<p class="error404">Error ' + httpRequest.status + ': ' + gh.globals.error404 + '</p>');
                            $j(this).find('div').fadeIn();
                            $j(this).dequeue();
                        });
                    }
                }
            };
            httpRequest.open("GET", url, true);
            httpRequest.send();
        } // end ajaxCall()

    };

    // initalize the ef global header
    gh.funnelling.initalize();
    // Initalize the ef contact us
    // gh.contactUs.initalize();


    gh.contactFormValidation.initalize();

    // Initalize the ef product header if isMultiLineProductName is true
    if (isMultiLineProductName === true && splitCount > 0) {
        gh.productHeader.initalize();
    }

    //Initialize the NON product header for central sites.

    /*
    This logic has been moved to the nonproduct header XSLT in global navigation
    if ($j("#site-name").length > 0) {
    gh.nonproductHeader.initalize(42);
    }*/

    if ($j('#product-contact-us').length === 1) {
        gh.loadScripts.loadPlugins();


        if ($j('#contact-details-container').attr('data-isstreetview')) {
            var streetViewAvailable = $j('#contact-details-container').attr('data-isstreetview');
            if (streetViewAvailable === 'false') {
                $j('body').addClass('no-streetview');
            }
        }

    }

    if ($j('#universalLinksButton').length === 1) {
        gh.generic.universalLinks();
    }

    if ($j('.office-images').length > 0) {
        gh.lightbox.initalize();
    }






};
// End efInitalize()






// mktSet = 'fr';
// ageGroupSet = 'HIGH';
// programSet = 'JU';
// programWent = ~JU~





efInitalize();

//END document ready

