/*jslint onevar: true, sub: true */
/**
 *   Javascript Library for DTS
 *   @requires jQuery 1.5+
 *   @author Digitaria, Inc.
 */

 /**
  *  setup the global Digitaria class and tie it to the window object
  *  @author Michael Turnwall
  */
 (function (global) {

     function digi() { }

     /**
     *   extend an object by merging with other objects
     *   if only one object is passed in then it extends digi class
     */
     digi.extend = function () {
         var target = arguments[0] || {},
             i = 1,
             length = arguments.length,
             property,
             source;
         if (length === i) {
             target = this;
             i = 0;
         }
         for (; i < length; i++) {
             source = arguments[i];
             if (source != null) {
                 for (property in source) {
                     target[property] = source[property];
                 }
             }
         }
         return target;
     };
     /**
     *  retrieves css for a given element
     *  @param {DOM Node} el the element to find the style from
     *  @param {String} style the actual style to get such as padding, margin, postion, etc
     *  @returns {String} the value of the style or an error message
     */
     digi.getStyle = function (el, style) {
         var styled;
         if (typeof el !== "object") {
             el = document.getElementById(el);
         }
         if (el.currentStyle) {  // IE
             styled = (el.currentStyle[style]);
         } else if (window.getComputedStyle) {  // everyone else
             styled = (document.defaultView.getComputedStyle(el, null).getPropertyValue(style));
         }
         return (styled) ? styled : "Error: Sorry, " + style + " could not be found";
     };
     /**
     *  finds the position of a DOM Node either relative to it's first offset parent or the window
     *  @param {DOM Node} el the element to find the style from
     *  @param {Boolean} [offset='false'] if set to true, position is based off of element's offset parent
     *  @returns {Object} element's position represented by an object, pos.x and pos.y
     */
     digi.findPosition = function (el, offset) {
         var pos = {
             x: 0,
             y: 0
         };
         if (el.offsetParent) {
             do {
                 pos["x"] += el.offsetLeft;
                 pos["y"] += el.offsetTop;
                 if (offset) {
                     if ($digi.getStyle(el.offsetParent, 'position') == 'relative') {
                         break;
                     }
                 }
                 el = el.offsetParent;
             } while (el);
         }
         return pos;
     };
     /**
     *  find the size of the viewport of the browser window
     *  @returns {Array} viewport.width, viewport.height
     */
     digi.getViewport = function () {
         var viewport = [];
         // standards compliant browsers
         if (window.innerHeight) {
             viewport["width"] = window.innerWidth;
             viewport["height"] = window.innerHeight;
         }
         // IE6 in standards mode. IE6 in quirks mode won't work
         else if (document.documentElement.clientHeight) {
             viewport["width"] = document.documentElement.clientWidth;
             viewport["height"] = document.documentElement.clientHeight;
         }
         return viewport;
     };
     /**
     *  find how far down the page the user has scrolled
     *  @returns {Array} offset.x, offset.y
     */
     digi.getScrollLength = function () {
         offset = [];
         if (self.pageXOffset || self.pageYOffset) {
             offset["x"] = self.pageXOffset;
             offset["y"] = self.pageYOffset;
         } else if ((document.documentElement && document.documentElement.scrollLeft) || (document.documentElement && document.documentElement.scrollTop)) {
             offset["x"] = document.documentElement.scrollLeft;
             offset["y"] = document.documentElement.scrollTop;
         }
         else if (document.body) {
             offset["x"] = document.body.scrollLeft;
             offset["y"] = document.body.scrollTop;
         }
         return offset;
     };

     digi.createLoader = function (options) {
         var loader = $("<div></div>")
                       .attr({ id: "formLoader" })
                       .attr({ style: options.styling || "width:32px;height:32px;float:right;" });
         /*console.log(loader);
         console.log($(options.replaceElement, options.context));*/
         $(options.replaceElement, options.context).hide().after(loader);
         return loader;
     };

     digi.version = "0.1";

     digi.alias = '$digi';
     global[digi.alias] = digi;

     if (global.digi) {
         throw new Error('digi object already defined');
     } else {
         global.digi = digi;
     }

 })(typeof window === 'undefined' ? this : window);
 
// form validation copied from epicpoker.com
function initFormValidation() {
    $('#siteHeaderSearch').submit(function () {
        var notEmpty = true;
        $('input:text', this).each(function () {
            var value = this.value;
            if (value == '' || value == $(this).data('defaultValue')) {
                notEmpty = false;
                return true;
            }
        });
        if (!notEmpty) {
            alert('Please enter a search term.');
            return notEmpty;
        }
    });
    /*
    * ----------------------------------------
    * First the "old style" of Matt's
    * Applies to any form with class "genericForm"
    * ----------------------------------------
    */
    // Grab hold of the .genericForm and don't allow it to submit unless it validates
    $('.genericForm').each(function() {
        this.onsubmit=function() {
            return validateForm($(this).attr('id'));
        };
    });

    // Do the same with the submit button
    $('.genericForm button.submit').each(function() {
        this.onclick=function() {
            return validateForm($(this).attr('id'));
        };
    });

    /*
    * ----------------------------------------
    * Now the new style
    * Applies to any form with class "validateForm"
    * ----------------------------------------
    */
    // Initialize the form validator
    validator=new com.digitaria.validator();

    // Grab hold of the .genericForm and don't allow it to submit unless it validates
    $('.formTemplate').not('form[data-success-element]').each(function() {
        this.onsubmit=function() {
            return validator.validate($(this), {});
        };
    });
    $('#contactUsModal form').submit(function () {
        var form = this,
            successEl = document.getElementById(form.getAttribute('data-success-element'));
        validation = validator.validate($(this), {});
        if (validation) {
            $digi.createLoader({ replaceElement: '.formTemplate', context: '#contactUsModal' });
            $.ajax({
                type: this.method,
                url: this.action,
                data: $(this).serialize(),
                success: function (data) {
                    if (data.result) {
                        form.style.display = 'none';
                        successEl.innerHTML = data.message;
                        successEl.style.display = 'block';
                    } else {
                        alert('There was an error submitting the form. Please try again later');
                    }
                    $('#formLoader').hide();
                },
                error: function () {
                    form.style.display = 'none';
                    successEl.innerHTML = 'There was an error submitting the form. Please try again later';
                    successEl.style.display = 'block';
                    $('#formLoader').hide();
                }
            });
        }
        return false;
    });

    // Do the same with the submit button
    $('.form button[type=submit]').each(function() {
        this.onclick=function() {
            return validator.validate($(this).parents('form'), {});
        };
    });
}

digi.expander = function (actuator, selector) {
    var i = 0,
        $_expandArea = $('.' + selector);
    if (actuator == 'inner') {
        $('.expandedArea').removeClass('expanded');
    } else {
        $('.innerActuator a').css('display', 'block');
    }
    $_expandArea.animate({
        height: 'toggle',
        opacity: 'toggle'
    }, {
        duration: 250,
        complete: function () {
            if (actuator == 'inner') {
                // $('.innerActuator a').hide();
                // $('.outerActuator a span').show();
                $('.expandedArea').removeClass('expanded');
            } else {
                // $('.outerActuator a span').hide();
                $('.innerActuator a').css('display', 'block');
                $('.expandedArea').addClass('expanded');
            }
        }
    });
};

digi.faqSlider = (function (options) {
    var $_actuator, $_container, $_section;
    
    return {
        animateSlide: function (el, callback) {
            $(el).animate({
                height: 'toggle'
            }, {
                duration: 500,
                easing: 'easeOutExpo',
                complete: callback
            });
        },
        open: function () {
            this.animateSlide($_section);
            $_container.addClass('faqOpened');
        },
        close: function () {
            this.animateSlide($_section);
            $_container.removeClass('faqOpened');
        },
        startSlide: function (el) {
            $_actuator = $(el);
            $_container = $_actuator.parents('.faqCont');
            $_section = $('.section', $_container);
            if ($_container.hasClass('faqOpened')) {
                this.close();
            } else {
                this.open();
            }
        }
    };
})();

/**
 *  DTS Modal/Dialog Module
 *  @requires jQuery UI Dialog module
 *  @author Michael Turnwall
 */
(function (digi) {
    var modals = {},
        $_dialog,
        $_el,
        id,
        modal,
        opts,
        selector,
        width;
    
    modals.openModal = function (options) {
        id = options.el.rel;
        // width =  (typeof width === 'undefined') ? (el.getAttribute('data-modalwidth')) : 630;
        $_dialog = $('#' + id).dialog({
            draggable: false,
            dialogClass: (typeof options.dialogClass !== 'undefined') ? options.dialogClass : true,
            modal: (typeof options.modal !== 'undefined') ? options.modal : true,
            resizable: false,
            show: 'fade',
            width: width, 
			open: function () { centerDialog() },
			close: function (event, ui) {
			    if (typeof options.onClose === 'function') {
			        options.onClose(event, ui);
			    }
			}
        });
        return $_dialog;
    };
    
    modals.loadImg = function (imgSrc) {
        var img, offset, currentWidth, currentHeight, top, left;
        img = new Image();
        modal.empty();
        img.onload = function () {
            offset = $_dialog.offset();
            currentWidth = $_dialog.parent().outerWidth();
            currentHeight = $_dialog.parent().outerHeight();
            top = offset.top + ((currentHeight - img.height - 30) / 2);
            left = offset.left + ((currentWidth - img.width - 30) / 2);
            width = img.width;
            $_dialog.parent().animate({
                top: top,
                left: left,
                width: img.width,
                height: img.height
            }, function () {
                modal.append(img);
            });
        };
        img.src = imgSrc;
    };
    
    /**
     *  don't use the jqueryUI dialog since the modal always needs to be in the feature rotator area
     *  jqueryUI always positions in relation to viewport
     */
    modals.loadVideoSlide = function (el) {
        var videoSlideModal, videoSlideModalClone, offset;
        videoSlideModal = $('#videoSlideModal');
        videoSlideModalClone = videoSlideModal.clone(true);
        offset = $('.featuredAreaRotatorModule .activeSlide').offset();
        videoSlideModalClone.attr('id', 'videoSlideModalClone').css({
            top: (offset.top - 10),
            left: (offset.left + 160)
        });
        $('body').append(videoSlideModalClone);
        digi.slideshow.pause();
        $('#videoSlideOverlay').fadeTo('normal', 0.9, function () {
            $('#videoSlideModalClone').show();
            if ($('iframe', videoSlideModalClone).attr('src') != el.href) {
                $('iframe', videoSlideModalClone).attr('src', el.href);
            }
        });
    };
    
    modals.closeVideoSlide = function (el) {
        var videoSlideModal = $('#videoSlideModal iframe');
        videoSlideModal.attr('src', '');
        $('#videoSlideModalClone').remove();
        $('#videoSlideOverlay').fadeOut(function () {
            digi.slideshow.play();
        });
    };
    
    modals.init = function (options) {
        var oldHref, closeCallback;
        opts = options || {};
        selector = (typeof opts.selector === 'undefined') ? 'a.modalLink' : opts.selector;
        $_el = $(selector);
        $_el.bind('click', function () {
            var that = this,
                videoModal;
            modal = $('#' + that.rel);
            if (this.className.match(/expandImgBtn/)) { 
                if (oldHref != this.href) {// only show image if it's a new image
                    modals.loadImg(this.href);
                }
                digi.modals.openModal({
                    el: this,
                    modal: true
                });
            } else if (this.className.match(/videoModal/)) {
                videoModal = $('#videoModal iframe');
                if (videoModal.attr('src') != this.href) {
                    videoModal.attr('src', this.href);
                }
                width = videoModal.width();
                digi.modals.openModal({
                    el: this,
                    modal: true,
                    onClose: function () {
                        $('#' + id + ' iframe').attr('src', '');
                    }
                });
            } else if (this.className.match(/videoSlide/)) {
                modals.loadVideoSlide(this);
            } else {
                width = (typeof width === 'undefined') ? (this.getAttribute('data-modalwidth')) : 630;
                if (this.className.match(/\bcontactUsLink\b/ig)) {
                    // remove success message and blank form so user can enter another question
                    closeCallback = function () {
                        var form =  $('#contactUsModal form');
                        form.get(0).reset();
                        form.css('display', 'block');
                        $('#' + form.attr('data-success-element')).empty();
                    };
                }
                digi.modals.openModal({
                    el: this,
                    modal: true,
                    onClose: closeCallback
                });
            }
            oldHref = this.href;
            return false;
        });
        $('.closeVideoSlideBtn').live('click', function (e) {
            e.preventDefault();
            modals.closeVideoSlide(this);
        });
    };
    digi.modals = modals;
})(digi);

/**
 *  DTS Tabs Module
 *  @author Michael Turnwall
 */
(function (digi) {
    var tabs = {},
        tabId;
    tabs.activeClass = 'activeTab';
    tabs.hide = function () {
        $('.' + tabs.activeClass).hide();
    };
    tabs.show = function (selector) {
        if (selector === undefined) {
            return false;
        }
        this.hide();        
        if($.browser.msie)
        {
            $(selector).show();
            $(selector).addClass(tabs.activeClass);
        }
        else
        {
            $(selector).fadeIn(function () {
                $(this).addClass(tabs.activeClass);
            });
        }
    };
    tabs.switchTab = function (el) {
        if (el.rel === undefined || el.rel === tabId) {
            return false;
        }
        tabId = el.rel;
        tabs.show('#' + tabId);
        $('li.active').removeClass('active');
        $(el).parent().addClass('active');
    };
    tabs.init = function (selector) {
        $('.tabCont').first().addClass(tabs.activeClass);
        $(selector).bind('click', function () {
            tabs.switchTab(this);
            return false; 
        });
    };
    digi.tabs = tabs;
})(digi);

/**
 *  DTS Tooltip Module
 *  @author Michael Turnwall
 */
(function (digi) {
    var tooltip = {},
        positionTooltip,
        obj = tooltip,
        timer, trigger,
        delay = 250,
        defaults = {
            triggerSelector: '.flyoutTrigger',
            flyoutSelector: '.techSubMenu',
            pointer: '.pointer'
        };
        
    function clearTimer() {
        clearTimeout(timer);
    }
    
    tooltip.timer = false;
    tooltip.delay = 250;
    tooltip.findElementPos = function (el, offset) {
        return digi.findPosition(el, offset);
    };
    tooltip.movePointer = function (top, left, $_popup, popupHeight, side) {
        var pointer = $(defaults.pointer, $_popup),
            pointerTop = top - 30,
            css = {};
        css.top = pointerTop;
        if (side == 'left') {
            css.right = 0 - 11;
        } else {
            css.left = 0;
        }
        pointer.css(css);
    };
    tooltip.show = function (el, parent) {
        /*
            TODO clean this function up, it sure is messy
        */
        var left, topOffset, $_popup, $_parent, popupHeight, offsetPos, truePos, viewport, contentArea, scrollLength,
            popupWidth, side, top, wrapper;
        $(defaults.flyoutSelector).hide();
        topOffset = 0;
        $_popup = $('.techSubMenu', parent);
        $_parent = parent;
        popupHeight = $_popup.outerHeight();
        offsetPos = this.findElementPos(el, true);
        truePos = this.findElementPos(el);
        viewport = digi.getViewport();
        wrapper = $_parent.parents('.moduleContentInner');
        contentArea = {
            width: wrapper.width(),
            height: wrapper.height()
        };
        scrollLength = digi.getScrollLength();
        popupWidth = $_popup.outerWidth();
        // make sure popup doesn't go off the bottom of the page
        if ((truePos.y + popupHeight) > (viewport['height'] + scrollLength['y'])) {
            topOffset = (truePos.y + popupHeight) - (viewport['height'] + scrollLength['y']);
        }
        top = offsetPos.y - topOffset - 10;
        
        if (positionTooltip) {
            //  if combination of the left pos, hover element width, and popup width is less than the main area
            //  then put on right side
            if (offsetPos.x + el.offsetWidth + popupWidth < contentArea.width) {
                left = offsetPos.x + el.offsetWidth;
                side = 'right';
            } else {
                left = offsetPos.x - popupWidth; // subtract 20 to compensate for the shadow
                side = 'left';
            }

            if ($_popup.css('display') != 'block') {
                $_popup.css({
                    top: top,
                    left: left
                });
                $_popup.addClass(side);
                tooltip.movePointer(top, left, $_popup, popupHeight, side);
                $_popup.animate({
                    left: (side == 'right') ? (left + 10) : (left - 10),
                    opacity: 'toggle'
                }, 'fast');
            }
        } else {
            if ($_popup.css('display') != 'block') {
                $_popup.css('top', top).fadeIn();
            }
        }
        
    };
    tooltip.hide = function (parent) {
        $('.techSubMenu', parent).removeClass('active').hide();
    };
    tooltip.init = function (selector, position) {
        var el,
            parent;
        positionTooltip = position;
        // obj = this;
        $(selector).hover(function () {
            clearTimer();
            el = this;
            parent = $(this).parent();
            if ($('.techSubMenu', parent).css('display') != 'block') {
                timer = setTimeout(function () {
                    obj.show.call(obj, el, parent);
                }, obj.delay);
            }
        }, function () {
            clearTimer();
            timer = setTimeout(function () {
                obj.hide.call(obj, parent);
            }, obj.delay);
        });
        $(defaults.flyoutSelector).hover(function () {
            clearTimer();
        }, function () {
            clearTimer();
            parent = $(this).parent();
            timer = setTimeout(function () {
                obj.hide.call(obj, parent);
            }, obj.delay);
        });
    };
    digi.tooltip = tooltip;
})(digi);

/**
 *  Tool tip for technologies
 *  a rewrite of the tooltip module
    TODO finish this rewrite
 *  @author Michael Turnwall
 */
digi.techTips = (function () {
    var timer, trigger,
        delay = 250,
        defaults = {
            triggerSelector: '.flyoutTrigger',
            flyoutSelector: '.techSubMenu',
            pointer: '.pointer'
        };
    function clearTimer() {
        clearTimeout(timer);
    }
    
    return {
        findPos: function () {
            
        },
        show: function (flyout) {
            
        },
        hide: function () {
            
        },
        init: function (opts) {
            var obj = this;
            this.opts = digi.extend({}, opts, defaults);
            this.$_trigger = $(this.opts.triggerSelector);
            this.$_flyout = $(this.opts.flyoutSelector);
            this.$_trigger.hover(function () {
                var flyout = $(this).siblings(obj.opts.flyoutSelector);
                timer = setTimeout(function () {
                    obj.show.call(obj, flyout);
                }, delay);
            }, function () {
                clearTimer();
                timer = setTimeout(function () {
                    obj.hide.call(obj);
                }, delay);
            });
        }
    };
})();

/**
 *  Ribbon style nav
 *  @author Michael Turnwall
 */
digi.ribbon = (function () {
    var animSpeed = 500,
        delay = 10,
        isNav,
        ribbon = {},
        $_nav,
        $_oldNav = false,
        selector,
        timer;
        
    function showRibbon() {
        if (selector != '#searchInputBox') {
            $(selector).animate({
                height: 'toggle',
				opacity: 'toggle'
            }, {
                duration: animSpeed,
                complete: function () {
            
                }
            });
        } else {
            $(selector).show();
        }
    }
    function clearTimer() {
        clearTimeout(timer);
    }
    return {
        show: function (el) {
            selector = (this.isNav) ? ('#' + el.rel) : ('#' + el.getAttribute('data-expander'));
            $_nav = $(selector);
            if ($_oldNav && $_oldNav.css('display') == 'block') {
                this.hide();
                $_nav.show();
            } else {
                timer = setTimeout(showRibbon, delay);
            }
            $_oldNav = $_nav;
        },    
        hide: function () {
            clearTimer();
            if ($_oldNav) {
                $_oldNav.hide();
				$('.activeHov').removeClass('activeHov');
            }
        },
        init: function (actuator, dropDown, nav) {
            var that = this;
			$_actuator = $(actuator);
            this.isNav = nav  || false;
            // $(actuator).each(function () {
            //     this.onmouseover = function () {
            //         that.show(this);
            //     };
            //     this.onmouseout = function () {
            //         clearTimer();
            //         timer = setTimeout(that.hide, delay);
            //     };
            // });
			
			
			/*$(actuator).bind('mouseover',function (e) {
				that.show(this);
			});*/
			
			if (!$_actuator.hasClass('searchOpenClose')) {
			    $_actuator.bind('mouseover',function (e) {
    				that.show(this);
					$(this).addClass('activeHov');
					
    			});
			    
			} else {
			    $_actuator.bind('click',function (e) {
			        e.preventDefault();
    				that.show(this);
    			});
			}

			$(actuator).bind('mouseout', function () {
                clearTimer();
                timer = setTimeout(that.hide, delay);
            });

            $(dropDown).bind('mouseover', function (e) {
                clearTimer();
            });

            $(dropDown).bind('mouseout', function () {
                clearTimer();
                timer = setTimeout(that.hide, delay);
            });
        }
    };
})();

/**
 *  Slideshow Rotator
 *  @author Michael Turnwall
 */
(function (digi) {
    var slideshow = {};
    
    slideshow.options = {
        auto: true,     // start slideshow on page load
        play: true,     // it's okay to rotate a slide
        playBtn: '.playBtn',    // selector for the play button
        slides: '.slide',       // selector for the individual slides
        slideControl: '.rotatorControls a',   //
        speed: 5000,     // speed between slides
        startPos: 1
    };
    /**
     *  start the rotator interval
     */
    slideshow.startRotate = function () {
        var obj = this;
        this.stopRotate();
        // this.currentPos = this.incrementPos();
        this.timer = setInterval(function () {
            obj.rotateSlide.call(obj, obj.currentPos, true);
        }, this.opts.speed);
    };
    /**
     *  clear the interval timer to stop slides from rotating
     */
    slideshow.stopRotate = function () {
        clearInterval(this.timer);
    };
    /**
     *  rotate the slides to desired slide
     *  @param {Integer} pos slide number to rotate to. If no pos is set then the currentPos parameter is used.
            After the rotation is complete, the currentPos parameter is incremented
     */
    slideshow.rotateSlide = function (pos) {
        var obj = this,
            tempPos = (pos == 'undefined') ? this.currentPos : pos;
        this.moveMarker(this.$_slideControls[tempPos]);
        $('.activeSlide', obj.el).fadeOut(500, function () {
            $(this).removeClass('activeSlide');
        });
        $(this.$_slides[tempPos]).fadeIn(500, function () {
            obj.currentPos = obj.incrementPos(tempPos);
            this.className += ' activeSlide';
        });
    };
    /*
     *  move the current position counter to the next slide
     *  @returns {Integer} next slide number
     */
    slideshow.incrementPos = function (start) {
        var pos = start || this.currentPos;
        return (pos < (this.$_slides.length - 1)) ? (pos + 1) : 0;
    };
    /*
     *  move the marker that designates which slide the user is on
     *  @param {DOM Node} el element that will be marked as active
     */
    slideshow.moveMarker = function (el) {
        var parent = $(el).parent();
        $('.activeDot', parent).removeClass('activeDot');
        el.className += ' activeDot';
    };
    slideshow.pause = function () {
        this.stopRotate();
        this.playStatus = false;
        if (!this.$_playBtn.hasClass('paused')) {
            this.$_playBtn.addClass('paused');
        }
    };
    slideshow.play = function () {
        this.playStatus = true;
    };
    /**
     *  setup the events for the slide controls
     */
    slideshow.setControlEvents = function () {
        var obj = this,
            oldLink;
        this.$_slideControls.bind('click', function () {
            var $_this = $(this),
                controlPos;
            obj.stopRotate();
            controlPos = this.innerHTML;
            if (this == oldLink) {
                return false;
            }
            if (this.rel != 'play') {
                obj.rotateSlide(controlPos - 1);
                if (this.$_playBtn) {
                    obj.playStatus = false;
                    if (!obj.$_playBtn.hasClass('paused')) {
                        obj.$_playBtn.addClass('paused');
                    }
                }
            } else {
                if (this.className.match(/paused/)) {
                    $_this.removeClass('paused');
                    obj.playStatus = true;
                    obj.startRotate();
                } else {
                    obj.stopRotate();
                    obj.playStatus = false;
                    $_this.addClass('paused');
                }
            }
            oldLink = this;
            return false;
        });
    };
    /** 
	 * initializes the object
	 * @param {Object Literal} options an object containing options for object
	 * @param {DOM Node} elem dom element to attach the messaging object to
	 * @constructs
	 */
    slideshow.init = function(options) {
        var obj = this,
            pos;
        this.timer;
        this.opts = $digi.extend({},this.options,options);
        // this.el = el;       // create local instance of DOM element
        this.$_el = $(this.opts.elSelector);  // create local instance of jQuery object
        this.$_slides = $(this.opts.slides, this.$_el);
        this.$_slideControls = $(this.opts.slideControl, this.$_el);
        if ($(this.opts.playBtn, this.$_el).length) {
            this.$_playBtn = false;
        } else {
            this.$_playBtn = $(this.opts.playBtn, this.$_el);
        }
        this.playStatus = this.opts.play;
        pos = this.opts.startPos;
        this.currentPos = (pos > 0 && pos < (this.$_slides.length - 1)) ? pos : 1;
        
        this.setControlEvents();
        
        this.$_slides.hover(function () {
            obj.stopRotate.call(obj);
        }, function () {
            if (obj.playStatus && obj.opts.auto) {
                obj.startRotate();
            }
        });
        
        if (this.opts.auto) {
            this.startRotate();
        }
        return this;
    };
    
    digi.slideshow = slideshow;
})(digi);

(function(digi) {

	var carouselSlider = {},
	    handleHelper,
	    scrollPane = $( ".carouselWrapper" ),
		scrollContent = $( ".scrollContent" ),
		scrollbar;
	
	//size scrollbar and handle proportionally to scroll distance
	function sizeScrollbar() {
	    var remainder,
	        proportion,
	        handleSize = 35;
		remainder = scrollContent.width() - scrollPane.width();
		proportion = remainder / scrollContent.width();
		handleSize = 35;
		scrollbar.find( ".ui-slider-handle" ).css({
			width: handleSize,
			"margin-left": -handleSize / 2
		});
        // handleHelper.width( "" ).width( scrollbar.width() - handleSize );
	}
	
	//reset slider value based on scroll content position
	function resetValue() {
	    var remainder, leftVal, percentage;
		remainder = scrollPane.width() - scrollContent.width();
		leftVal = scrollContent.css( "margin-left" ) === "auto" ? 0 : parseInt( scrollContent.css( "margin-left" ) );
		percentage = Math.round( leftVal / remainder * 100 );
		scrollbar.slider( "value", percentage );
	}
	
	carouselSlider.init = function () {
	    //build slider
        scrollbar = $( ".scroll-bar" ).slider({
            slide: function( event, ui ) {
                if ( scrollContent.width() > scrollPane.width() ) {
                    scrollContent.css( "margin-left", Math.round(ui.value / 100 * ( scrollPane.width() - scrollContent.width() )) + "px" );
                } else {
                    scrollContent.css( "margin-left", 0 );
                }
            }
        });
        //append icon to handle
        handleHelper = scrollbar.find( ".ui-slider-handle" )
                                .append( "<span class='ui-icon ui-icon-grip-dotted-vertical'></span>" )
                                .wrap( "<div class='ui-handle-helper-parent'></div>" ).parent();
        //change overflow to hidden now that slider handles the scrolling
        scrollPane.css( "overflow", "hidden" );
        setTimeout( sizeScrollbar, 10 );//safari wants a timeout
	};
    
    digi.carouselSlider = carouselSlider;
})(digi);

digi.updateLoginForm = function (el) {
    var value = el.value,
        forgotLink = document.getElementById('forgotPasswordLink'),
        createProfileLink = document.getElementById('createProfileLink'),
        extendedForm = $('.extendedForm');
    if (value) {
        if (extendedForm.css('display') != 'block') {
            extendedForm.slideDown();
        }
        forgotLink.href = loginUrls[value].forgot;
        createProfileLink.href = loginUrls[value].create;
        $('.formErrors').hide();
    } else {
        extendedForm.slideUp();
    }
};

digi.rotateBannerText = (function () {
    var count,
        easing = 'easeInOutExpo',
        defaults = {
            animSpeed: 500,
            activeClass: 'activeItem',
            slidesParentSel: '.textRotateMask',
            slideSel: '.rotateItem',
            interval: 3000
        },
        that,
        timer,
        wordsLength;
    return {
        words: [],
        rotateText: function () {
            var newEl,
                activeClass = that.opts.activeClass;
            count = that.incrementPos();
            newEl = that.prepText();
            $('.' + activeClass).animate({
                top: '70px',
                opacity: 'toggle'
            }, {
                duration: that.opts.animSpeed,
                easing: easing,
                complete: function () {
                    $(this).removeClass(activeClass);
                }
            });
            newEl.addClass(activeClass).animate({
                top: 0,
                opacity: 'toggle'
            }, {
                duration: that.opts.animSpeed,
                easing: easing,
                complete: function () {
                    $(this).addClass(that.opts.activeClass);
                }
            });
        },
        prepText: function () {
            return $(that.$_items[count]).css({
                top: '-65px',
                display: 'none'
            });
        },
        incrementPos: function () {
            var tempPos = count;
            if (tempPos >= (wordsLength - 1)) {
                return 0;
            }
            return (tempPos + 1);
        },
        init: function (opts) {
            that = this;
            that.opts = digi.extend({}, opts, defaults);
            that.$_items = $(that.opts.slideSel);
            count = (typeof that.opts.startPos === 'undefined') ? 0 : startPos;
            wordsLength = that.$_items.length;
            timer = setInterval(that.rotateText, that.opts.interval);
        }
    };
})();

/*digi.mmgFilter = (function () {
    var filterBy,
        $_filterItems,
        defaults = {
            itemSel: '.mediaCell'
        },
        that;
    return {
        animateItem: function (el) {
            $(el).fadeIn(1500);
        },
        runFilter: function (filtered) {
            var newRow = $('<div class="mediaRow" />'),
                filterWrapper = $('.mediaRows'),
                el;
            // filtered.css('display', 'none');
            filterWrapper.empty();
            // console.time('native');  
            for (var i=0, z=filtered.length; i < z; i++) {
                el = $(filtered[i]);
                if (newRow) {
                    filterWrapper.append(newRow);
                    newRow = false;
                }
                if ((i + 1) % 3) {
                    el.removeClass('lastCell');
                } else {
                    if (!el.hasClass('lastCell')) {
                        el.addClass('lastCell');
                    }
                    newRow = $('<div class="mediaRow" />');
                }
                $('.mediaRow').last().append(el);
            }
            // console.timeEnd('native'); 
            // console.time('jquery'); 
            // filtered.each(function (i) {
            //     var $_this = $(this);
            //     i++;
            //     if (newRow) {
            //         filterWrapper.append(newRow);
            //         newRow = false;
            //     }
            //     if (i % 3) {
            //         $_this.removeClass('lastCell');
            //     } else {
            //         if (!$_this.hasClass('lastCell')) {
            //             $_this.addClass('lastCell');
            //         }
            //         newRow = $('<div class="mediaRow" />');
            //     }
            //     $('.mediaRow').last().append(this);
            // });
            // console.timeEnd('jquery');
        },
        setupFilter: function (el) {
            var numOfRows,
                newRow = $('<div class="mediaRow" />'),
                filterWrapper = $('.mediaRows'),
                filtered,
                regexp;
            filterBy = el.innerHTML;
            regexp = new RegExp(filterBy);
            if (!filterBy.match(/all/ig)) {
                filtered = $_filterItems.filter(function () {
                    if (this.getAttribute('rel').match(regexp)) {
                        return this;
                    }
                });
            } else {
                filtered = $_filterItems;
            }
            this.runFilter(filtered);
        },
        init: function () {
            that = this;
            $_filterItems = $(defaults.itemSel);
            $('a.filterBtn').bind('click', function (e) {
                e.preventDefault();
                if (this.innerHTML !== filterBy) {
                    $('.filterControls a').removeClass('active');
                    this.className +=' active';
                    that.setupFilter(this);
                }
            });
        }
    };
    
})();*/

/** pass Object.create an object to create new instance */
if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}

function decreaseTimer(seconds) {
    if (seconds > 1) {
        seconds--;
        $('#takeoverModal > #timer > span').html(seconds);
        setTimeout('decreaseTimer(' + seconds + ')', 1000);
    }
    else {
        $('#takeoverModal').dialog("close");
    }
}

function centerDialog()
{
    $('.ui-dialog').each(function () {

        var myWidth = (window.innerWidth > 0) ? window.innerWidth : $(window).width();
        var myHeight = (window.innerWidth > 0) ? window.innerHeight : $(window).height();

        var posLeft = (myWidth - $('.ui-dialog').width()) / 2;

        if (posLeft < 0) {
            posLeft = 0;
        }

        var posTop = (myHeight - $('.ui-dialog').height()) / 2;

        if (posTop < 0) {
            posTop = 0;
        }

        $(this).css('left', posLeft + 'px').css('top', posTop + 'px').css('position', 'fixed');

    });
}

var resizeTimeoutId;
function window_resize() {
     window.clearTimeout(resizeTimeoutId);
     resizeTimeoutId = window.setTimeout('doResizeCode();', 10);
}

function doResizeCode()
{
	centerDialog();
}

$(document).ready(function () {
    var slideshow, ribbonNav, dropDown, searchInput, resourceCenterSelect, mmgIntroPlaying;

    /* Takeover Modal */

    // Show takeover ?
    if ($('#takeoverModal').length > 0 && jCore.readCookie("skipTakeover") === false) {
        jCore.writeCookie("skipTakeover", "true", 1);
        var width = $('#takeoverModal').data('width') == undefined ? 960 : $('#takeoverModal').data('width');
        var height = $('#takeoverModal').data('height') == undefined ? 600 : $('#takeoverModal').data('height');
        $('#takeoverModal').dialog({
            width: width,
            height: height,
            modal: true,
            open: function () {
                $(this).children('#timer').html('Ad will close in <span>' + $(this).data('timer') + '</span> seconds');
                setTimeout('decreaseTimer(' + $(this).data('timer') + ')', 1000);
				
				centerDialog();
             }
        });
    }
	
	$(window).resize(function () {
		window_resize();
	});	

    /* Ticket #49359 Update Resumeware Rss Integration */

    $('#recentJobOpenings .jobOpenings').each(function () {
        var url = $(this).attr('data-url');
        var that = $(this);

        if (url != "") {
            jQuery.getFeed({
                url: "/handlers/proxy.ashx?url=" + url,
                success: function (feed) {

                    if (feed !== undefined && feed.items !== undefined && feed.items.length > 0) {
                        var htmlColA = '';
                        var htmlColB = '';

                        var length = Math.min(6, feed.items.length);

                        for (var i = 0; i < length; i++) {

                            var item = feed.items[i];

                            if (i < 3) {
                                htmlColA += '<div class="jobOpening"><a title="' + item.title + '" href="' + item.link + '">' + item.title + '</a><span class="jobLocation">' + item.description + '</span></div>';
                            }
                            else {
                                htmlColB += '<div class="jobOpening"><a title="' + item.title + '" href="' + item.link + '">' + item.title + '</a><span class="jobLocation">' + item.description + '</span></div>';
                            }
                        }

                        $(that).html('<div class="colA">' + htmlColA + '</div>' + '<div class="colB">' + htmlColB + '</div>');
                    }
                    else {
                        $('#recentJobOpenings').hide();
                    }
                }
            });
        }
    });

    /* Ticket #47186: Hide background if no tout is in right rail */
    $('.rail4').each(function () {
        if (jQuery.trim(this.innerHTML) == "") {
            $(this).hide();
        }
    });

    $digi.rotateBannerText.init();

    /* Outline Issue IE7 #48731 */

    $('a').each(function () {
        $(this).attr("hideFocus", "true").css("outline", "none");
    });


    /* GA */

    /* Facebook */
    if (FB && FB.Event && FB.Event.subscribe) {
        FB.Event.subscribe('edge.create', function (targetUrl) {
            _gaq.push(['_trackSocial', 'Facebook', 'Like', document.title]);
        });
    }

    /* Twitter Tweet */
    if (twttr && twttr.events && twttr.events.bind) {
        twttr.events.bind('tweet', function (event) {
            if (event) {
                _gaq.push(['_trackSocial', 'Twitter', 'Tweet', document.title]);
            }
        });
    }

    $('a').bind('click', function () {
        // Track Some External Links
        if (!this.host.match(/dts.com/) &&
            !(
                this.className.match(/videoModal/) ||
                this.className.match(/videoSlide/) ||
                this.className.match(/trailer/) ||
                this.className.match(/connect_widget_like_button/) ||
                this.id == 'facebookLink' ||
                this.id == 'facebookShareBtn' ||
                this.href.match(/twitter.com\/share/) ||
                this.id == 'twitterLink' ||
                $(this).parents('div#plusone').length > 0 ||
                this.id == 'youtubeLink' ||
                this.href.match(/.pdf/)
             )
           ) {
            _gaq.push(['_trackEvent', 'Outbound Link', 'Outbound Link Click', this.href]);
        }

        // Video Link
        if (this.className.match(/videoModal/) ||
        this.className.match(/videoSlide/) ||
        this.className.match(/trailer/)) {
            _gaq.push(['_trackEvent', 'Video', 'Video Click', this.getAttribute('data-title')]);
        }

        // Facebook Follow
        if (this.id == 'facebookLink') {
            _gaq.push(['_trackSocial', 'Facebook', 'Follow', document.title]);
        }

        // Facebook Share
        if (this.id == 'facebookShareBtn') {
            _gaq.push(['_trackSocial', 'Facebook', 'Share', document.title]);
        }

        // Twitter Follow
        if (this.id == 'twitterLink') {
            _gaq.push(['_trackSocial', 'Twitter', 'Follow', document.title]);
        }

        // Google Plus One
        if ($(this).parents('div#plusone').length > 0) {
            _gaq.push(['_trackSocial', 'Google', 'Plus One', document.title]);
        }

        // YouTube Follow
        if (this.id == 'youtubeLink') {
            _gaq.push(['_trackSocial', 'YouTube', 'Follow', document.title]);
        }

        // Download PDF
        if (this.href.match(/.pdf/)) {
            _gaq.push(['_trackEvent', 'Download', 'PDF', (this.title != "") ? this.title : this.href]);
        }
    });

    initFormValidation();
    $digi.carouselSlider.init();

    $('.faqCont .header a').bind('click', function (e) {
        e.preventDefault();
        $digi.faqSlider.startSlide(this);
    });

    $('select').not('.multiple, .proNavSelect').sb({
        fixedWidth: true
    });

    /** featured trailers carousel */
    if ($('.carousel').length) {
        $(".carousel").jCarouselLite({
            btnNext: ".next",
            btnPrev: ".previous",
            scroll: 5,
            visible: 5,
            easing: "easeOutExpo",
            speed: 800
        });
    }
    $('#featuredTrailersModule .carousel a').bind('click', function (e) {
        if (mmgIntroPlaying) return false;
        var source = this.href;
        e.preventDefault();
        $('#playerContainer iframe').attr('src', source);
        $('#trailerCalloutLink,#trailerCalloutBackground').css('visibility', 'visible');
        if ($(this).attr('data-title') != '') {
            if ($(this).attr('data-callout-link') != '') {
                $('#trailerCalloutLink').html($(this).attr('data-title') + '&nbsp;&nbsp;' + unescape($(this).attr('data-callout-link')));
            }
            else {
                $('#trailerCalloutLink').html($(this).attr('data-title'));
            }
        }
    });

    $('a.fauxDropDown').each(function () {
        dropDown = Object.create($digi.ribbon);
        dropDown.init(this, '#' + this.getAttribute('data-expander'));
        dropDown.onclick = function () {
            return false;
        };
        $('.expander a', this.parentNode).bind('click', function () {
            if (this.getAttribute('data-inputUpdate')) {
                dropDown.onclick();
                return false;
            }
        });
    });

    // setup ribbon sub nav
    ribbonNav = Object.create($digi.ribbon);
    searchInput = Object.create($digi.ribbon);
    ribbonNav.init('a.navigatorLinks', '.ribbonNavInner', true);
    searchInput.init('a.searchOpenClose', '#searchInputBox', true);

    if ($('.tabs')) {
        $digi.tabs.init('.tabTwoColumnModule .tabs a');
    }

    if ($('.actuator').length) {
        $('.actuator').bind('click', function () {
            $digi.expander(this.getAttribute('data-actuator'), this.rel);
            return false;
        });
    }

    if ($('a.modalLink').length) {
        $digi.modals.init();
    }
    if ($('.flyoutTrigger').length) {
        $digi.tooltip.init('.flyoutTrigger');
    }
    if ($('.featuredAreaRotatorModule').length) {
        slideshow = $digi.slideshow.init({
            auto: false,
            elSelector: '.featuredAreaRotatorModule'
        });
    }

    $('input[type="text"]').each(function () {
        var defaultValue = this.defaultValue;
        $(this)
            .bind('focus', function () {
                if (this.value == defaultValue) {
                    this.value = '';
                }
            })
            .bind('blur', function () {
                if (this.value == '') {
                    this.value = defaultValue;
                }
            });
    });

    if (typeof loginUrls !== 'undefined') {
        resourceCenterSelect = $('#centerChoice').bind('change', function () {
            $digi.updateLoginForm(this);
        });
        if (resourceCenterSelect.val()) {
            $('.extendedForm').css('display', 'block');
        }
    }
    /** handle drop down navigaton on the professional pages */
    if ($('.proNavModule select').length) {
        $('.proNavModule select').each(function () {
            this.selectedIndex = 0;
            this.onchange = function () {
                var newUrl = this.options[this.selectedIndex].value || false;
                if (newUrl) {
                    window.location = newUrl;
                }
            };
        });
    }

    //$digi.mmgFilter.init();

    function skipIntro() {
        $('#introSkipBtn').hide();
        mmgIntroPlaying = false;
        $('#playerContainer').html('<iframe src="" width="640" height="360" scrolling="no" frameborder="0" style="display: none;" webkitAllowFullScreen allowFullScreen>');
        $('#featuredTrailersModule .carousel a.first').trigger('click');
        $('#playerContainer iframe').load(function () {
            $(this).css({
                display: 'block'
            });
        });
    }

    // don't load jplayer unless settings object is set
    if ((typeof jPlayerOpts !== 'undefined') && jCore.readCookie("skipMMGIntro") === false) {

        $('#playerContainer').jPlayer({
            ready: function () {
                $(this).jPlayer("setMedia", jPlayerOpts.media).jPlayer('play');

                if (navigator.userAgent.indexOf("iPad") != -1) {
                    $('.jp-video-play').bind('click', function () {
                        $(this).hide();
                        $('#playerContainer').jPlayer('play');
                        // Set skip intro cookie
                        jCore.writeCookie("skipMMGIntro", "true", 1);
                    }).show();
                }
                else {
                    $('#playerContainer').jPlayer('play');
                    // Set skip intro cookie
                    jCore.writeCookie("skipMMGIntro", "true", 1);
                }

                mmgIntroPlaying = true;
                $('#introSkipBtn').show();
            },
            swfPath: "/media/flash",
            supplied: jPlayerOpts.supplied,
            size: {
                width: "640px",
                height: "360px",
                cssClass: "jp-video-360p"
            },
            ended: function () {
                skipIntro();
            }
        });

        $('#introSkipBtn').bind('click', function () {
            skipIntro();
        });
    }
    // SKIP MMG INTRO
    else {
        skipIntro();
    }
});


