/**
 * Core TWP JavaScript Famework
 * @version 1.0
 * @author Jesse Foltz
 * @author David Johnson
 * @author Chris Kankel
 * @author Steven King
 * @author Larry Landerson
 * @author Chad Shryock
 * @author Lee Trout
 */
var TWP = window.TWP || {}

TWP_tmp = {

    version : '1.0.0',
    debug : false,


    // A registry of objects in the framework
    registry : [],

    /**
     *
     * Creates a new namespace.
     * @param ns (String) A fully qualified namespace (parent ns must be included)
     * @return Object A new namespaces object
     */
    namespace : function(ns){

        // This function should accept multiple ns arguments

        if(!ns || !ns.length){
            return null;
        }

        var twp_2 = ns.split(".");
        var twp_3 = TWP;

        for(var i=(twp_2[0]=="TWP")?1:0;i<twp_2.length;++i){
            twp_3[twp_2[i]] = twp_3[twp_2[i]] || {};
            twp_3 = twp_3[twp_2[i]];
        }

        return twp_3;

    },

    /**
     * Creates a new object
     * @param parent (Object) The parent the newly returned object inherits from
     * @return Object A new "subclass" object
     */
    createObject : function(parent){
        var F = function(){};
        F.prototype = parent || {};
        return new F();
    },

    /**
     * Creates a new object with the signature of the "parent"
     * @param parent (Object) The parent the newly returned object inherits from
     * @return Object A new "subclass" object
     */
    extend : function(o){
        var F = function(){};
        F.prototype = o || {};
        return new F();
    },

    memoize : function(){

    },

    /**
     * Registers a new object
     * @param name (String) The name of the object
     * @param objClass (Object) The object "class" to be registered
     */
    register : function(name, objClass){

        if(!this.registry[name]){
            this.registry[name] = {}
        }

        var module = this.registry[name];
        module.name = name
        module.objClass = objClass;

        TWP.log(name + " added to registry.");
    },

    /**
     * Gets a new instance of a class in the registry
     * @param name (String) The name of the object that was used to register it
     * @return Object A new instance of the requested object
     */
    get : function(name) {
        var temp = TWP.registry[name].objClass;
        if (typeof temp == 'object') {
            return temp;
        }
        return new temp();
    },

    /**
     * Looks for debug=true in the request url
     */
    requestDebug : function() {
        if (window.location.href.indexOf('debug=true') != -1) {
            this.debug = true;
        }
    },

    /**
     * Prints out a div at the bottom of the <body> with information about the registry
     */
    showInfo : function() {
        // TODO create a <div> at the bottom of the <body> printing out a table of registry information
    },

    log : function(message, exceptionObject) {
        try {
            if (this.debug) {
                if (exceptionObject) {
                    console.log(message + ' %o', exceptionObject);
                } else {
                    console.log(message);
                }
            }
        } catch (e) {
        }
    }
};
for (var key in TWP_tmp) {
    TWP[key] = TWP_tmp[key];
}
TWP_tmp = null;

// Look for debug flag
TWP.requestDebug();

// create core namespaces
TWP.namespace("Util");
TWP.namespace("Plugin");
TWP.namespace("Page");
TWP.namespace("Module");
TWP.namespace("Events");
/**
 * Core TWP Util Object
 * @version 1.0
 * @author Jesse Foltz
 * @author David Johnson
 * @author Chris Kankel
 * @author Steven King
 * @author Larry Landerson
 * @author Chad Shryock
 * @author Lee Trout
 */
TWP.Util = {
    version : '1.0.0'
};

/**
 * Core TWP Module Object
 * @version 1.0
 * @author Jesse Foltz
 * @author David Johnson
 * @author Chris Kankel
 * @author Steven King
 * @author Larry Landerson
 * @author Chad Shryock
 * @author Lee Trout
 */
TWP.Module = {

    version : '1.0.0',

    counter : 1000,

    referenceNameLookup : [],

    /**
     * Gets a new Instance of an Object in the registry
     * @param name (String) The name of the object
     * @param args (Object) With values to pass to the new instance
     * @return Object A new instance of the request Object
     */
    get : function(name, args) {
        try {
            // Generate the reference Id
            var ref = name + "." + this.getUID();

            // Get the base object from the TWP registry
            var temp = TWP.registry[name];

            // Get the Object from the registry object
            var obj = temp.objClass;

            // Create the instance Array if it doesn't exist'
            if (temp.instance == undefined) {
                temp.instance = [];
            }

            // Create a new instance of the object
            var instance = new obj(args);
            instance.instanceId = ref;

            // Put the new instance in the registry
            temp.instance[ref] = instance;

            // Register this instance with the referenceNameLookup Array
            this.referenceNameLookup[ref] = name;

            return instance;
        } catch (e) {
            TWP.log('Error getting a new instance for ' + name, e);
        }
    },

    /**
     * Gets an Instance on an Object from the TWP registry
     * @param instanceId (String) The instanceId of an object when created by TWP.Module.get()
     * @return Object The requested instance of an Object
     */
    getInstance : function(instanceId) {
        return TWP.registry[this.references[instanceId]].instance[instanceId];
    },

    /**
     * Generates a Unique Id
     * @return int A unique id
     */
    getUID : function() {
        return this.counter++;
    }
};

TWP.Util.HeaderDetection = function() {
    this.setUserAgent(navigator.userAgent);
    this.getCssClass();
};

TWP.Util.HeaderDetection.prototype = {

    chrome : false,
    opera : false,
    firefox : false,
    firefox2 : false,
    firefox3 : false,
    firefox3_5 : false,
    ie : false,
    ie6 : false,
    ie7 : false,
    ie8 : false,
    mozilla : false,
    safari : false,
    safari3 : false,
    safari4 : false,
    windows : false,
    mac : false,
    linux : false,

    getCssClass : function() {
        if (document.getElementById && document.createTextNode) {
            var n = document.body;
            if (!n || n == undefined || n == null || n.length == 0) {
                setTimeout(function() {
                    var o = TWP.get('Util.HeaderDetection');
                    o.getCssClass();
                }, 250);
                return;
            }
        } else {
            TWP.log("Browser doesn't support document.getElementById()");
            return;
        }

        this.addClass('javascript');
        
        if (this.windows) {
            this.addClass('windows');
        } else if (this.mac) {
            this.addClass('mac');
        } else if (this.linux) {
            this.addClass('linux');
        }

        if (this.ie) {
            this.addClass('ie');
            if (this.ie8) {
                this.addClass('ie8');
            } else if (this.ie7) {
                this.addClass('ie7');
            } else if (this.ie6) {
                this.addClass('ie6');
            }
        } else if (this.firefox) {
            this.addClass('firefox');
            if (this.firefox3_5) {
                this.addClass('firefox3-5');
            } else if (this.firefox3) {
                this.addClass('firefox3');
            } else if (this.firefox2) {
                this.addClass('firefox2');
            }
        } else if (this.safari) {
            this.addClass('safari');
            if (this.safari4) {
                this.addClass('safari4');
            } else if (this.safari3) {
                this.addClass('safari3');
            }
        } else if (this.chrome) {
            this.addClass('chrome');
        } else if (this.opera) {
            this.addClass('opera');
        } else if (this.mozilla) {
            this.addClass('mozilla');
        }
    },

    isChrome : function() {
        return this.chrome;
    },

    isOpera : function() {
        return this.opera;
    },

    isFirefox : function() {
        return this.firefox;
    },

    isFirefox2 : function() {
        return this.firefox2;
    },

    isFirefox3 : function() {
        return this.firefox3;
    },

    isFirefox3_5 : function() {
        return this.firefox3_5;
    },

    isIe : function() {
        return this.ie;
    },

    isIe6 : function() {
        return this.ie6;
    },

    isIe7 : function() {
        return this.ie7;
    },

    isIe8 : function() {
        return this.ie8;
    },

    isMozilla : function() {
        return this.mozilla;
    },

    isSafari : function() {
        return this.safari;
    },

    isSafari3 : function() {
        return this.safari3;
    },

    isSafari4 : function() {
        return this.safari4;
    },

    isWindows : function() {
        return this.windows;
    },

    isMac : function() {
        return this.mac;
    },

    isLinux : function() {
        return this.linux;
    },

    setUserAgent : function(ua) {
        this.userAgent = ua;
        var u = ua.toLowerCase()

        var t = '';
        var v = '';

        if (u.indexOf("msie") != -1){
            this.ie = true;
            t = u.substring(u.indexOf('msie'), u.length);
            v = t.substring(4, t.indexOf(';'));
            v = this.trim(v);

            if (v.charAt(0) == '6') {
                this.ie6 = true;
            } else if (v.charAt(0) == '7') {
                this.ie7 = true;
            } else if (v.charAt(0) == '8') {
                this.ie8 = true;
            }
        } else if (u.indexOf("firefox") != -1) {
            this.firefox = true;
            t = u.substring(u.indexOf('firefox'));
            v = t.substring(8);
            v = this.trim(v);

            if (v.charAt(0) == '2') {
                this.firefox2 = true;
            } else if (v.charAt(0) == '3') {
                if (v.match("^" + '3.5') == '3.5') {
                    this.firefox3_5 = true;
                } else {
                    this.firefox3 = true;
                }
            }
        } else if (u.indexOf("safari") != -1) {
            this.safari = true;
            t = u.substring(u.indexOf('version/'));
            v = t.substring(8);
            v = this.trim(v);

            if (v.charAt(0) == '3') {
                this.safari3 = true;
            } else if (v.charAt(0) == '4') {
                this.safari4 = true;
            }
        } else if (u.indexOf("chrome") != -1) {
            this.chrome = true;
        } else if (u.indexOf("opera") != -1) {
            this.opera = true;
        } else if (u.indexOf("mozilla") != -1) {
            this.mozilla = true;
        }

        if (u.indexOf("windows") != -1) {
            this.windows = true;
        } else if (u.indexOf("macintosh") != -1) {
            this.mac = true;
        } else if (u.indexOf("linux") != -1) {
            this.linux = true;
        }
    },

    addClass : function(c) {
        if(document.getElementById && document.createTextNode) {
            var n = document.body;
            if(n) {
                n.className += n.className ? ' ' + c : c;
            }
        }
    },

    trim : function(str) {
        return (str.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""));
    }

};

TWP.register('Util.HeaderDetection', new TWP.Util.HeaderDetection());
/**
 * Modified from a script found below:
 * @see: http://remysharp.com/2009/01/07/html5-enabling-script/
 */
TWP.Util.HTML5IEFix = function(args) {
    var btd = TWP.get("Util.HeaderDetection");
    if (btd.isIe()) {
        this.tags = this.tagsString.split(',');
        this.tags = this.tags.concat(this.customTagsString.split(','));
        this.fix();
    }
};

TWP.Util.HTML5IEFix.prototype = {

    customTagsString : "by,clear,column,content,display-block,displaytype,id,ip,pill,text",

    tagsString : "abbr,article,aside,audio,bb,canvas,datagrid,datalist,details,dialog,eventsource,figure,footer,header,hgroup,mark,menu,meter,nav,output,progress,section,time,video",

    fix : function() {
        var i = this.tags.length;
        while(i--){
            document.createElement(this.tags[i]);
        }
    }
};

TWP.register("Util.HTML5IEFix", new TWP.Util.HTML5IEFix());
TWP.Util.TWPUser = function(args) {
    this.options = args || {};
    this.readCookie();
    this.placeCookie();
};

TWP.Util.TWPUser.prototype = {

    version : '1.0.0',

    cookieUser : null,
    signedIn : false,
    twpUserName : null,
    userType : 'washington-post',

    getCookieUser : function() {
        return this.cookieUser;
    },

    getTwpUserName : function() {
        return this.twpUserName;
    },

    isFacebookUser : function() {
        if (this.userType == 'facebook-connect') {
            return true;
        }
        return false;
    },

    isSignedIn : function () {
        return this.signedIn;
    },

    readCookie : function() {
        var start = -1;
        var end = -1
        if (document.cookie.indexOf("fbuname") != -1) {
            this.userType = 'facebook-connect';
            this.signedIn = true;
            start = (document.cookie.indexOf("fbuname") + 8);
            end = (document.cookie.indexOf(";",start)) == -1 ? document.cookie.length : document.cookie.indexOf(";",start);
            this.twpUserName = document.cookie.substring(start,end);
        } else if (document.cookie.indexOf("wpniuser") != -1) {
            this.userType = 'washington-post';
            this.signedIn = true;
            start = (document.cookie.indexOf("wpniuser") + 9);
            end = (document.cookie.indexOf(";",start)) == -1 ? document.cookie.length : document.cookie.indexOf(";",start);
            this.cookieUser = document.cookie.substring(start,end);
            if(this.cookieUser.indexOf("@") != -1) {
                this.twpUserName = this.cookieUser.substring(0, this.cookieUser.indexOf("@"));
            } else {
                this.twpUserName = this.cookieUser;
            }
        }
    },

    /**
     * Places a universal persistent cookie
     */
    placeCookie : function() {
        var upc_url = new String(document.location.href) ;
        if (upc_url.indexOf(".washingtonpost.com") > -1) {
            var c = document.cookie;
            var pos = c.indexOf("WPNIUCID");
            if (pos == -1) {
                var d = new Date();
                var i = "WPNI"+ d.getTime() +"."+ Math.round(Math.random()*10000);
                d.setTime(d.getTime() + 31104000000);
                document.cookie = "WPNIUCID="+ i +
                "; expires="+ d.toGMTString() +
                "; path=/"+
                "; domain=.washingtonpost.com";
            }
        }
    }
};

TWP.register('TWP-User', new TWP.Util.TWPUser());
// <summary>Interval object, property of the window object</summary>
// <param name="delay">Delay of the interval, default is 1 sec.</param>
Interval = function(delay){
	this.delay = delay || 1000;
	this.timeout = null;
	this.bindable = jQuery(this);
}


// <summary>Event listener of Interval object</summary>
// <param name="event">The event to occur</event>
// <param name="callback">The callback to occur once the event has completed</event>
Interval.prototype.listen = function(event, callback){
	this.bindable.bind(event, callback);
}

// <summary></summary>
// <param name=""></event>


// <summary>Sets the delay for the interval occurence</summary>
// <param name="delay">The delay for the interval in milliseconds</event>
Interval.prototype.setDelay = function(delay){
	this.delay = delay;
}

// <summary>Starts the interval</summary>
// <param name="now">???</event>
Interval.prototype.start = function(now){
	if(!this.timeout){
		this.scheduleUpdate();
	}
}

// <summary>Resets the interval</summary>
// <param name="now">???</event>
Interval.prototype.restart = function(now){
	this.stop();
	this.start();
}

// <summary>Stops the interval</summary>
// <param name="now">???</event>
Interval.prototype.stop = function(now){
	if(this.timeout){
		clearTimeout(this.timeout);
		this.timeout = undefined;
	}
}


// <summary>Schedules an update for the interval</summary>
// <param name=""></event>
Interval.prototype.scheduleUpdate = function(){
	var self = this;
	this.timeout = setTimeout(function(){
		self.scheduleUpdate();
		self.execute();
	}, this.delay);
}

// <summary>Executes the Interval</summary>
// <param name=""></event>
Interval.prototype.execute = function(){
	this.bindable.trigger('run');
}

TWP.register("Util.Interval", Interval);
(function(){

    TWP.Module.GlobalHeader = function(){

        var defaults = {
            showWeather : true,
            target : document.getElementById('header-v3'),
            initialized : false,
            headerType : 'default',
            mainNavRoot : document.getElementById('main-nav'),
            mainNavChildren : null,
            navNode : null,
            thisNode : null,
            nodeRoot : null,
            nodeRootChild : null,
            nodeRootChildCategory : null,
            paramList : {},
            nodeMatched : false,
            version : -1,
            browser : null,
            url : window.location.href,
            rootPath : null,
            fileName : null,
            qString : null
        };

        var weather = null;

        // Private Methods
        function getEnvInfo(){
            if (navigator.appName == 'Microsoft Internet Explorer'){
                defaults.browser = "msie";
                var ua = navigator.userAgent;
                var re  = /MSIE ([0-9]{1,}[\.0-9]{0,})/;
                if (re.exec(ua) !== null){
                    defaults.version = parseFloat( RegExp.$1 );
                }
            }

            if(defaults.qString){
                var params = defaults.qString.split("&");

                for(var j=0;j<params.length;j++){
                    var k = params[j].split("=")[0], v = params[j].split("=")[1];
                    defaults.paramList[k] = v;
                }
            }
        }

        // Get children elements
        function getChildren(parent, name){
            var nodes = [];
            for(var r=0;r<parent.childNodes.length;r++){
                if(parent.childNodes[r].nodeType === 1 && parent.childNodes[r].nodeName === name.toUpperCase()){
                    nodes.push(parent.childNodes[r]);
                }
            }
            return nodes;
        }

        // Gets the current date
        function getCurrentDate(){
            var curr = new Date(), day = curr.getDay(), month = curr.getMonth(), date = curr.getDate(), year = curr.getFullYear();
            var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "Decemeber"];
            var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

            var currDate = document.getElementById('current-date');
            
            if(currDate){
                currDate.innerHTML = days[day] + ", " + months[month] + " " + date + ", " + year;
            }
        }


        function setNavContext(){

            if(!defaults.mainNavRoot){
                return;
            }

            // Check by commercial node
            var mainNavRoot = defaults.mainNavRoot;
            var mainSubNavRoot = document.getElementById('main-sub-nav');
            var mainNavChildren = getChildren(mainNavRoot, 'li');
            var subcategoryNav = document.getElementById('main-category-nav-wrapper');

            for(var a=0;a<mainNavChildren.length;a=a+1){
                var item = mainNavChildren[a];
                if(item.getAttribute('data') == defaults.nodeRoot){
                    var currClass = (item.getAttribute('class')) ? item.getAttribute('class') : '';
                    item.className = (currClass !=  '') ? currClass + ' active' : ' active';
                    defaults.nodeMatched = true;
                    break;
                }
                
            }

            if(mainSubNavRoot){
                var mainSubNavChildren = getChildren(mainSubNavRoot, 'li');
                for(var c=0;c<mainSubNavChildren.length;c=c+1){
                    var item = mainSubNavChildren[c];
                    var dataAttr = (item.getAttribute('data')) ? item.getAttribute('data') : '';
                    if(defaults.nodeRootChild && dataAttr == defaults.nodeRootChild){
                        var currClass = (item.getAttribute('class')) ? item.getAttribute('class') : '';
                        item.setAttribute('class', currClass + ' active');
                        break;
                    }
                }
            }

            // Highlight CategoryNode
            if(subcategoryNav){

                subcategoryNav.style.display = "block"

                var ulNodes = getChildren(subcategoryNav, 'ul');
                for (var i=0;i<ulNodes.length;i++){

                    var dataAttr = ulNodes[i].getAttribute("data");

                    if (dataAttr && dataAttr == defaults.nodeRootChild) {
                        ulNodes[i].style.display = "block";
                      
                        var liNodes = getChildren(ulNodes[i], 'li');

                        for (var j=0;j<liNodes.length;j++) {
                            if (liNodes[j].getAttribute("data") == defaults.nodeRootChildCategory){
                                var currClass = (liNodes[i].getAttribute('class')) ? liNodes[j].getAttribute('class') : '';
                                liNodes[j].className = 'active';
                                
          
                            }
                        }
                    }
                }


                var mainSubNavChildren = getChildren(mainSubNavRoot, 'li');
                for(var c=0;c<mainSubNavChildren.length;c=c+1){
                    var item = mainSubNavChildren[c];
                    var dataAttr = (item.getAttribute('data')) ? item.getAttribute('data') : '';
                    if(defaults.nodeRootChild && dataAttr == defaults.nodeRootChild){
                        var currClass = (item.getAttribute('class')) ? item.getAttribute('class') : '';
                        item.className = 'active';
                        break;
                    }
                }
            }
        }

        function setBranding(){
            var logo = document.getElementById('logo');
            var logoChildren = getChildren(logo, 'a');

            if(defaults.nodeRoot == 'politics'){
                logo.className = defaults.nodeRoot;
                logoChildren[0].setAttribute('href', 'http://www.washingtonpost.com/politics');
            } else if (defaults.nodeRoot == 'business') {
                logo.className = defaults.nodeRoot;
                logoChildren[0].setAttribute('href', 'http://www.washingtonpost.com/business');
            } else if (defaults.nodeRoot == 'local') {
                logo.className = defaults.nodeRoot;
                logoChildren[0].setAttribute('href', 'http://www.washingtonpost.com/local');
            } else if (defaults.nodeRoot == 'national') {
                logo.className = defaults.nodeRoot;
                logoChildren[0].setAttribute('href', 'http://www.washingtonpost.com/national');
            }
        }

        function addEvent(el, evt, callback, cap){
            if(el && evt){
                if(el.addEventListener){
                    el.addEventListener(evt, callback, cap);
                } else {
                    evt = (evt == 'mouseover') ? 'mouseenter' : evt;
                    evt = (evt == 'mouseout') ? 'mouseleave' : evt;
                    el.attachEvent('on' + evt, callback);
                }
            }
        }

        function removeEvent(el, evt, callback, cap){
            if(el && evt){
                if(el.removeEventListener){
                    el.removeEventListener(evt, callback, cap);
                } else {
                    evt = (evt == 'mouseover') ? 'mouseenter' : evt;
                    evt = (evt == 'mouseout') ? 'mouseleave' : evt;
                    el.detachEvent('on' + evt, callback);
                }
            }
        }

        function setAuthenticationLinks(){
            // Determine if the user is authenticated, show the proper creds
            var signin = document.getElementById('global-signin');
            var registration = document.getElementById('global-registration');
            var userName = null;
            var pref = ' | <a href="http://www.washingtonpost.com/ac2/wp-dyn?node=admin/registration/manage&destination=manage&nextstep=gather">Change Preferences</a>';

            if(signin && registration){
                if(TWP.Util.User.getAuthentication()){
                    userName = TWP.Util.User.getUserName();

                    // User is signed in
                    if(TWP.Util.User.getUserType() == 'fbuname'){
                        var html = '<span class="icon facebook sm"><a href="http://www.washingtonpost.com/wp-srv/community/mypost/index.html?newspaperUserId=' + userName + '">' + userName + '</a></span>';
                        if(defaults.nodeRoot == 'mypost'){
                            html += pref;
                        }

                        signin.innerHTML = html;
                        registration.innerHTML = '<a href="http://www.washingtonpost.com/ac2/wp-dyn?node=admin/registration/login&destination=logout&nextstep=confirm">Sign Out</a>';
                        return;
                    }

                    var html = '<span>Hello</span> <a href="http://www.washingtonpost.com/wp-srv/community/mypost/index.html?newspaperUserId=' + userName + '">' + userName + '</a>';
                    if(defaults.nodeRoot == 'mypost'){
                        html += pref;
                    }

                    signin.innerHTML = html;
                    registration.innerHTML = '<a href="http://www.washingtonpost.com/ac2/wp-dyn?node=admin/registration/login&destination=logout&nextstep=confirm">Sign Out</a>';
                } else {
                    signin.innerHTML = '<a href="http://www.washingtonpost.com/ac2/wp-dyn?node=admin/registration/register&destination=login&nextstep=gather&application=reg30-globalnav&applicationURL=' + defaults.url + '">Sign In</a>';
                    registration.innerHTML = '<a href="http://www.washingtonpost.com/ac2/wp-dyn?node=admin/registration/register&destination=register&nextstep=gather&application=reg30-globalnav&applicationURL=' + defaults.url + '">Register Now</a>';
                }
            }
        }

        // Sets up user tools
        function setupUserTools(){
            // Tools menu
            var userTools = document.getElementById('user-tools');
            var utilityWrapper = document.getElementById('utility-wrapper');
            var userToolsActive = false;
            var openTimer = null;
            var closeTimer = null;
            var listItems = getChildren(userTools, 'li');

            function onExpand(){
                addEvent(userTools, 'mouseout', hideTools, true);
            }

            function onCollapse(){
                for(var c=0;c<userTools.childNodes.length;c=c+1){
                    if(userTools.childNodes[c].nodeName == "LI"){
                        var listItem = userTools.childNodes[c];

                        if(listItem.className != ""){
                            listItem.className = (listItem.className).replace('selected', '');
                        }
                    }
                }

                addEvent(userTools, 'mouseover', showTools, false);
            }

            function showTools(e){
                removeEvent(userTools, 'mouseover', showTools, false);

                if(!e){
                    var e = window.event;
                }
                e.cancelBubble = true;

                if (e.stopPropagation){
                    e.stopPropagation();
                }

                if(userToolsActive){
                    clearTimeout(closeTimer);
                    closeTimer = null;
                    return false;
                }

                var setup = {
                    target : utilityWrapper,
                    speed : 300,
                    height : 50,
                    callback : onExpand
                };

                if(!openTimer){
                    openTimer = setTimeout(function(){
                        if(!userToolsActive && utilityWrapper.getAttribute('style') != ''){
                            userToolsActive = true;
                            animate(setup);
                        }
                        openTimer = null;
                    }, 1000);
                } else {
                    clearTimeout(openTimer);
                    openTimer = null;
                }
                return false;
            }

            function hideTools(e){
                var oldRelated = e.relatedTarget;
                var related = e.relatedTarget;
                // Traverse up the tree
                while (related && related != userTools){
                    try {
                        related = related.parentNode;
                    } catch(ex) {
                        related = userTools;
                    }
                }
                if(oldRelated === related || related === null){
                    setup = {
                        target : utilityWrapper,
                        speed : 300,
                        height : 23,
                        callback : onCollapse
                    };

                    closeTimer = setTimeout(function(){
                        if(userToolsActive){
                            removeEvent(userTools, 'mouseout', hideTools, true);
                            animate(setup);
                            userToolsActive = false;
                        }
                    }, 1000);
                } else {
                    return false;
                }
            }

            if(userTools){
                addEvent(userTools, 'mouseover', showTools, false);

                function addSelected(e){
                    if(!e){
                        var e = window.event;
                    }

                    for(var c=0;c<listItems.length;c=c+1){
                        var listItem = listItems[c];
                        if(listItem.className != ""){
                            listItem.className = (listItem.className).replace('selected', '');
                        }
                    }

                    var node = (e.target) ? e.target.parentNode : e.srcElement.parentNode;
                    while (node && node.nodeName != "LI"){
                        node = node.parentNode;
                    }
                    node.className = "selected";
                }

                for(var j=0;j<listItems.length;j=j+1){
                    var li = listItems[j];
                    var anchor = getChildren(li, 'A')[0];
                    addEvent(anchor, 'mouseover', addSelected, false);
                }
            }
        }


        function moveSingleVal(currentVal, finalVal, frameAmt){
            if(frameAmt === 0 || currentVal === finalVal){
                return finalVal;
            }

            currentVal += frameAmt;
            if((frameAmt> 0 && currentVal>= finalVal) || (frameAmt <0 && currentVal <= finalVal)){
                return finalVal;
            }

            return currentVal;
        }

        function doFrame(el, currHt, ht, fHt, callback){
            if(el === null){
                return;
            }
            currHt = moveSingleVal(currHt, ht, fHt);

            if(defaults.browser == 'msie' && defaults.version < 8){
                el.style.height = Math.round(currHt);
            } else {
                el.setAttribute('style', 'height:' + Math.round(currHt) + 'px;');
            }

            if(currHt == ht){
                if(callback !== null){
                    callback();
                }
                return;
            }

            setTimeout(function(){
                doFrame(el, currHt, ht, fHt, callback);
            }, 40);
        }

        function animate(config){
            var el = config.target;
            var speed = config.speed;
            var ht = config.height;
            var currHt = (el.offsetHeight) ? el.offsetHeight : el.style.pixelHeight;
            var totalFrames = 1;
            var callback = config.callback;

            if(speed>0){
                totalFrames = speed/40;
            }

            var fHt = ht - currHt;
            if(ht!==0){
                fHt /= totalFrames;
            }

            doFrame(el, currHt, ht, fHt, callback);
        }

        function setupWeather(){
            weather = new TWP.Module.GlobalWeather();
        }

        // END: Private Methods


        // BEGIN: Set everything up
        getEnvInfo();

        var nodeHierarchy = null;

        // Determine where we are in the heirarchy by nodes
        if(window.thisNode){
            defaults.thisNode = window.thisNode;
        }
        
        if(window.navNode || window.commercialNode){
            defaults.navNode = window.navNode || window.commercialNode;
           

            if(defaults.navNode.indexOf("/")){
                nodeHierarchy = defaults.navNode.split("/");
            }

            if(nodeHierarchy.length){
                defaults.nodeRoot = nodeHierarchy[0];
                if(nodeHierarchy.length > 1){
                    defaults.nodeRootChild = nodeHierarchy[1];
                    if (nodeHierarchy.length > 2) {
                        defaults.nodeRootChildCategory = nodeHierarchy[2];
                    }
                }
            } else {
                defaults.nodeRoot = nodeHierarchy;
            }
        }


        // Initialize the user, available globally
        TWP.Util.User.init();

        // Set global authentication links
        setAuthenticationLinks();

        // Initialize drop menu in IE
        if(defaults.browser == 'msie'){
            setup = {
                target : document.getElementById('main-nav')
            };
            TWP.Util.DropDownMenuIE(setup);
        }

        // Set the navigation context
        setNavContext();

        // set branding
        setBranding();

        if(defaults.showWeather && document.getElementById('global-weather')){
            setupWeather();
        }

        // Get current date
        getCurrentDate();
    };
})();
(function(){

    TWP.Util.Cookie = function(){

        return {

            // Gets the cookie for the domain
            get : function(){
                return document.cookie;
            },

            /// <summary>Gets the value of the a cookie by name</summary>
            /// <param name="name" type="string">The name of the cookie</param>
            /// <returns>The name's value</returns>
            read : function(name){

                if(!name){
                    return null;
                }

                if(document.cookie.length > 0){

                    var strStart = name + "=";
                    var cookieSplit = document.cookie.split(";");

                    for(var b=0;b<cookieSplit.length;b++){

                        var c = cookieSplit[b];
                        c = (c).replace(/^(\s|\u00A0)+|(\s|\u00A0)+$/g, '');
                        
                        if(c.charAt(0) != ''){ // trim whitespace
                            c = c.substring(0, c.length);

                            if(c.indexOf(strStart) == 0){
                                return c.substring(strStart.length, c.length);
                            }
                        }

                    }
                }

                return null;
            },

            /// <summary>Sets a cookie</summary>
            /// <param name="name" type="string">The name of the cookie</param>
            /// <param name="value" type="string">The value for the cookie</param>
            /// <param name="path" type"string"></param>
            /// <param name="expires" type"object">When the cookie will expire, defaults to 30 days</param>
            /// <param name="domain" type="string"></param>
            /// <returns></returns>
            create : function(name, value, path, expires, domain){
                var cookieVal = "";

                if(!name && !expires && !value){
                    return;
                }

                if (!expires) {
                    var d = new Date();
                    d.setTime(d.getTime() + (30*24*60*60*1000));
                    expires = d;
                }

                cookieVal = name + "=" + value + "; expires=" + expires.toGMTString();

                if(path){
                    cookieVal += "; path=" + path;
                }

                if(domain){
                    cookieVal += "; domain=" + domain;
                }

                document.cookie = cookieVal;

            },

            /// <summary>Removes a cookie</summary>
            /// <param name="name">The name of the cookie to remove</param>
            /// <returns></returns>
            remove : function(name){
                this.set(name, "", -1);
            }
        }
    }();
})();

(function(){

    TWP.Util.User = function(){
        var initialized = false;
        var isAuthenticated = false;
        var userName = null;
        var userId = "";
        var userCookie = null;
        var isFacebookUser = false;
        var userType = "washington-post";
        var validCookies = ["fbuname", "wpniuser"];

        function parseCookieUserName(cookie, startStr, offset){
            var start = -1, end = -1;
            start = (cookie.indexOf(startStr) + offset);
            end = (userCookie.indexOf(";", start)) == -1 ? userCookie.length : userCookie.indexOf(";",start);

            return cookie.substring(start, end);
        }

        function setCustomCookie(){
            var upcUrl = document.location.href;

            if(upcUrl.indexOf("localhost") > -1){
                var c = TWP.Util.Cookie.get();

                if(c.indexOf("WPNIUCID") == -1){
                    var d = new Date();
                    var i = "WPNI" + d.getTime() + "." + Math.round(Math.random()*10000);
                    d.setTime(d.getTime() + 31104000000);
                    TWP.Util.Cookie.create("WPNIUCID", i, "/", d, ".washingtonpost.com");
                }
            }
        }

        return {
            // Determine whether the user has the appropriate cookie
            init : function(){

                if(initialized){
                    return;
                }

                initialized = true;

                var userCookieName = "";

                // START: TEST
                // add a cookie for testing
                //TWP.Util.Cookie.create("headzip", "20009", "/");
                // END: TEST

                for(var a=0;a<validCookies.length;a++){
                    if(document.cookie.indexOf(validCookies[a]) != -1){
                        userCookie = document.cookie;
                        userType = validCookies[a];
                        isAuthenticated = true;
                        break;
                    }
                }

                if(isAuthenticated){
                    switch(userType){
                        case 'fbuname' :
                            userCookieName = parseCookieUserName(userCookie, userType, 8);
                            break;
                        default :
                            userCookieName = parseCookieUserName(userCookie, userType, 9);
                            break;
                    }

                    userName = (userCookieName.indexOf("@") !== -1) ? userCookieName.substring(0, userCookieName.indexOf("@")) : userCookieName;
                    userId = userCookieName;
                }

                setCustomCookie();
            },

            getUserCookie : function(){
                return (userCookie.length > 0 && typeof userCookie == "string") ? userCookie : null;
            },

            getUserType : function(){
                return (userType.length > 0 && typeof userType == "string") ? userType : null;
            },

            getUserId : function(){
                return userId;
            },

            getUserName : function(){
                return (typeof userName == "string") ? userName : "";
            },

            getAuthentication : function(){
                return isAuthenticated;
            }
        }

    }();
})();

/* Utility for returning commom url attributes */
TWP.Util.Url = {

    /// <summary>Returns the paramters as an object, key=>value pairs</summary>
    /// <param name="url" type="string">The url to be parsed</param>
    /// <returns>An object</returns>
    getParameters : function(url){
        var paramList = [], params = {}, kvPairs, tmp;

        url = (url !== '' && typeof url === 'string') ? url : document.URL;

        if(url){
            if(url.indexOf("?") !== -1){
                paramList = url.split("?")[1];

                if(paramList){
                    if(paramList.indexOf("&")){
                        kvPairs = paramList.split("&");
                    } else {
                        kvPairs = [paramList];
                    }

                    for(var a=0;a<kvPairs.length;a++){
                        if(kvPairs[a].indexOf("=") !== -1){
                            tmp = kvPairs[a].split("=");
                            params[tmp[0]] = unescape(tmp[1]);
                        }
                    }
                }
            }
        }
        
        return (params) ? params : null;
    },

    getUrl : function(){
        return window.location.href || document.url;
    },

    getRootPath : function(){
        return this.getProtocol() + "//" + this.getHost() + this.getPathName();
    },

    getSubDomain : function(){

    },

    getTopLevelDomain : function(){
        return window.document.domain;
    },

    getHost : function(){
      return window.location.host;
    },

    getHostName : function(){
        return window.location.hostname;
    },

    getProtocol : function(){
        return window.location.protocol || window.document.protocol;
    },

    getPort : function(){
        return window.location.port;
    },

    getHash : function(){
        return window.location.hash;
    },

    getPathName : function(){
        return window.location.pathname;
    },

    getFileName : function(){

    },

    getFileNameExtension : function(){

    },

    isSSL : function(){
        var isSSL = false;

        if(this.getProtocol().indexOf('https://') !== -1){
            isSSL = true;
        }

        return isSSL;
    }
};
// Supports the new global masthead v3.0.0, because some pages still in quirks and CSS menus will not work in IE6+
(function(){

	TWP.Util.DropDownMenuIE = function(setup){
		var config = setup;
		var html = null;
		var ctx = null;

		if(config.target){
			ctx = config.target;
		}

        var currTarget;

		bindNav();


        function addClass(e){

            if(e.stopPropagation){
                e.stopPropagation();
            }
            e.cancelBubble = true;

            var self = currTarget =  e.srcElement;

            if(self.parentNode.className && self.parentNode.className.indexOf('selected') != -1){
                return;
            }

            var itemClass = '';

            if(self.parentNode.className){
                itemClass = self.parentNode.className;
            }

            self.parentNode.className = (itemClass != '') ? itemClass +  ' selected' :  'selected';

            currTarget.parentNode.attachEvent('onmouseleave', removeClass);
        }

        function removeClass(e){

            if(currTarget.parentNode.className != ''){
                currTarget.parentNode.className = (currTarget.parentNode.className).replace('selected', '');
            }

            currTarget.detachEvent(addClass);
        }

		function bindNav(){

            if(ctx){
                var navItems = ctx.childNodes;

                for(var i=0;i<navItems.length;i++){
                    if(navItems[i].nodeName == "LI"){
                        var item = navItems[i];
                        var itemChildNodes = item.childNodes;
                        var len = itemChildNodes.length;
                        for(var j=0;j<len;j++){
                            if(itemChildNodes[j].nodeName == "A"){
                                var anchor = itemChildNodes[j];
                                anchor.attachEvent('onmouseover', addClass);
                                break;
                            }
                        }
                    }
                }
            }
		}
	}
})();
// Wires up a form for basic behaviors and validation
(function(){

    // class
    TWP.Util.Form = function(setup){
        var self = this;
        var config = setup;
        var ctx = null;
        var inputFields = [];
        var restoreFields = [];

        if(!config){
            return;
        }

        if(config.context){
            ctx = config.context;
        }

        // find all restore fields
        var ipt = ctx.getElementsByTagName('input');

        for(var a=0;a<ipt.length;a=a+1){
            if(ipt[a].getAttribute('type') == 'text'){
                inputFields.push(ipt[a]);

                if((ipt[a].className).indexOf('restore') != -1){
                    restoreFields.push(ipt[a]);
                }
            }
        }

        for(var b=0;b<restoreFields.length;b=b+1){
            defaultTextRestore(restoreFields[b]);
        }

        function defaultTextRestore(field){
            var defaultText = field.defaultValue;

            field.onfocus = function(){
                if(this.value == defaultText){
                    this.value = '';
                }

                field.onblur = function(){

                   if(this.value != '' && this.value != defaultText){
                       return;
                   }
                   this.value = defaultText;
                }
            }
        }

        return {
            removeDefaultTextRestore : function(field){

            }
        }
    }

     // find all forms in the DOM and wire them up

     window.onload = function(){
         var forms = document.forms;

         for(var c=0;c<forms.length;c=c+1){
            var self = forms[c];
            var setup = {
               context : self
            }
            new TWP.Util.Form(setup);
         }
     }
})();
TWP.Util.WindowScroll = {

    getScrollTop : function(){
        if (document.documentElement && document.documentElement.scrollTop){
            return document.documentElement.scrollTop;
        } else if (document.body) {
            return document.body.scrollTop;
        } else if (window.pageYOffset) {
            return window.pageYOffset;
        }
        return 0;
    },

    getScrollLeft : function(){
        if (document.documentElement && document.documentElement.scrollLeft){
            return document.documentElement.scrollLeft;
        } else if (document.body) {
            return document.body.scrollLeft;
        } else if (window.pageXOffset) {
            return window.pageXOffset;
        }
        return 0;
    },

    getScrollXY : function(){

        return [this.getScrollLeft(), this.getScrollTop()];
    }
};
(function(){

    TWP.Util.RelativeTime = {

        getRelativeTime : function(date, relativeTo){

            var delta = (relativeTo.getTime() - date.getTime()) / 1000;

            if (delta < 60) {
                return Math.round(delta) + ((delta == 1) ? 'sec' : 'secs') + 'ago';
            } else if (delta == 60) {
                return '1 min ago';
            } else if(delta < (60*60)) {
                return Math.round(delta/60) + ((Math.round(delta/60) == 1) ? ' min' :  ' mins') + ' ago';
            } else if(delta < (120*60)) {
                return '1 hour ago';
            //} else if(delta < (3*60*60)) { // less than four hours
             //   return Math.round(delta / 3600) + ' hours ago';
            //} else if(delta < (24*60*60)) {
                //return 'about ' + Math.round(delta / 3600) + ' hours ago';
            //} else if(delta < (48*60*60)) {
                //return 'yesterday';
            } else if(delta < (4*60*60)) {
                var d = new Date(date);
                var hour = (d.getHours() == 0) ? 12 : ((d.getHours() > 12) ? d.getHours() - 12 : d.getHours());
                var mins = (d.getMinutes() < 10) ? '0' + d.getMinutes() : d.getMinutes();
                var meridiem = (d.getHours() >= 12) ? ' p.m.' : ' a.m.';
                return hour + ":" + mins + meridiem + " ET";
            } else {
                return '';
            }
            //return Math.round(delta / 86400) + ' days ago';
        }
    };
})();
(function(){

    /**
     * Date calculations. By default this class operates on the current
     * timezone offset. Creating it with a different offset allows operations
     * on other time zones.
     */
    TWP.Util.DateCalculator = function(offset){
        var self = this;

        //this.offset = (offset) ? offset : ((new Date()).getTimezoneOffset()) * 60 * 1000;

        this.offset = 0;

        // Takes a number and pads it with leading 0 to the length specified.
        // The padded length does not include negative sign if present.
        function zeroPad(num, nLen){
            var isNegative = (num < 0), s = num.toString();

            if(isNegative){
                s = s.substr(1, s.length);
            }

            while (s.length < nLen){
                s = "0" + s;
            }

            if (isNegative) s = "-" + s;

            return s;
        }

        return {
            // Converts a date to UTC or returns a UTC now.
            newUtcDate : function(date){
                if(!date){
                    date = new Date();
                }

                return new Date(date.getTime() + self.offset);
            },

            // <summary>Converts a date to ISO 8601 format or returns an ISO now</summary>
            // <param name="date" type="object">optional ECMAScript Date object</param>
            // <param name="relative" type="boolean">
            //		timestamp will show local time with a time offset from UTC;
            //   	otherwise the timestamp will show UTC (a.k.a. Zulu) time.
            // </param>
            // <param name="resolution" type="number"></param>
            // <return></return>
            newIso8601Date : function(date, relative, resolution){
                var iso = "";
                var mSecs = cSecs = 0;
                var resolution = 1; // overriding resolution arg

                if(!date){
                    date = new Date();
                }

                // Milliseconds
                if(relative){
                    mSecs = date.getMilliseconds();
                } else {
                    mSecs = date.getUTCMilliseconds();
                }


                // Precision is in centisecond
                if(resolution == 0){
                    if(mSecs > 500){
                        if(relative){
                            date.setMilliseconds(1000);
                        } else {
                            date.setUTCMilliseconds(1000);
                        }
                    }
                } else {
                    if(mSecs > 994){
                        if(relative){
                            date.setMilliseconds(1000);
                        } else {
                            date.setUTCMilliseconds(1000);
                        }
                    } else {
                        cSecs = Math.floor(mSecs/10);
                    }
                }

                // If the date is to be relative to the machine's locale...
                if(relative){
                    iso = date.getFullYear() + '-';
                    iso += zeroPad(date.getMonth(), 2) + '-';
                    iso += zeroPad(date.getDate(), 2) + 'T';
                    iso += zeroPad(date.getHours(), 2) + ':';
                    iso += zeroPad(date.getMinutes(), 2) + ':';
                    iso += zeroPad(date.getSeconds(), 2);
                } else {
                    iso = date.getUTCFullYear() + '-';
                    iso += zeroPad(date.getUTCMonth(), 2) + '-';
                    iso += zeroPad(date.getUTCDate(), 2) + 'T';
                    iso += zeroPad(date.getUTCHours(), 2) + ':';
                    iso += zeroPad(date.getUTCMinutes(), 2) + ':';
                    iso += zeroPad(date.getUTCSeconds(), 2);
                }

                // Pad cSec if needed
                if(cSecs > 0){
                    iso += "." + zeroPad(cSecs, 2);
                }

                // Add timezone offset
                if(relative){
                    var tzOffset = -date.getTimezoneOffset();

                    if(tzOffset >= 0){
                        iso += "+";
                    }

                    iso += zeroPad(Math.round(tzOffset/60), 2);

                    tzOffset = tzOffset % 60;

                    if(tzOffset > 0){
                        s += ":" + zeroPad(tzOffset, 2);
                    }
                } else {
                    iso += "Z";
                }

                return iso;
            },

            // Converts a UTC date to local.
            utcToLocalDate : function(utcDate){
                return new Date(utcDate.getTime() - self.offset);
            },

            // 2008-09-18T22:50:22Z
            parseIso8601Date : function(xmlDate){

                var utc = Date.UTC(
                    xmlDate.substring(0,4),
                    xmlDate.substring(5,7),
                    xmlDate.substring(8,10),
                    xmlDate.substring(11,13),
                    xmlDate.substring(14,16),
                    xmlDate.substring(17,19),
                    xmlDate.substring(20, 22));


                return new Date(utc + self.offset);
            },

            // returns a date as plain date string
            getTimestampAsString : function(date){
                if(!date){
                    date = new Date();
                }

                return date.toString();
            },

            // returns a date as UTC string
            getUtcAsString : function(date){
                if(!date){
                    date = new Date();
                }

                return date.toGMTString();
            }
        }
    };
})();
TWP.Util.ElPosition = {

    getPos : function(obj) {
        return [this.getRealLeft(obj), this.getRealTop(obj)];
    },

    getRealTopByObj : function(obj) {
        yPos = 0;
        if(obj)
        {
            yPos = obj.offsetTop;
            tempEl = obj.offsetParent;
            while(tempEl !== null)
            {
                yPos += tempEl.offsetTop;
                tempEl = tempEl.offsetParent;
            }
        }
        return yPos;
    },

    getRealTop : function(obj){
        yPos = this.getRealTopByObj(obj);
        return yPos;
    },

    getRealLeftByObj : function(obj){
        xPos = 0;
        if(obj)
        {
            xPos = obj.offsetLeft;
            tempEl = obj.offsetParent;
            while(tempEl !== null)
            {
                xPos += tempEl.offsetLeft;
                tempEl = tempEl.offsetParent;
            }
        }
        return xPos;
    },

    getRealLeft : function(obj){
        xPos = this.getRealLeftByObj(obj);
        return xPos;
    }    
};
TWP.Util.FormValidation  = {

    regexValidate : function(value, pattern){
        if (pattern != null && pattern.length > 0){
            var re = new RegExp(pattern);
            return value.match(re);
        } else {
            return false;
        }
    },
    
    /// <summary>Validates an email address</summary>
    /// <param name="email" type="string">The email to validate</param>
    /// <returns>boolean</returns>
    validateEmailAddress : function(email){
        return this.regexValidate(email, "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
    },

    /// <summary>Validates multipe email address</summary>
    ///  <param name="emails" type="string">The email comma delimited list to validate</param>
    ///  <param name="max" type="number">Maximum emails in the list</param>
    /// <returns>boolean</returns>
    validateMultipleEmailAddresses : function(emails, max){
        var valid = false;
        var addresses = emails.split(",");

        if(addresses.length){
            for(var a=0;a<addresses.length;a++){
                if(addresses[a] != ''){
                    var address = addresses[a].replace(/^\s+|\s+$/g, "");
                    valid = this.regexValidate(address, "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$");
                } else {
                    valid = false;
                }
            }
        }

        if(addresses.length > max || !valid){

            return false;
        }
        return true;
    },
   formatDollar : function(aElement) {
        var lsElementValue = aElement.value;
        var isNegative = false;
        if (lsElementValue.substring(0, 1) == "-") {
            isNegative = true;
            lsElementValue = lsElementValue.substring(1, lsElementValue.length);
        }
        var lsBuffer1 = "";
        for (var i = 0; i < lsElementValue.length; i++) {
            var lsCh = lsElementValue.substring(i, i + 1);
            if (((lsCh >= "0") && (lsCh <= "9")) || (lsCh == ".")) {
                lsBuffer1 += lsCh;
            } else if ((lsCh != "$") && (lsCh != ",")) {
                alert("Enter a number, please.");
                return false;
            }
        }
        if (isNegative) {
            lsBuffer1 = "-" + lsBuffer1;
        }
        if (lsBuffer1 == "") {
            lsBuffer1 = "0";
        }
        var lrVal = parseFloat(lsBuffer1);
        if (isNegative) {
            lsBuffer1 = lsBuffer1.substring(1, lsBuffer1.length);
        }
        var liComma = 0;
        var lsBuffer2 = "";
        var liDecimalPos = lsBuffer1.indexOf(".");
        for (var i = lsBuffer1.length; i > 0; i--) {
            if (liComma > 2) {
                lsBuffer2 += ",";
                liComma = 0;
            }
            lsBuffer2 += lsBuffer1.substring(i, i - 1);
            if ((liDecimalPos == -1) || (i <= liDecimalPos)) {
                liComma += 1;
            }
        }
        if (isNegative) {
            lsBuffer1 = "-$";
        } else {
            lsBuffer1 = "$";
        }
        for (var i = lsBuffer2.length; i > 0; i--) {
            lsBuffer1 += lsBuffer2.substring(i, i - 1);
        }
        aElement.value = lsBuffer1;

        return true;
    },
	
    formatPercent : function(aElement) {
        var lsElementValue = aElement.value;
        var isNegative = false;
        if (lsElementValue.substring(0, 1) == "-") {
            isNegative = true;
            lsElementValue = lsElementValue.substring(1, lsElementValue.length);
        }
        var lsBuffer1 = "";
        for (var i = 0; i < lsElementValue.length; i++) {
            var lsCh = lsElementValue.substring(i, i + 1);
            if (((lsCh >= "0") && (lsCh <= "9")) || (lsCh ==".")) {
                lsBuffer1 += lsCh;
            } else if (lsCh !="%") {
                alert("Enter a number, please.");
                return false;
            }
        }
        if (lsBuffer1 == "") {
            lsBuffer1 = "0";
        }
        var lrVal = parseFloat(lsBuffer1);
        lrVal = lrVal/100;
        if (isNegative) {
            lrVal = lrVal * -1;
        }
        if (isNegative) {
            lsBuffer1 = lsBuffer1.substring(1, lsBuffer1.length);
        }
        lsBuffer = TWP.Util.FormValidation.round(lrVal * 100, 2);
        if (isNegative) {
            aElement.value = "-" + lsBuffer + "%";
        } else {
            aElement.value = lsBuffer + "%";
        }

        return true;
    },
	
    formatNumber : function(aElement) {
        var lsElementValue = aElement.value;
        var isNegative = false;
        if (lsElementValue.substring(0, 1) == "-") {
            isNegative = true;
            lsElementValue = lsElementValue.substring(1, lsElementValue.length);
        }
        var lsBuffer1 = "";
        for (var i = 0; i < lsElementValue.length; i++) {
            var lsCh = lsElementValue.substring(i, i + 1);
            if (((lsCh >= "0") && (lsCh <= "9")) || (lsCh == ".")) {
                lsBuffer1 += lsCh;
            } else if (lsCh != ",") {
                alert("Enter a number, please.");
                return false;
            }
        }
        if (isNegative) {
            lsBuffer1 = "-" + lsBuffer1;
        }
        if (lsBuffer1 == "") {
            lsBuffer1 = "0";
        }
        var lrVal = parseFloat(lsBuffer1);
        if (isNegative) {
            lsBuffer1 = lsBuffer1.substring(1, lsBuffer1.length);
        }
        var liComma = 0;
        var lsBuffer2 = "";
        var liDecimalPos = lsBuffer1.indexOf(".");
        for (var i = lsBuffer1.length; i > 0; i--) {
            if (liComma > 2) {
                lsBuffer2 += ",";
                liComma = 0;
            }
            lsBuffer2 += lsBuffer1.substring(i, i - 1);
            if ((liDecimalPos == -1) || (i <= liDecimalPos)) {
                liComma += 1;
            }
        }
        if (isNegative) {
            lsBuffer1 = "-";
        } else {
            lsBuffer1 = "";
        }
        for (var i = lsBuffer2.length; i > 0; i--) {
            lsBuffer1 += lsBuffer2.substring(i, i - 1);
        }
        aElement.value = lsBuffer1;

        return true;
    },
	
    round : function(number,X) {
        // rounds number to X = (!X ? 3 : X);
        var n = 0;
        n = Math.round(number*Math.pow(100,X))/Math.pow(100,X)
        return n;
    }	
};
// <summary>Utility that returns randomized numbers and lists</summary>
TWP.Util.Random = {

	// <summary>Returns a number in a specified range</summary>
	// <param name="min">Minimum number in the range</param>
	// <param name="max">Maximum number in the range</param>
	// <returns>Positive number</returns>
	getRandomNumberInRange : function(min, max){

        if(min == 0){
            min = Math.random();
        }

        if(max == 0){
            max = Math.random();
        }

		return (Math.round((max-min) * Math.random() + min));
	},

	// <summary>Returns an array of numbers, given a size</summary>
	// <param name="size" type="number">The size of the array to return</param>
	// <param name="min" type="number">Minimum number in the range</param>
	// <param name="max" type="number">Maximum number in the range</param>
	// <param name="unigue" type="boolean">Boolean to specify unique or non-unique array values.
	// In order to return all uniques, size must be equivalent to all
	// numbers with the domain of the range [min, max]
	// </param>
	// <returns>Array</returns>
	getRandomNumberListInRange : function(size, min, max, unique){
		var temp, nums = [];

		for(var a=0;a<size;a++){


			if(unique){

				while((temp=this.hasNumber(this.randomNumberInRange(min,max), nums))===-1){
					nums[a] = temp;
				}

			} else {
				nums[a] = this.randomNumberInRange(min, max);
			}

		}


		return (nums);

	},

	// <summary>Checks an array for the specified number </summary>
	// <param name="num" type="number">The number to search for</param>
	// <param name="arr" type="arr">The array list to search</param>
	// <returns>An integer,either -1 if false or the number("num") if true</returns>
	hasNumber : function(num, arr){

		var len = arr.length

		for(var b=0;b<len;b=b+1){

			if(num == arr[b]){
				return (-1);
			}
		}

		return num;
	}

}
js_months = new Array('Jan.','Feb.','March','April','May','June','July','Aug.','Sept.','Oct.','Nov.','Dec.') ;

function display_headlines(headlines)
{
	for ( var i=0; i<headlines.length; i++ )
	{
		var item = headlines[i] ;
		document.write("<a href="+item.url+">") ;
		document.write(item.headline) ;
		document.write("</a>") ;
		document.write("<br/>") ;
	}
}

function render_js_headlines(style,collection,maximum,startIndex)
{
	if ( typeof style == "undefined" )
		style = "default" ;
	if ( typeof collection == "undefined" && typeof headlines == "object" )
		collection = headlines ;
	if ( typeof maximum == "undefined" )
		maximum = 20 ;
	if ( maximum > collection.length )
		maximum = collection.length ;
        if (typeof startIndex == "undefined")
                startIndex = 0;

	var output = '' ;
	switch ( style )
	{
		case "realestate":
		{
			render_js_realestate() ;
			break ;
		}
		case "sidebar":
		{
			render_js_sidebar() ;
			break ;
		}
		case "strip_of_links":
		{
			render_js_sidebar() ;
			break ;
		}
		case "default" :
		{
			render_js_default() ;
			break ;
		}
		case "entertainment" :
		{
			render_js_entertainment() ;
			break ;
		}
		case "columnist" :
		{
			render_js_columnist() ;
			break ;
		}
		case "columns" :
		{
			render_js_columns() ;
			break ;
		}
		case "head_source_date_time" :
		{
			render_js_head_source_date_time() ;
			break ;
		}
		case "kidspost" :
		{
			render_js_kidspost() ;
			break ;
		}
		case "plain_links" :
		{
			render_js_plain_links() ;
			break ;
		}
		case "plain_links_bullets" :
		{
			render_js_plain_links_bullets() ;
			break ;
		}
		case "pulldown" :
		{
			render_js_pulldown() ;
			break ;
		}
		case "columnstrip" :
		{
			render_js_columnstrip() ;
			break ;
		}
		case "articlestrip" :
		{
			render_js_articlestrip() ;
			break ;
		}
		case "linksetblurb" :
		{
			render_js_linksetblurb() ;
			break ;
		}
		case "printupdate" :
		{
			render_js_printupdate() ;
			break ;
		}
		case "urlonly" :
		{
			render_js_urlonly() ;
			break ;
		}
		case "columnlink" :
		{
			render_js_columnlink() ;
			break ;
		}
		case "plain_headline_date_source" :
		{
			render_js_plain_headline_date_source() ;
			break ;
		}
		case "readmore" :
		{
			render_js_readmore() ;
			break ;
		}
		case "metbot" :
		{
			render_js_metbot() ;
			break ;
		}
		case "headline_module" :
		{
			render_js_headline_module() ;
			break ;
		}
		case "hed_byline_date" :
		{
			render_js_hed_byline_date() ;
			break ;
		}
		case "twpv3_bulleted_linklist" :
		{
			render_js_twpv3_bulleted_linklist();
			break;
		}
		case "twpv3_story_one" :
		{
			render_js_twpv3_story_one(false,startIndex);
			break;
		}
		case "twpv3_story_one_meta" :
		{
			render_js_twpv3_story_one(true,startIndex);
			break;
		}
		case "twpv3_story_large" :
		{
			render_js_twpv3_story_large(true,startIndex);
			break;
		}


	}
	// document.write('<form><textarea>') ;
	document.write( output ) ;
	// document.write('</textarea></form>') ;

	function render_js_hed_byline_date()
	{
		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
			output += '<p class="columnlink">&#8226; <a href="'+item.url+'">'+item.headline+'</a> <span class="columndate">('+item.byline+', '+getDateTime(item.pubdate, item.source)+')</span></p>' ;
		}
	}

function render_js_headline_module()
	{
		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
				output += '&#149; <a href="'+item.url+'">'+item.headline+'</a>' ;
				output += '<br>' ;
		}
	}

	function render_js_columnlink()
	{
		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
			output += '<p class="columnlink">&#8226; <a href="'+item.url+'">'+item.headline+'</a> <span class="columndate">('+getDateTime(item.pubdate, item.source)+')</span></p>' ;
		}
	}

	function render_js_articlestrip()
	{
		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
			output += '<font size="+1"><a href="'+item.url+'"><b>'+item.headline+'</b></a></font><br><font size="-1">'+item.blurb+'</font>' ;
		}
	}

	function render_js_printupdate()
	{
		for (var i=0; i<maximum; i++)
		{
			var item = collection[i] ;
			if ( item.source != 'Post' && item.byline != '' )
			{	output += '<h3><a href="'+item.url+'?nav=printbox">'+item.headline+'</a><br/></h3>'+item.blurb+'<br/><img src="http://media.washingtonpost.com/wp-srv/globalnav/images/spacer.gif" alt="spacer" width="1" height="5">' ;
			}
		}
	}

	function render_js_linksetblurb()
	{
		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
			output += '<h1><a href="'+item.url+'">'+item.headline+'</a><br/></h1><h2>'+item.blurb+'</h2>' ;
		}
	}

	function render_js_columnstrip()
	{
		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
			output += '<font size=""><a href="'+item.url+'"><b>'+item.headline+'</b></a></font><br><font size="-1">'+item.blurb+'</font>' ;
		}
	}


	function render_js_pulldown()
	{
		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
			output += '<option value="'+item.url+'">'+getAuthor(item.byline)+': '+item.headline+'</option>' ;
		}
	}
	function render_js_columns()
	{
		output += '<div id="headlines_js">\n' ;
		output += '<div class="'+style+'">\n' ;
		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
			output += '<a href="'+item.url+'">'+item.headline+'</a> ' ;
			if ( item.source != '' || item.pubdate != '' )
			{
				output += '<span class="source">' ;
				output += ' <nobr>(' ;
				if ( item.source != '' )
					output += item.source ;
				if ( item.source != '' && item.pubdate != '' )
					output += ', ' ;
				output += getDateTime(item.pubdate, item.source);
				output += ')</nobr>' ;
				output += '</span>' ;
			}
			output += '</span></a><br/>\n' ;
		}
		output += '</div>\n' ;
		output += '</div>\n' ;
	}

	function render_js_plain_headline_date_source()
	{
		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
			output += '<p class="phds-link"><a href="'+item.url+'">'+item.headline+'</a> <span class="columndate">('+getDateTime(item.pubdate, item.source)+')</span></p>' ;
		}
	}

		function render_js_head_source_date_time()
	{
		output += '<div id="headlines_js">\n' ;
		output += '<div class="'+style+'">\n' ;
		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
			output += '<div><a href="'+item.url+'">'+item.headline+'</a> ' ;
			if ( item.source != '' || item.pubdate != '' )
			{
				output += '<span class="source">' ;
				output += ' <nobr>(' ;
				if ( item.source != '' )
					output += item.source ;
				if ( item.source != '' && item.pubdate != '' )
					output += ', ' ;
				if ( item.pubdate != '' )
				{
					output += js_months[item.pubdate.getMonth()] ;
					output += ' ' ;
					output += item.pubdate.getDate() ;
					var hours = item.pubdate.getHours();
					var ampm = "AM";
					if (hours >= 12) {
						ampm = "PM";
						hours = hours - 12;
					}
					if (hours == 0) { hours = 12; }
					var mins = item.pubdate.getMinutes();
					if (mins < 10) { mins = "0"+mins; }
					output += '; ' + hours + ':' + mins + ' ' + ampm;
				}
				output += ')</nobr>' ;
				output += '</span>' ;
			}
			output += '</span></a></div>\n' ;
		}
		output += '</div>\n' ;
		output += '</div>\n' ;
	}

	function render_js_kidspost()
	{
		output += '<div id="headlines_js">\n' ;
		output += '<div class="'+style+'">\n' ;
		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
			output += '<div style="margin-bottom:6px;"><a href="'+item.url+'">'+item.headline+'</a> ' ;
			if ( item.source != '' || item.pubdate != '' )
			{
				output += '<span class="source">' ;
				output += ' <nobr>(' ;
				if ( item.source != '' )
					output += item.source ;
				if ( item.source != '' && item.pubdate != '' )
					output += ', ' ;
				output += getDateTime(item.pubdate, item.source);
				output += ')</nobr>' ;
				output += '</span>' ;
			}
			output += '</span></a></div>\n' ;
		}
		output += '</div>\n' ;
		output += '</div>\n' ;
	}

	function getDateTime(aDate, source) {
		if (aDate == '') { return ''; }
		var dateString = js_months[aDate.getMonth()] ;
		dateString += ' ' ;
		dateString += aDate.getDate() ;
		if (source != 'Post') {
			var hours = aDate.getHours() ;
			var ampm = "AM";
			if (hours >= 12) {
				ampm = "PM";
				hours = hours - 12;
			}
			if (hours == 0) { hours = 12; }
			var mins = aDate.getMinutes();
			if (mins < 10) { mins = "0"+mins; }
			dateString += '; ' + hours + ':' + mins + ' ' + ampm;
		}

		return dateString;
	}
	function render_js_sidebar()
	{
		output += '<div id="headlines_js">\n' ;
		output += '<div class="'+style+'">\n' ;
		output += '<ul style="list-style-image: url(http://media.washingtonpost.com/wp-adv/classifieds/realestate/redesign/images/black.gif)">\n' ;
		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
			output += '<li><span class="bullet_spacing">' ;
			output += '<a href="'+item.url+'">'+item.headline+'</a>' ;
			if ( item.source != '' || item.pubdate != '' )
			{
				output += '<span class="source">' ;
				output += ' <nobr>(' ;
				if ( item.source != '' )
					output += item.source ;
				if ( item.source != '' && item.pubdate != '' )
					output += ', ' ;
				if ( item.pubdate != '' )
				{
					output += js_months[item.pubdate.getMonth()] ;
					output += ' ' ;
					output += item.pubdate.getDate() ;
					var hours = item.pubdate.getHours();
					var ampm = "AM";
					if (hours >= 12) {
						ampm = "PM";
						hours = hours - 12;
					}
					if (hours == 0) { hours = 12; }
					var mins = item.pubdate.getMinutes();
					if (mins < 10) { mins = "0"+mins; }
					output += '; ' + hours + ':' + mins + ' ' + ampm;
				}
				output += ')</nobr>' ;
				output += '</span>' ;
			}
			output += '</span></a>\n' ;
		}
		output += '</ul>\n' ;
		output += '</div>\n' ;
		output += '</div>\n' ;
	}

	function render_js_strip_of_links()
	{
		// alert(style) ;
	}

	function render_js_plain_links()
	{
		output += '<div id="headlines_js">\n' ;
		output += '<div class="'+style+'">\n' ;
		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
				output += '<span>';
				output += '<a href="'+item.url+'">'+item.headline+'</a>' ;
				output += '</a></span><br />\n' ;
		}
		output += '</div>\n' ;
		output += '</div>\n' ;
	}

	function render_js_plain_links_bullets()
	{
		output += '<div id="headlines_js">\n' ;
		output += '<div class="'+style+'"><ul>\n' ;
		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
				output += '<span>';
				output += '<li><a href="'+item.url+'">'+item.headline+'</a>' ;
				output += '</li></span>\n' ;
		}
		output += '</a></ul><div class="clearboth"></div></div>\n' ;
		output += '</div>\n' ;
	}

	function render_js_columnist()
	{
		output += '<div id="headlines_js">\n' ;
		output += '<div class="'+style+'">\n' ;
		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
			var author = getAuthor(item.byline);
			if (author != '') {
				output += '<span>';
				output += '<b>'+getAuthor(item.byline)+': </b>' ;
				output += '<a href="'+item.url+'">'+item.headline+'</a>' ;
				output += '</a></span><br />\n' ;
			}
		}
		output += '</div>\n' ;
		output += '</div>\n' ;
	}
	function getAuthor(byline)
	{
		if (byline == '') return byline;
		var re = /^By /;
		return byline.replace(re,"");
	}
	function render_js_realestate()
	{
		output += '<div id="headlines_js">\n' ;
		output += '<div class="'+style+'">\n' ;
		output += '<ul style="list-style-image: url(http://media.washingtonpost.com/wp-adv/classifieds/realestate/redesign/images/black.gif)">\n' ;
		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
			output += '<li><span class="bullet_spacing">' ;
			output += '<a href="'+item.url+'">'+item.headline+'</a>' ;
			if ( item.source != '' || item.pubdate != '' )
			{
				output += '<span class="source">' ;
				output += ' <nobr>(' ;
				if ( item.source != '' )
					output += item.source ;
				if ( item.source != '' && item.pubdate != '' )
					output += ', ' ;
				if ( item.pubdate != '' )
				{
					output += js_months[item.pubdate.getMonth()] ;
					output += ' ' ;
					output += item.pubdate.getDate() ;
				}
				output += ')</nobr>' ;
				output += '</span>' ;
			}
			output += '</span></a>\n' ;
		}
		output += '</ul>\n' ;
		output += '</div>\n' ;
		output += '</div>\n' ;
	}

	function render_js_readmore()
	{
		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
				output += '<span style="font: normal 12px arial,helvetica;">';
				output += '&#149; <a href="'+item.url+'?nav=trm" style="font-weight:normal;"  target="_top">'+item.headline+'</a>' ;
				output += '<br /></span>\n';
		}
	}

	function render_js_metbot()
	{
		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
				output += '<tr valign=\"top\"><td><span style=\"font: normal 8pt arial;\">&#149;</span></td> <td>';
				output += '<span style="font: normal 12px arial,helvetica;">';
				output += '<a href="'+item.url+'?nav=mbot" style="font-weight:normal;"  target="_top">'+item.headline+'</a>' ;
				output += '<br /></span></td></tr>\n';
		}
	}

	function render_js_default()
	{
		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
			output += '<p class="js_default"><a href="'+item.url+'">'+item.headline+'</a><br />'+item.blurb+'</p>' ;
		}
	}


	function render_js_twpv3_bulleted_linklist(){
		output += '<ul class="bulleted">\n' ;

		for (var i=0; i<maximum; i++ )
		{
			var item = collection[i] ;
				output += '<li><a href="'+item.url+'">'+item.headline+'</a>' ;
				output += '</li>\n' ;
		}

		output += '</ul>\n' ;
	}


	function render_js_twpv3_story_one(showMeta,startIndex){

		for(var i=0;i<maximum;i=i+1){
                    if (i >= startIndex ) {

			var item = collection[i];

			output += '<div class="wp-row' + ((i==maximum-1) ? ' no-pad' : ' border')  + '">';
			output += '<div class="module story-one">';
			output += '<h2><a href="' + item.url + '">' + item.headline + '</a></h2>'; // Headline
			if (item.thumbnail.url != "") {
                            output += '<div class="thumbnail left"><a href="' + item.url + '"><img src="' + item.thumbnail.url + '" alt="' + item.headline + '" /></a></div>'; // Image
                        }
			var dateCal = new TWP.Util.DateCalculator();
			var iso = dateCal.newIso8601Date(item.pubdate);

			if(showMeta){
				output += '<div class="meta"><span class="byline">'+ item.byline + '</span><span class="timestamp" data="' + iso + '"></span></div>'; // timestamp
			}

			output += '<p>' + item.blurb + '</p>';
			output += '</div>';
			output += '</div>';
                    }
		}

	}

	function render_js_twpv3_story_large(showMeta,startIndex){

		for(var i=0;i<maximum;i=i+1){
                     if (i >= startIndex ) {

			var item = collection[i];

			output += '<div class="wp-row' + ((i==maximum-1 && maximum > 1) ? ' no-pad' : ' double-border')  + '">';
			output += '<div class="module h1-hero">';
			output += '<h2><a href="' + item.url + '">' + item.headline + '</a></h2>'; // Headline
			if (item.media290.url != "") {
                            output += '<div class="thumbnail left"><a href="' + item.url + '"><img src="' + item.media290.url + '" alt="' + item.headline + '" /></a></div>'; // Image
                        }
			var dateCal = new TWP.Util.DateCalculator();
			var iso = dateCal.newIso8601Date(item.pubdate);

			if(showMeta){
				output += '<div class="meta"><span class="byline">'+ item.byline + '</span><span class="timestamp" data="' + iso + '"></span></div>'; // timestamp
			}

			output += '<p>' + item.blurb + '</p>';
			output += '</div>';
			output += '</div>';
                     }
		}

	}
}
/* plugin */
/* version 2.0. */
;(function($){

    $.fn.carousel = function(options){
        return this.each(function(){
            new $.carousel(this, options);
        });
    };

    $.carousel = function(el, options){

        // defaults
        var defaults = {
            vertical : true,
            speed : 8000,
            queue : null,
            rotate : false,
            hoverPause : false,
            initCallback : null,
            onAfterScrollCallback : null,
            onBeforeScrollCallback : null,
            context : null,
            pagination : false
        };

        this.options = $.extend(defaults, options);

        this.props = {
            items : [],
            totalItems : 0,
            intvObj : null,
            currIndex : 0,
            initialized : false,
            animating : false,
            carouselEl : el,
            queue : (this.options.queue) ? $(el).find(this.options.queue).get(0) : $(el).children().eq(0).get(0),
            range : null,
            direx : 'forward', // scroll forward or back
            page : 1,
            totalPages : 1,
            cacheNextIndex : 0,
            cachePrevIndex : null,
            itemWh : 0,
            viewportWh : 0,
            paginationHTML : ''
        };

        // determine what dimension/offset we will be using
        this.widthHeight = !this.options.vertical ? "width" : "height";
        this.leftTop = !this.options.vertical ? "left" : "top";

        if(!this.props.queue){
            return;
        }

        // initialize
        this.init(el);
    }

    $.carousel.fn = $.carousel.prototype = {};
    $.carousel.fn.extend = $.carousel.extend = $.extend;

    $.carousel.fn.extend({

        init : function(){
            var self = this, props = this.props, options = this.options, totalQueueWH =0, mh=0, d, pwh, b = $(props.queue).children().length, show = 0, wt, ht;

            // viewport height/width
            pwh = props.viewportWh = self.getIntegerVal($(props.queue).parent()[self.widthHeight]());

            // initial setup of queue items
            $(props.queue).children().each(function(){
                // get the dimensions
                d = self.getDimension(this);
                wt = d[0];
                ht = d[1];

                // add item to the cache
                props.items.push(this);

                // based on the width/height of viewport, determine how many items we can show
                if(options.vertical){
                    ht = ht - self.getIntegerVal($(this).css('paddingTop')) - self.getIntegerVal($(this).css('paddingBottom'));
                    totalQueueWH = totalQueueWH + ht;
                } else {
                    totalQueueWH += wt - self.getIntegerVal($(this).css('paddingLeft')) - self.getIntegerVal($(this).css('paddingRight'));
                }

                if(totalQueueWH <= pwh){
                    show++;
                }
            });

            // based on the viewport height, the num items to show
            options.show = show;
            props.initialized = true;
            props.totalItems = props.items.length;

            props.cachePrevIndex = props.totalItems - 1;
            props.cacheNextIndex = options.show;

            // Determine the total number of pages
            props.totalPages = (options.show > 0 && options.show < props.totalItems) ? Math.ceil(props.totalItems/options.show) : props.totalItems;

            // Set the queue height to fix slideup/down on page
            if(options.fixedHeight){
               $(props.queue).height(pwh).css('overflow', 'hidden');
            }

            // Remove all from the DOM except the onload items, we've store those away
            $(props.queue).children().each(function(i){
               if(i > options.show - 1) {
                   $(this).remove();
               }
            });

            // execute callback
            if(this.options.initCallback != null){
                (this.options.initCallback)(this);
            }
        },

        scrollQueue : function(index){
            var props = this.props, options = this.options, tmp;
            if(props.direx == 'forward'){
                tmp = index + 1;
            } else {
                tmp = index;
            }

            if(options.show == 1){
                props.page = (((tmp + 1) * options.show) - options.show);
            } else {
                props.page = Math.ceil(tmp / (props.page * options.show));
            }

            this.scroll(index);
        },

        next : function(){
            var props = this.props, options = this.options, index;

            /*if(props.animating || props.totalPages == 1){
                return;
            }*/

            props.direx = 'forward';
            index = props.cacheNextIndex;
            this.scrollQueue(index);
        },

        previous : function(){
            var props = this.props, index;

            /*if(props.animating || props.totalPages == 1){
                return;
            }*/

            props.direx = 'backward';
            index = props.cachePrevIndex;
            this.scrollQueue(index);
        },


        scroll : function(){
            var that = this, props = this.props, options = this.options, left = 0, top = 0, params;
            var page = props.page;

            if(props.direx == 'forward' && !options.vertical){
                left = -(props.viewportWh);
            } else if(props.direx == 'backward' && !options.vertical) {
                left = 0;
            }

            if(props.direx == 'forward' && options.vertical){
                top = -(props.viewportWh);
            } else if(props.direx == 'backward' && options.vertical) {
                top = 0;
            }

            params = (!this.options.vertical) ? {
                'left' : left
            } : {
                'top' : top
            };

            if(this.props.animating){
                return;
            }

            this.props.animating = true;
            that.notify('onBeforeScroll', params);

            if(this.options.onBeforeScrollCallback != null){
                (this.options.onBeforeScrollCallback)(this);
            }
        },

        onBeforeScroll : function(params){
            var props = this.props;

            if(props.direx == 'forward'){
                this.setForwardScroll(params);
            } else {
                this.setBackwardScroll(params);
            }
        },

        animateScroll : function(params){
            var props = this.props;
            var that = this;
            var show = this.options.show;


            $(props.queue).children().eq($(props.queue).children().length-1).css({
                'z-index' : show,
                'opacity' : 0,
                'display' : 'block'
            }).animate({
                'opacity' : 1
            }, 450, function(){
                $(this).addClass('selected').removeAttr('style');
            });

            // Get the next page in the list or group of items and place behind the current
            var old = $(props.queue).children().eq(0);
            $(old).animate({
                opacity : 0
            }, 100, function(){
                $(old).remove()
            });

            setTimeout(function(){
                that.props.animating = false;

                // Reset the interval
                if(that.props.autoScroll){
                    that.props.intvObj.restart();
                }

                that.notify('onAfterScroll');
            }, 310);
        },

        onAfterScroll : function(){
            var props = this.props;
            if(this.options.onAfterScrollCallback != null){
                (this.options.onAfterScrollCallback)(this);
            }
        },

        setForwardScroll : function(params){
            var props = this.props, options = this.options, frag, ti = props.totalItems, next = props.cacheNextIndex, prev = props.cachePrevIndex, show = options.show, el;

            if(options.show == 1){

                frag = document.createDocumentFragment();

                // clone items
                for(var a=0, b=show;a<b;a++){
                    // Get element and append

                    el = $(props.items[next]).clone().get(0);
                    el.removeAttribute('style');

                    frag.appendChild(el);

                    if(next == ti - 1){
                        next = 0;
                    } else {
                        next++;
                    }

                    if(prev == ti - 1){
                        prev = 0;
                    } else {
                        prev++;
                    }
                }

                if(props.currIndex == props.totalPages-1){
                    props.currIndex = 0;
                } else {
                    props.currIndex++;
                }

                $(props.queue).append(frag);
                props.cacheNextIndex = next;
                props.cachePrevIndex = prev;

            }

            this.cleanQueue();
            this.animateScroll(params);
        },

        setBackwardScroll : function(params){
            var props = this.props, options = this.options, frag, ti = props.totalItems, show = options.show, next = props.cacheNextIndex, prev = props.cachePrevIndex;

            if(options.show == 1){

                frag = document.createDocumentFragment();

                // clone items
                for(var a=0, b=show;a<b;a++){
                    // Get element and append
                    el = $(props.items[prev]).clone().get(0);
                    el.removeAttribute('style');

                    frag.appendChild(el);

                    if(next == ti - 1){
                        next = 0;
                    } else {
                        next++;
                    }
                }

                if(prev == 0){
                    prev = ti - 1;
                } else {
                    prev--;
                }

                if(props.currIndex == 0){
                    props.currIndex = props.totalPages-1;
                } else {
                    props.currIndex--;
                }

                $(props.queue).append(frag);
                props.cacheNextIndex = next;
                props.cachePrevIndex = prev;

            }

            this.cleanQueue();
            this.animateScroll(params);
        },

        cleanQueue : function(){
            var props = this.props;
            // cleanup queue
            var ql = $(props.queue).children().length;
            $(props.queue).children().each(function(i){
                if($(this).hasClass('last')){
                    $(this).removeClass('last');
                }

                /*if(i == ql-1){
                    $(this).addClass('last');
                }*/
            });
        },

        notify : function(evt, params){
            this.callback(evt, params);
        },

        callback : function(evt, params){
            var fn = evt;
            this[fn](params);
        },

        getIntegerVal: function(v) {
            v = parseInt(v);
            return isNaN(v) ? 0 : v;
        },

        getDimension: function(el) {
            el = $(el)
            var w = 0, h = 0;

            if(!$.browser.msie){
                w = this.getIntegerVal($(el).width()) + this.getIntegerVal($(el).css('marginLeft')) + this.getIntegerVal($(el).css('marginRight')) +  this.getIntegerVal($(el).css('paddingLeft')) + this.getIntegerVal($(el).css('paddingRight'));
                h = this.getIntegerVal($(el).height()) + this.getIntegerVal($(el).css('marginTop')) + this.getIntegerVal($(el).css('marginBottom')) + this.getIntegerVal($(el).css('paddingTop')) + this.getIntegerVal($(el).css('paddingBottom'));

            } else {
                w = this.getIntegerVal($(el).width()) + + this.getIntegerVal($(el).css('paddingLeft')) + this.getIntegerVal($(el).css('paddingRight'))
                h = this.getIntegerVal($(el).height()) + this.getIntegerVal($(el).css('paddingTop')) + this.getIntegerVal($(el).css('paddingBottom'));
            }

            return [w, h];
        }
    });

})(jQuery);
/* plugin */
(function($){

    $.fn.hotContent = function(options){
        return this.each(function(){
            new $.hotContent(this, options);
        });
    }

    $.hotContent = function(el, options){

        // defaults
        var defaults = {
            displayMax : 6,
            section : 'all',
            type : 'articles'
        };

        // new options
        this.options = $.extend(defaults, options);

        this.props = {
            element : el
        };

        this.init(el);
    }

    $.hotContent.fn = $.hotContent.prototype = {};

    $.hotContent.fn.extend = $.hotContent.extend = $.extend;

    $.hotContent.fn.extend({
        init : function(el){
            var self = this, props = this.props, options = this.options;

            // Set initialization to true
            props.initialized = true;

            // Setup some more props
            props.section = options.section;
            props.type = options.type;
            props.displayMax = options.displayMax;
            if (options.callback) {
                props.callback = options.callback;
            }
            if (options.event) {
                props.event = options.event;
            }

            // default display types
            if (!options.displayTemplate) {
                if (el.tagName.toLowerCase() == "ol" || el.tagName.toLowerCase() == "ul") {
                    options.displayTemplate = '<li><a href="#{url}">#{linkText}</a></li>';
                } else {
                    options.displayTemplate = '<p><b>#{no}.</b>: <a href="#{url}">#{linkText}</a></p>';
                }
            }

            this.load(props.section, props.type, props);
        },

        getDataUrl : function(section,type,proxy){
            if (proxy) {
                return "/wpost/data/proxy.json?r=http://www.washingtonpost.com/wp-srv/javascript/contentorbiting/hotcontent/"+section+"/"+type+"/index.js&jsonp=?";
            }
            return "http://www.washingtonpost.com/wp-srv/javascript/contentorbiting/hotcontent/"+section+"/"+type+"/index.js";
        },

        getProperties : function(obj) {
            // Go through all the properties of the passed-in object
            var r = new Array();
            for (var i in obj) {
                var o = {};
                o.name = i;
                o.value = obj[i];
                r.push(o);
            }
            return r;
        },

        load : function(section,type,props){
            var self = this;

            // determin type to load
            var dtype = 'json';
            var dataUrl = '';
            if (window.location.href.indexOf("http://www.washingtonpost.com/") > -1) {
                dataUrl = self.getDataUrl(section,type, false);
            } else if (window.location.href.indexOf("http://live.washingtonpost.com/") != -1) {
                dtype = 'jsonp';
                dataUrl = "http://www.washingtonpost.com" + self.getDataUrl(section,type, true);
            } else {
                dtype = 'jsonp';
                dataUrl = self.getDataUrl(section,type, true);
            }
            $.ajax({
                dataType:dtype,
                url:dataUrl,
                dataFilter:function(data,type){
                    return self.toJSON(data);
                },
                success:function(data,msg){
                    $.extend(props,{
                        msg:msg
                    });
                    self.render(data, props);
                }
            });
        },

        render : function(data, props) {
            var self = this;

            var $el = $(props.element);
            var max = props.displayMax - 1; // -1 for index
            var maxHeight = 0;

            $el.html("");

            $(data.content).each(function(i) {
                $el.append(self.sanitizeItem(i+1, this));
                return (i < max);
            });

            if(props.event) $(document).trigger(props.event,self.sanitizeUrls(data));
            if(props.callback) props.callback.call(self,data,props);
        },

        sanitizeItem : function(position, item) {
            var self = this;
            var r = this.options.displayTemplate;
            item.position = position;
            var p = this.getProperties(item);
            for (var i = 0; i < p.length; i++) {
                if (p[i].name == 'url') {
                    p[i].value = self.sanitizeUrl(p[i].value);
                }
                r = r.replace('\#\{' + p[i].name + '\}', p[i].value);
            }
            return r;
        },

        sanitizeUrls : function(data){
            var self = this;
            $(data.content).each(function(i){
                this.url = self.sanitizeUrl( this.url );
            });
            return data;
        },

        sanitizeUrl : function(url){
            return url.replace(/(\?|&)nav=.*?(&|$)/,'');
        },

        toJSON : function(json){
            //alert(!(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test( json.replace(/"(\\.|[^"\\])*"/g, '')))&&eval('('+json+')'));
            json = json.replace(/\n/g,'');
            json = json.replace(/"\s*,\s*/g,'",');
            json = json.replace(/{\s*/g,'{');
            while ( json.match(/([{,])(\w+):/) ) {
                json = json.replace(/[{,]\w+:/,RegExp.$1+'"'+RegExp.$2+'":');
            }
            json = json.replace(/\\'/g,'&#39;');
            json = json.replace(/\\"/g,'&#34;');
            json = json.replace(/\s*;$\s*/g,'');
            //alert(!(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test( json.replace(/"(\\.|[^"\\])*"/g, '')))&&eval('('+json+')'));

            return json;
        }

    });
})(jQuery);

/*
 * Overlay Box (1.0)
 * by Chad Shryock
 */

(function(jQuery) {

    var self = null;

    jQuery.fn.obox = function(o) {
        return this.each(function() {
            new jQuery.obox(this, o);
        });
    };

    /**
     * The inputAutogrow object.
     *
     * @constructor
     * @name jQuery.obox
     * @param Object e The item to trigger the showing of the box.
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/Overlay
     */

    jQuery.obox = function (e, o) {

        this.options		= o || {};

        this.loadingImage       = 'http://media3.washingtonpost.com/wpost/images/loading.gif';
        this.closeImage         = 'http://media3.washingtonpost.com/wpost/images/icons/icon-close.png';
        this.closeImageOver     = 'http://media3.washingtonpost.com/wpost/images/icons/icon-close-over.png';

        this.windowId           = this.options.windowId;
        this.windowTitle        = this.options.windowTitle;

        this.draggable          = this.options.draggable || false;
        this.show_title_bar     = this.options.showTitleBar || false;
        this.show_background    = false;
        this.background_overlay_opacity = this.options.backgroundOverlayOpacity || '';

        this.beforeRevealCallback = this.options.beforeRevealCallback;
        this.beforeCloseClearCallback = this.options.beforeCloseClearCallback;

        this.backgroundOverlayHtml = '<div id="' + this.options.windowId + '-overlay" class="obox-overlay" style="display:none;">&nbsp;</div>';

        this.boxHtml = '\
                <div id="' + this.options.windowId + '" class="obox" style="display:none;">\
                    <div class="popup"></div>\
                    <div class="container">\
                        <div class="titleBar" style="display:none"><div class="window-actions position-right"><div class="close">&nbsp;<a href="#" rel="close"><img src="' + this.closeImage + '" height="15" width="15" alt="Close" /></a></div></div><span>' + this.options.windowTitle + '</span></div>\
                        <div class="content" style="display:none;"></div>\
                        <div class="loading"><img src="' + this.loadingImage + '"/></div>\
                    </div>\
                </div>';

        this.trigr          = jQuery(e);
        this.windr          = null;

        this.rtrn           = null;
        this.bindr          = this.options.bindTo || document;

        this.init();
    };

    jQuery.obox.fn = jQuery.obox.prototype = {
        obox: '1.0'
    };

    jQuery.obox.fn.extend = jQuery.obox.extend = jQuery.extend;

    jQuery.obox.fn.extend({

        init: function() {
            var self = this;

            if (this.background_overlay_opacity != '') {
                this.show_background = true;
                this.overlay = jQuery(this.backgroundOverlayHtml).appendTo("body");
                this.overlay.css('opacity',this.background_overlay_opacity);
                this.overlay.css('position','fixed');
                if (jQuery.browser.msie && jQuery.browser.version=="6.0") {
                    this.overlay.css('position','absolute');
                    this.overlay.css('top','0px');
                    this.overlay.css('left','0px');
                }
                this.overlay.css('height','100%');
                this.overlay.css('width', '100%');
                this.overlay.css('z-index', '1999998');
            }


            this.windr = jQuery(this.boxHtml).appendTo("body");

            if (this.show_background) {
                this.windr.css('z-index', '1999999');
            }

            // enable title bar if needed
            if (this.show_title_bar) {
                jQuery("div.titleBar", this.windr).show();
            }

            // enable draggable if needed
            if (this.draggable) {
                var opts = {
                    cursor : 'move',
                    stack : {
                        group : '.obox',
                        min : 50
                    }
                };
                if (this.show_title_bar) {
                    opts.handle = 'div.titleBar';
                }
                this.windr.draggable(opts);
            }

            // close
            jQuery("div.titleBar div.close a[rel='close']", this.windr).bind('click', function() {
                jQuery(self.bindr).unbind('close_' + self.windowId + '.obox');
                self.close();
                return false;
            });

            // preload images
            var preload = [ new Image(), new Image(), new Image() ];
            preload[0].src = this.loadingImage;
            preload[1].src = this.closeImage;
            preload[2].src = this.closeImageOver;

            jQuery("div.titleBar div.window-actions a[rel='close'] img", this.windr).hover(function() {
                // over
                jQuery(this).attr("src", preload[2].src);
            }, function() {
                // out
                jQuery(this).attr("src", preload[1].src);
            });

            this.trigr.bind('click', function() {
                self.open();
                return false;
            });

            // setup data to return with the triggering of events
            this.rtrn = [ new Object(), new Object() ];
            this.rtrn[0] = this.windr;
            this.rtrn[1] = this.trigr;

            jQuery(this.bindr).trigger('init.obox', this.rtrn);
        },

        open : function() {
            jQuery(this.bindr).trigger('beforeOpen.obox', this.rtrn);

            var self = this;

            // bind closing trigger
            // bind an event to the trigr to request close, so the client doesn't have to search for the object'
            jQuery(this.bindr).bind('close_' + self.windowId + '.obox', function() {
                jQuery(self.bindr).unbind('close_' + self.windowId + '.obox');
                self.close();
            });

            this.windr.css({
                top:	getPageScroll()[1] + (getPageHeight() / 5)
            });

            this.windr.fadeIn("slow");
            this.windr.css('left', (jQuery(window).width() / 2) - (this.windr.width() / 2));

            this.data = fillFromHref(this.trigr.attr("href"));

            jQuery(this.bindr).trigger('open.obox', this.rtrn);
            this.reveal();
        },

        reveal : function() {
            jQuery("div.content", this.windr).append(this.data);

            jQuery(this.bindr).trigger('beforeReveal.obox', this.rtrn);

            if (this.show_background) {
                this.overlay.show();
            }

            if (this.beforeRevealCallback) {
                this.beforeRevealCallback(this.trigr, this.windr);
            }

            jQuery("div.loading", this.windr).fadeOut("normal", function() {
                jQuery("div.content", this.windr).fadeIn("normal");
            });
            jQuery(this.bindr).trigger('reveal.obox', this.rtrn);
        },

        close : function() {
            jQuery(this.bindr).trigger('beforeClose.obox', this.rtrn);
            var self = this;
            if (this.show_background) {
                this.overlay.hide();
            }
            this.windr.fadeOut("normal", function() {
                if (self.beforeCloseClearCallback != undefined) {
                    self.beforeCloseClearCallback(this.trigr, this.windr);
                }
                jQuery("div.content", self.windr).empty();
                jQuery("div.loading", self.windr).show();
                jQuery("div.content", self.windr).hide();
            });
            jQuery(this.bindr).trigger('close.obox', this.rtrn);
        }

    });

    // getPageScroll() by quirksmode.com
    function getPageScroll() {
        var xScroll, yScroll;
        if (this.pageYOffset) {
            yScroll = this.pageYOffset;
            xScroll = this.pageXOffset;
        } else if (document.documentElement && document.documentElement.scrollTop) {	 // Explorer 6 Strict
            yScroll = document.documentElement.scrollTop;
            xScroll = document.documentElement.scrollLeft;
        } else if (document.body) {// all other Explorers
            yScroll = document.body.scrollTop;
            xScroll = document.body.scrollLeft;
        }
        return new Array(xScroll,yScroll);
    }

    // Adapted from getPageSize() by quirksmode.com
    function getPageHeight() {
        var windowHeight
        if (this.innerHeight) {	// all except Explorer
            windowHeight = this.innerHeight;
        } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
            windowHeight = document.documentElement.clientHeight;
        } else if (document.body) { // other Explorers
            windowHeight = document.body.clientHeight;
        }
        return windowHeight;
    }

    // Figures out what you want to display and displays it
    // formats are:
    //      div: #id
    function fillFromHref(href) {
        // div
        if (href.match(/#/)) {
            var url    = window.location.href.split('#')[0];
            var target = href.replace(url,'');
            return jQuery(target).clone().show().html();
        }
        return "";
    }
})(jQuery);
(function(){

    TWP.Module.GlobalHeader = function(){

        var defaults = {
            showWeather : true,
            target : document.getElementById('header-v3'),
            initialized : false,
            headerType : 'default',
            mainNavRoot : document.getElementById('main-nav'),
            mainNavChildren : null,
            navNode : null,
            thisNode : null,
            nodeRoot : null,
            nodeRootChild : null,
            nodeRootChildCategory : null,
            paramList : {},
            nodeMatched : false,
            version : -1,
            browser : null,
            url : window.location.href,
            rootPath : null,
            fileName : null,
            qString : null
        };

        var weather = null;

        // Private Methods
        function getEnvInfo(){
            if (navigator.appName == 'Microsoft Internet Explorer'){
                defaults.browser = "msie";
                var ua = navigator.userAgent;
                var re  = /MSIE ([0-9]{1,}[\.0-9]{0,})/;
                if (re.exec(ua) !== null){
                    defaults.version = parseFloat( RegExp.$1 );
                }
            }

            if(defaults.qString){
                var params = defaults.qString.split("&");

                for(var j=0;j<params.length;j++){
                    var k = params[j].split("=")[0], v = params[j].split("=")[1];
                    defaults.paramList[k] = v;
                }
            }
        }

        // Get children elements
        function getChildren(parent, name){
            var nodes = [];
            for(var r=0;r<parent.childNodes.length;r++){
                if(parent.childNodes[r].nodeType === 1 && parent.childNodes[r].nodeName === name.toUpperCase()){
                    nodes.push(parent.childNodes[r]);
                }
            }
            return nodes;
        }

        // Gets the current date
        function getCurrentDate(){
            var curr = new Date(), day = curr.getDay(), month = curr.getMonth(), date = curr.getDate(), year = curr.getFullYear();
            var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "Decemeber"];
            var days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

            var currDate = document.getElementById('current-date');
            
            if(currDate){
                currDate.innerHTML = days[day] + ", " + months[month] + " " + date + ", " + year;
            }
        }


        function setNavContext(){

            if(!defaults.mainNavRoot){
                return;
            }

            // Check by commercial node
            var mainNavRoot = defaults.mainNavRoot;
            var mainSubNavRoot = document.getElementById('main-sub-nav');
            var mainNavChildren = getChildren(mainNavRoot, 'li');
            var subcategoryNav = document.getElementById('main-category-nav-wrapper');

            for(var a=0;a<mainNavChildren.length;a=a+1){
                var item = mainNavChildren[a];
                if(item.getAttribute('data') == defaults.nodeRoot){
                    var currClass = (item.getAttribute('class')) ? item.getAttribute('class') : '';
                    item.className = (currClass !=  '') ? currClass + ' active' : ' active';
                    defaults.nodeMatched = true;
                    break;
                }
                
            }

            if(mainSubNavRoot){
                var mainSubNavChildren = getChildren(mainSubNavRoot, 'li');
                for(var c=0;c<mainSubNavChildren.length;c=c+1){
                    var item = mainSubNavChildren[c];
                    var dataAttr = (item.getAttribute('data')) ? item.getAttribute('data') : '';
                    if(defaults.nodeRootChild && dataAttr == defaults.nodeRootChild){
                        var currClass = (item.getAttribute('class')) ? item.getAttribute('class') : '';
                        item.setAttribute('class', currClass + ' active');
                        break;
                    }
                }
            }

            // Highlight CategoryNode
            if(subcategoryNav){

                subcategoryNav.style.display = "block"

                var ulNodes = getChildren(subcategoryNav, 'ul');
                for (var i=0;i<ulNodes.length;i++){

                    var dataAttr = ulNodes[i].getAttribute("data");

                    if (dataAttr && dataAttr == defaults.nodeRootChild) {
                        ulNodes[i].style.display = "block";
                      
                        var liNodes = getChildren(ulNodes[i], 'li');

                        for (var j=0;j<liNodes.length;j++) {
                            if (liNodes[j].getAttribute("data") == defaults.nodeRootChildCategory){
                                var currClass = (liNodes[i].getAttribute('class')) ? liNodes[j].getAttribute('class') : '';
                                liNodes[j].className = 'active';
                                
          
                            }
                        }
                    }
                }


                var mainSubNavChildren = getChildren(mainSubNavRoot, 'li');
                for(var c=0;c<mainSubNavChildren.length;c=c+1){
                    var item = mainSubNavChildren[c];
                    var dataAttr = (item.getAttribute('data')) ? item.getAttribute('data') : '';
                    if(defaults.nodeRootChild && dataAttr == defaults.nodeRootChild){
                        var currClass = (item.getAttribute('class')) ? item.getAttribute('class') : '';
                        item.className = 'active';
                        break;
                    }
                }
            }
        }

        function setBranding(){
            var logo = document.getElementById('logo');
            var logoChildren = getChildren(logo, 'a');

            if(defaults.nodeRoot == 'politics'){
                logo.className = defaults.nodeRoot;
                logoChildren[0].setAttribute('href', 'http://www.washingtonpost.com/politics');
            } else if (defaults.nodeRoot == 'business') {
                logo.className = defaults.nodeRoot;
                logoChildren[0].setAttribute('href', 'http://www.washingtonpost.com/business');
            } else if (defaults.nodeRoot == 'local') {
                logo.className = defaults.nodeRoot;
                logoChildren[0].setAttribute('href', 'http://www.washingtonpost.com/local');
            } else if (defaults.nodeRoot == 'national') {
                logo.className = defaults.nodeRoot;
                logoChildren[0].setAttribute('href', 'http://www.washingtonpost.com/national');
            }
        }

        function addEvent(el, evt, callback, cap){
            if(el && evt){
                if(el.addEventListener){
                    el.addEventListener(evt, callback, cap);
                } else {
                    evt = (evt == 'mouseover') ? 'mouseenter' : evt;
                    evt = (evt == 'mouseout') ? 'mouseleave' : evt;
                    el.attachEvent('on' + evt, callback);
                }
            }
        }

        function removeEvent(el, evt, callback, cap){
            if(el && evt){
                if(el.removeEventListener){
                    el.removeEventListener(evt, callback, cap);
                } else {
                    evt = (evt == 'mouseover') ? 'mouseenter' : evt;
                    evt = (evt == 'mouseout') ? 'mouseleave' : evt;
                    el.detachEvent('on' + evt, callback);
                }
            }
        }

        function setAuthenticationLinks(){
            // Determine if the user is authenticated, show the proper creds
            var signin = document.getElementById('global-signin');
            var registration = document.getElementById('global-registration');
            var userName = null;
            var pref = ' | <a href="http://www.washingtonpost.com/ac2/wp-dyn?node=admin/registration/manage&destination=manage&nextstep=gather">Change Preferences</a>';

            if(signin && registration){
                if(TWP.Util.User.getAuthentication()){
                    userName = TWP.Util.User.getUserName();

                    // User is signed in
                    if(TWP.Util.User.getUserType() == 'fbuname'){
                        var html = '<span class="icon facebook sm"><a href="http://www.washingtonpost.com/wp-srv/community/mypost/index.html?newspaperUserId=' + userName + '">' + userName + '</a></span>';
                        if(defaults.nodeRoot == 'mypost'){
                            html += pref;
                        }

                        signin.innerHTML = html;
                        registration.innerHTML = '<a href="http://www.washingtonpost.com/ac2/wp-dyn?node=admin/registration/login&destination=logout&nextstep=confirm">Sign Out</a>';
                        return;
                    }

                    var html = '<span>Hello</span> <a href="http://www.washingtonpost.com/wp-srv/community/mypost/index.html?newspaperUserId=' + userName + '">' + userName + '</a>';
                    if(defaults.nodeRoot == 'mypost'){
                        html += pref;
                    }

                    signin.innerHTML = html;
                    registration.innerHTML = '<a href="http://www.washingtonpost.com/ac2/wp-dyn?node=admin/registration/login&destination=logout&nextstep=confirm">Sign Out</a>';
                } else {
                    signin.innerHTML = '<a href="http://www.washingtonpost.com/ac2/wp-dyn?node=admin/registration/register&destination=login&nextstep=gather&application=reg30-globalnav&applicationURL=' + defaults.url + '">Sign In</a>';
                    registration.innerHTML = '<a href="http://www.washingtonpost.com/ac2/wp-dyn?node=admin/registration/register&destination=register&nextstep=gather&application=reg30-globalnav&applicationURL=' + defaults.url + '">Register Now</a>';
                }
            }
        }

        // Sets up user tools
        function setupUserTools(){
            // Tools menu
            var userTools = document.getElementById('user-tools');
            var utilityWrapper = document.getElementById('utility-wrapper');
            var userToolsActive = false;
            var openTimer = null;
            var closeTimer = null;
            var listItems = getChildren(userTools, 'li');

            function onExpand(){
                addEvent(userTools, 'mouseout', hideTools, true);
            }

            function onCollapse(){
                for(var c=0;c<userTools.childNodes.length;c=c+1){
                    if(userTools.childNodes[c].nodeName == "LI"){
                        var listItem = userTools.childNodes[c];

                        if(listItem.className != ""){
                            listItem.className = (listItem.className).replace('selected', '');
                        }
                    }
                }

                addEvent(userTools, 'mouseover', showTools, false);
            }

            function showTools(e){
                removeEvent(userTools, 'mouseover', showTools, false);

                if(!e){
                    var e = window.event;
                }
                e.cancelBubble = true;

                if (e.stopPropagation){
                    e.stopPropagation();
                }

                if(userToolsActive){
                    clearTimeout(closeTimer);
                    closeTimer = null;
                    return false;
                }

                var setup = {
                    target : utilityWrapper,
                    speed : 300,
                    height : 50,
                    callback : onExpand
                };

                if(!openTimer){
                    openTimer = setTimeout(function(){
                        if(!userToolsActive && utilityWrapper.getAttribute('style') != ''){
                            userToolsActive = true;
                            animate(setup);
                        }
                        openTimer = null;
                    }, 1000);
                } else {
                    clearTimeout(openTimer);
                    openTimer = null;
                }
                return false;
            }

            function hideTools(e){
                var oldRelated = e.relatedTarget;
                var related = e.relatedTarget;
                // Traverse up the tree
                while (related && related != userTools){
                    try {
                        related = related.parentNode;
                    } catch(ex) {
                        related = userTools;
                    }
                }
                if(oldRelated === related || related === null){
                    setup = {
                        target : utilityWrapper,
                        speed : 300,
                        height : 23,
                        callback : onCollapse
                    };

                    closeTimer = setTimeout(function(){
                        if(userToolsActive){
                            removeEvent(userTools, 'mouseout', hideTools, true);
                            animate(setup);
                            userToolsActive = false;
                        }
                    }, 1000);
                } else {
                    return false;
                }
            }

            if(userTools){
                addEvent(userTools, 'mouseover', showTools, false);

                function addSelected(e){
                    if(!e){
                        var e = window.event;
                    }

                    for(var c=0;c<listItems.length;c=c+1){
                        var listItem = listItems[c];
                        if(listItem.className != ""){
                            listItem.className = (listItem.className).replace('selected', '');
                        }
                    }

                    var node = (e.target) ? e.target.parentNode : e.srcElement.parentNode;
                    while (node && node.nodeName != "LI"){
                        node = node.parentNode;
                    }
                    node.className = "selected";
                }

                for(var j=0;j<listItems.length;j=j+1){
                    var li = listItems[j];
                    var anchor = getChildren(li, 'A')[0];
                    addEvent(anchor, 'mouseover', addSelected, false);
                }
            }
        }


        function moveSingleVal(currentVal, finalVal, frameAmt){
            if(frameAmt === 0 || currentVal === finalVal){
                return finalVal;
            }

            currentVal += frameAmt;
            if((frameAmt> 0 && currentVal>= finalVal) || (frameAmt <0 && currentVal <= finalVal)){
                return finalVal;
            }

            return currentVal;
        }

        function doFrame(el, currHt, ht, fHt, callback){
            if(el === null){
                return;
            }
            currHt = moveSingleVal(currHt, ht, fHt);

            if(defaults.browser == 'msie' && defaults.version < 8){
                el.style.height = Math.round(currHt);
            } else {
                el.setAttribute('style', 'height:' + Math.round(currHt) + 'px;');
            }

            if(currHt == ht){
                if(callback !== null){
                    callback();
                }
                return;
            }

            setTimeout(function(){
                doFrame(el, currHt, ht, fHt, callback);
            }, 40);
        }

        function animate(config){
            var el = config.target;
            var speed = config.speed;
            var ht = config.height;
            var currHt = (el.offsetHeight) ? el.offsetHeight : el.style.pixelHeight;
            var totalFrames = 1;
            var callback = config.callback;

            if(speed>0){
                totalFrames = speed/40;
            }

            var fHt = ht - currHt;
            if(ht!==0){
                fHt /= totalFrames;
            }

            doFrame(el, currHt, ht, fHt, callback);
        }

        function setupWeather(){
            weather = new TWP.Module.GlobalWeather();
        }

        // END: Private Methods


        // BEGIN: Set everything up
        getEnvInfo();

        var nodeHierarchy = null;

        // Determine where we are in the heirarchy by nodes
        if(window.thisNode){
            defaults.thisNode = window.thisNode;
        }
        
        if(window.navNode || window.commercialNode){
            defaults.navNode = window.navNode || window.commercialNode;
           

            if(defaults.navNode.indexOf("/")){
                nodeHierarchy = defaults.navNode.split("/");
            }

            if(nodeHierarchy.length){
                defaults.nodeRoot = nodeHierarchy[0];
                if(nodeHierarchy.length > 1){
                    defaults.nodeRootChild = nodeHierarchy[1];
                    if (nodeHierarchy.length > 2) {
                        defaults.nodeRootChildCategory = nodeHierarchy[2];
                    }
                }
            } else {
                defaults.nodeRoot = nodeHierarchy;
            }
        }


        // Initialize the user, available globally
        TWP.Util.User.init();

        // Set global authentication links
        setAuthenticationLinks();

        // Initialize drop menu in IE
        if(defaults.browser == 'msie'){
            setup = {
                target : document.getElementById('main-nav')
            };
            TWP.Util.DropDownMenuIE(setup);
        }

        // Set the navigation context
        setNavContext();

        // set branding
        setBranding();

        if(defaults.showWeather && document.getElementById('global-weather')){
            setupWeather();
        }

        // Get current date
        getCurrentDate();
    };
})();
(function($){

    TWP.Module.Menu = function(setup){
        if(!setup){
            return;
        }

        var config = setup;
        var target = config.target;

        var utilityHt = $('#utility-wrapper').height();
        var animating = false;
        var currTarget = null;
        var wrapperExpanded = false;
        var intv = null;
        var prevItem = null;

        function init(){
            bindEvents();
        }

        function showDrop(){
            alert('')
        }

        function bindEvents(){
            if(!target){
                return;
            }

            var mainNav = target;
            var mainNavItems = [];
            var subNavItems = []

            for(var e=0;e<mainNav.childNodes.length;e=e+1){
                if(mainNav.childNodes[e].nodeType == 1 && mainNav.childNodes[e].nodeName == "LI" ){
                    mainNavItems.push(mainNav.childNodes[e]);
                }
            }


            // setup mouseover
            for(var a=0;a<mainNavItems.length;a=a+1){
                for(var b=0;b<mainNavItems[b].childNodes.length;b=b+1){
                    if(mainNavItems[b].nodeName == "A"){
                        var anchor = mainNavItems[b];
                        anchor.onmouseover = showDrop;
                        break;
                    }
                }
            }



            $(mainNavItems).each(function(){

               $('a.anchor', this).mouseover(function(e){
                    var self = this;

                    clearInterval(intv);
                    intv = null;

                    if(this == prevItem){
                        return;
                    }
                    
                    $(target).find('.active').removeClass('active');

                    $(this).addClass('active');
                    
                    $(target).find('div').removeAttr('style');

                    $(this).siblings('div').attr('style', 'display:block;');

                   function hideMenu(){
                       $('#utility-wrapper').animate({
                           height : utilityHt
                       }, 300, function(){
                            prevItem = null;
                       });
                   }

                    function trackEngagement(){
                        /*$(window).bind('mousemove', function(e){
                            currTarget = $(e.target);
                        });*/
                        
                        /*$('body').bind('mouseleave', function(){
                            hideMenu();
                        });

                        intv = setInterval(function(){
                            if($(currTarget).parents(target).length !== 1){
                                clearInterval(intv);
                                intv = null;
                                hideMenu();
                            }
                        }, 13);*/
                    }

                    if($('#utility-wrapper').height() != config.size){
                        if(animating){
                            return;
                        }

                        animating = true;

                        $('#utility-wrapper').animate({
                            height : config.size
                        }, 300, function(){
                            animating = false;
                            wrapperExpanded = true;
                        });
                    }

                    trackEngagement();

                    return false;
                });
            });
        }

        init();

        return {
            showSubnav : function(){

            },

            hideSubnav : function(){

            }
        }
    }
})(jQuery);
TWP.Module.DialogBox = function(config){
    
    this.id = config.id;

    var defaults = {
        html : '<p>No content</p>',
        container : $('<div id="dialog-' + this.id + '" class="dialog"><div class="content"></div></div>'),
        isAjax : false,
        //ajaxUrl : (config.isAjax && this.target.nodeName.toLowerCase() === 'a') ? $(this.target).attr('href') : (config.isAjax && config.ajaxUrl != '') ? config.ajaxUrl : '',
        isModal: false,
        adjustXY : [0,0],
        scrollable : false,
        width : 100, // defaults to 100px
        height : null,
        context : this,
        center : true,
        renderTo : null,
        wrapper : ''
    }

    this.settings = $.extend(defaults, config);
    this.init();
};


TWP.Module.DialogBox.prototype = {
    
    fixedTop : null,

    init : function(){
        var self = this, settings = this.settings, html = settings.html, content = $('div.content', settings.container);

        if(settings.isAjax){
            this.doXHR();
        } else {
            if(html){

                function injectContent(){

                    if(content){
                        content.append(html);
                    }

                    settings.container.insertBefore($('body').children().eq(0));

                    if(settings.wrapper){
                        $(settings.wrapper).insertBefore(content);
                    }

                    self.setDimensions();
                    self.setCoordinates();
                }

                injectContent();
            }
        }
    },

    doXHR : function(){
        if(settings.url){
            $.ajax({
               url : settings.url,
               dataType : 'html',
               success : function(){

               },

               error : function(){

               }
            });
        }
    },

    setCoordinates : function(){
        var settings = this.settings, center, scrollDelay, that = this;

        // We should always center the box unless otherwise specified
        if(settings.center){
            center = this.getCenter();

            settings.container.css({
                left : center[0] + ((typeof settings.adjustXY[0] == 'number') ? settings.adjustXY[0] : 0),
                top : center[1] + ((typeof settings.adjustXY[1] == 'number') ? settings.adjustXY[1] : 0),
                zIndex : 9999 + that.id
            });

        } else {
            settings.container.css({
               left : ((typeof settings.adjustXY[0] == 'number') ? settings.adjustXY[0] : 0),
               top : ((typeof settings.adjustXY[1] == 'number') ? settings.adjustXY[1] : 0),
                zIndex : 9999 + that.id
            });
        }

        // check for scrollable
        if(settings.scrollable){
            var sWidth = $(document).width(), sHeight = $(document).height();

            window.onscroll = function(){

                center = that.getCenter();
                 
                if($.browser.version != '6.0'){

                    if(!that.fixedTop){
                        var vpHeight = (window.innerHeight) ? window.innerHeight : $(window).height();
                        that.fixedTop = Math.round((vpHeight/2) - (settings.container.height()/2));
                    }

                    settings.container.css({
                        'top' : that.fixedTop,
                        'position' : 'fixed'
                    });

                } else {
                    settings.container.css({
                        'top' : center[1] + 'px'
                    });
                }

                if(!document.getElementById('overlay') && settings.modal == true){
                    $('<div id="overlay">&#xA0;</div>').css({
                        'height' : sHeight,
                        'width' : sWidth
                    }).insertBefore($('body').children().eq(0));
                }

                function resetDialogBox(){
                    if(settings.modal == true){
                        $('#overlay').remove();
                    }
                    
                    setTimeout(function(){
                        settings.container.css({
                            top : center[1],
                            position : 'absolute'
                        });
                    }, 13);

                    $(window).unbind('mouseup');
                }

                $(window).bind('mouseup', resetDialogBox);
            }
        } else {
            window.onscroll = null;
        }
    },

    getCenter : function(){
        var settings = this.settings, left, top, renderToWidth, renderToHeight, centerHorz, centerVert, newWidth, newHeight;
        var vpWidth = (window.innerWidth) ? window.innerWidth : $(window).width();
        var vpHeight = (window.innerHeight) ? window.innerHeight : $(window).height();

        newWidth = (settings.width) ? settings.width : settings.container.width();
        newHeight = (settings.height) ? settings.height : settings.container.height();

        if(settings.renderTo){
            left = TWP.Util.ElPosition.getPos($(settings.renderTo).get(0))[0];
            renderToWidth = $(settings.renderTo).width();
            centerHorz = (Math.round((renderToWidth/2) + left) - (settings.width/2));
        } else {
            centerHorz = Math.round((vpWidth/2) - (newWidth/2));
        }

        if(settings.renderTo){
            top = TWP.Util.ElPosition.getPos($(settings.renderTo).get(0))[1];
            renderToHeight = $(settings.renderTo).height();
            centerVert = (Math.round((renderToHeight/2) + top) - (newHeight/2));
        } else {
            centerVert = Math.round((vpHeight/2) - (newHeight/2) + TWP.Util.WindowScroll.getScrollXY()[1]);
        }

        return [centerHorz, centerVert];
    },

    updateContent : function(html, cb){
        return $('#dialog-' + this.id).find('div.content').html(html);
    },

    showBox : function(cb){
        var self = this, settings = this.settings;

        $('#dialog-' + this.id).fadeIn(250, function(){
            if(typeof cb == 'function'){
                return cb.apply(self.settings.context);
            }
        });
    },

    hideBox : function(destroy, cb){
        var self = this, settings = this.settings;

        TWP.Module.DialogBoxManager.isActive = false;
        
        settings.container.fadeOut(250, function(){
            if(destroy){
                $('#dialog-' + self.id).remove();
            }

            if(settings.scrollable){
                $('#overlay').remove();
                window.onscroll = null;
            }

            if(destroy){
                // Notify the manager
                TWP.Module.DialogBoxManager.destroyBox(self.id);

                if(typeof cb == 'function'){
                    return cb.apply(self.settings.context);
                }
            }
        });
    },

    getIntegerVal: function(v) {
        v = parseInt(v);
        return isNaN(v) ? 0 : v;
    },

    getDimensions : function(el){
        
        el = $(el)
        var w = 0, h = 0;

        if(!$.browser.msie){
            w = this.getIntegerVal($(el).width()) + this.getIntegerVal($(el).css('marginLeft')) + this.getIntegerVal($(el).css('marginRight')) +  this.getIntegerVal($(el).css('paddingLeft')) + this.getIntegerVal($(el).css('paddingRight'));
            h = this.getIntegerVal($(el).height()) + this.getIntegerVal($(el).css('marginTop')) + this.getIntegerVal($(el).css('marginBottom')) + this.getIntegerVal($(el).css('paddingTop')) + this.getIntegerVal($(el).css('paddingBottom'));

        } else {
            w = this.getIntegerVal($(el).width()) + + this.getIntegerVal($(el).css('paddingLeft')) + this.getIntegerVal($(el).css('paddingRight'))
            h = this.getIntegerVal($(el).height()) + this.getIntegerVal($(el).css('paddingTop')) + this.getIntegerVal($(el).css('paddingBottom'));
        }

        return [w, h];
    },
    
    setDimensions : function() {
        var settings =  this.settings, content = $(settings.container).find('div.content'), dialog = $(settings.container).parent().children().eq(0), cth;

        if(settings.wrapper){
            dialog.width(settings.width);

            content.css({
                top : '10px',
                left : '10px'
            });

            // set width
            if(!$.browser.msie){
                content.width(settings.width - 20);
            } else {
                content.width(settings.width - 20);
            }

            // set height
            if(settings.height > 0){
                $('#dialog-' + this.id).height(settings.height);
                $('#dialog-' + this.id).find('div.wrapper').height(settings.height - 20);
            } else {
                // have to use dialog for some reason
                cth = $('#dialog-' + this.id).height();
                $('#dialog-' + this.id).height(cth + 20);
                $('#dialog-' + this.id).find('div.wrapper').height(cth + 20);
                settings.height = cth + 20;
            }
        }
    }
};


(function($){

    TWP.Module.ShareWidget = function(config){

        if(!config && !config.url){
            return;
        }

        var config = config;
        var url = config.url;
        var ctx = config.context;
        var isActive = false;
        var networks = null;
        var inTarget = false;
        var root = null;

        function setNetworks(url, title){
            return networks = [
                {
                    name : 'Facebook',
                    url : 'http://www.facebook.com/sharer.php?u=' + url + '&amp;title=' + title
                },
                {
                    name : 'Digg',
                    url : 'http://digg.com/submit?phase=2&amp;url=' + url + '&amp;title=' + title
                },
                {
                    name : 'Stumble Upon',
                    url : 'http://www.stumbleupon.com/submit?url=' + url + '&title=' + title
                },
                /*{
                    name : 'Myspace',
                    url : 'http://www.myspace.com/Modules/PostTo/Pages/?u=' + url + '&amp;title=' + title
                },*/
                {
                    name : 'Email',
                    url : 'mailto:?subject=The Washington Post: ' + title + '&body=' + title + '%0A' + url
                },
                {
                    name : 'Twitter',
                    url : 'http://twitter.com/home?status=' + title + ' - ' + url
                },
                {
                    name : 'Delicious',
                    url : 'http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url=' + url + '&title=' + title
                },
                {
                    name : 'Yahoo Buzz',
                    url : 'http://buzz.yahoo.com/submit/?submitUrl=' + url + '&amp;title=' + title
                },
                {
                    name : 'LinkedIn',
                    url : 'http://www.linkedin.com/shareArticle?mini=true&url=' + url + '&amp;title=' + title
                }
            ]
        }

        $(config.context).bind('mouseover', function(){
            if(isActive){
                return;
            }

            isActive = true;
            var self = this;

            if($(this).attr('rel') && $(this).attr('rel') !== ''){
                var data = $(this).attr('rel').split('|'); // http://www.google.com|My tittle

                //assign the value to variables and encode it to url friendly
                var url = encodeURIComponent(data[0]);
                var title = encodeURIComponent(data[1]);

                if(url, title){
                    setNetworks(url, title);
                }
            }

            $(this).css('background-position', 'left -64px');

            getShareBox();

            $(this).bind('mouseleave', function(){
                var self = this;
                setTimeout(function(){
                   if(!inTarget){
                        $(self).removeAttr('style')
                        $(this).unbind('mouseleave');
                        $(root).remove();
                        isActive = false;
                   }
                }, 50);
            });
        });

        function getShareBox(){

            root = $('<div id="share-box"></div>');

            // Build columns
            if(networks){
                var len = networks.length;
                var itemsPerCol = Math.ceil(len/2);
                var col1 = $('<ul class="left wp-pad-right"></ul>');
                var col2 = $('<ul class="left"></ul>');
                var box = $('<div class="box"></div>');
                var footer = $('<div class="box-bottom"><div class="corner bot-right"><div>&#xA0;</div></div></div>')

                for(var a=0;a<len;a=a+1){
                   var cls = 'share share-' + ((networks[a].name).toLowerCase()).replace(' ', '-');
                   var item = $('<li><a target="_blank" class="' + cls + '" href="' + networks[a].url + '">' + networks[a].name + '</a></li>');

                   if(a < itemsPerCol){
                       col1.append(item);
                   } else {
                       col2 .append(item)
                   }
                }

                box.append(col1).append(col2);
                root.append(box);
                root.append(footer);

                // get the context's position
                var pos = TWP.Util.ElPosition.getPos(ctx)

                $(root).css({
                    left : pos[0],
                    top : pos[1] + 17
                }).insertBefore($('body').children().eq(0));

                $(root).bind('mouseover', function(e){

                    inTarget = true;

                    $(this).bind('mouseleave', function(e){
                        $(ctx).css('background-position', 'left -48px');
                        $(ctx).unbind('mouseleave');
                        $(root).remove();
                        isActive = false;
                        inTarget = false;
                    });
                    return false;
                });
            }
        }

        return {
            show : function(){

            },

            hide : function(){

            }
        }
    };
})(jQuery);
(function($){

    TWP.Module.Video = function(config){
        var self = this;
        var config = config;
        var queue = null;
        var dialog = null;
        var target = (config.target) ? config.target : null;
        var queue = $(target).find('.queue:eq(0)');
        var numPages = null;
        var isCtrlSetup = false;

        var deck = $(target).find('.deck:eq(0)');
        var deckImg = $('div.image img', deck);
        var deckDesc = $('div.overlay-wrapper p', deck);

        var currItem = null;
        var isActive = false;

        // get the first item content
        var firstItem = $(target).find('.queue:eq(0)').children('li').eq(0);
        $(target).find('.share:eq(0)').attr('rel', $(firstItem).find('a').attr('href') + '|' + $(firstItem).find('h4').text());


        function formatQueue(){
           // the video preview queue uses lhp's structure, lets format the queue first
            var items = [];
            var queue = $('.video-preview').find('.queue:eq(0)');
            var len = queue.children().length;
            var parent = queue.parent();

            queue.children().each(function(i){
                $('div.content div.image', this).append('<div class="overlay"></div>')
                // Add play overlay
                items.push($(this));
            });

            queue.remove();

            var pages = $('<div class="pages"></div>');
            parent.append(pages);

            if(len > 3){
                numPages = Math.ceil(len/3);

                for(var h=0;h<numPages;h++){
                    var page = $('<div></div>').attr('class', 'page' + ((h==0) ? ' selected' : ''));
                    pages.append(page);

                    for(var i=0;i<3;i++){
                        $(page).append(items[(h*3)+i]);
                    }
                }
            }

            addPagination();
        }

        formatQueue();

        // Adds pagination to the controls
        function addPagination(){
            var ctrls = $(target).find('.controls');

            for(var h=0;h<numPages;h++){
                var item = $('<a class="nav-page' + ((h==0) ? ' selected' : '') + ((h==numPages -1) ? ' last' : '') + '" href="#page"><span>Page ' + (h+1) + '</span></a>');
                item.insertBefore($('a.next', ctrls));
            }
        }


        function bindQueueItemEvents(carousel){
            var params = null;
            var flashConfig = null;
            var content = null;

            $(target).find('.content .image a').bind('click', function(){
                return false;
            });

            function initConfig(params, root){
                flashConfig = setupFlashConfig(params);

                content = {
                    title : $(root).find('h4').text(),
                    desc : $(root).find('p').text(),
                    link : $(root).find('a').attr('href'),
                    section : $('#main-nav').find('.active:eq(0)').children('a').text()
                }

                createVideoDialogBox(content);
                createSWF(flashConfig);
            }


            $(target).find('.deck').children('div.overlay-wrapper').children('.overlay').bind('click', function(){
                if(isActive){
                    return;
                }

                isActive = true;
                params = TWP.Util.Url.getParameters($(firstItem).find('a').attr('rel'));
                initConfig(params, $(firstItem));

               return false;
            });

            $(target).find('.image').each(function(){

                var self = this;


                $('a', self).bind('click', function(e){
                    if(isActive){
                        return;
                    }

                    isActive = true;

                    if($(this).attr('rel') !== undefined){
                        params = TWP.Util.Url.getParameters($(this).attr('rel'));
                        initConfig(params, $(this).parent().parent());
                    }
                });

                $(self).bind('click', function(e){
                    if(isActive){
                        return;
                    }

                    isActive = true;

                    var root = ($('a', this).attr('rel') !== undefined) ? $(self).parent() : $(firstItem);
                    // check to see if item has an anchor, if not grab the first item
                    params = TWP.Util.Url.getParameters($(root).find('a').attr('rel'));
                    initConfig(params, $(root));

                    return false;
                });

            });
        }

        function setupFlashConfig(params){
            var flashConfig = {
                jsonURL:params['jsonURL']
            }

            return flashConfig;
        }

        function bindNav(carousel){
            self.carouselProps = carousel.props;

            // bind navigation
            self.ctrls = $(target).find('.controls');
            var prev = $('.prev', self.ctrls);
            var pages = $('.nav-page', self.ctrls);
            var next = $('.next', self.ctrls);

            $(prev).bind('click', function(){
                carousel.previous();
                return false;
            });

            $(next).bind('click', function(){
                carousel.next();
                return false;
            });

            $(pages).each(function(i){
                $(this).bind('click', function(i){
                    return false;
                });
            });
        }

        function createVideoDialogBox(params){
            
            if(TWP.Module.DialogBoxManager.isActive){
                return;
            }

            var vSocialNetwork = '<ul class="social-networking-counts inline"><li><span rel="' + params.link  + '|' + params.title + '" class="social-network icon share"></span></li></ul>';

            var vBoxRoot = $('<div id="video-dialog-box"></div>');
            var vTitlebar = $('<div class="titlebar"><h6 class="twp-logo-128">The Washington Post</h6><span> | </span>' + params.section + ' Video<div class="button close"></div></div>');
            var vFooter = $('<div class="footer"><h2><a href="' + params.link + '">' + params.title + '</a></h2><p>' + params.desc + '</p>' + vSocialNetwork + '</div>');
            var swfTarget = $('<div id="video-dialog-box-target"></div>');

            vBoxRoot.append(vTitlebar);
            vBoxRoot.append(swfTarget);
            vBoxRoot.append(vFooter);

            var setup = {
                html : vBoxRoot,
                width : 896,
                height : 694,
                wrapper : '<div class="wrapper"></div>',
                context : this
            }

            dialog = TWP.Module.DialogBoxManager.createBox(setup);
        }


        // Create swf
        function createSWF(flashVars){
            var params = {bgcolor: '#FFFFFF', wMode: 'Opaque', allowScriptAccess: 'always', swLiveConnect: 'true'}

            if(swfobject.embedSWF && typeof swfobject.embedSWF == 'function'){
                swfobject.embedSWF("http://media10.washingtonpost.com/wp/swf/OmniPlayer.swf", "video-dialog-box-target", "856", "486", "10", "expressInstall.swf", flashVars, params, '', '', this.onVideoLoad());
            }
        }

        // Public methods
        this.setupVideoQueue = function(carousel){
            bindQueueItemEvents(carousel);
            if(!isCtrlSetup){
                bindNav(carousel);
                isCtrlSetup = true;
            }
        }

        this.showDeckPreview = function(item){
            // Find all the necessary fields
            var link = $('div.content div.image a', item).attr('href');
            var imgSrc = $('div.content div.image a img', item).attr('rel');
            var title = $('div.content h4', item).text();
            var deck = $('div.content p', item).text();

            deckImg.attr('src', imgSrc);
            deckDesc.html(title);
        }

        this.scrolled  = function(carousel){
            var idx = self.carouselProps.currIndex;

            // update pages
            $('.nav-page', self.ctrls).each(function(i){
                if(i == idx){
                    $(this).addClass('selected');
                } else {
                    $(this).removeClass('selected');
                }
            });
        }

        this.onVideoLoad = window['onVideoLoad'] = function(){

            // find share
            var share = new TWP.Module.ShareWidget({context : $('#dialog-' + dialog.id).find('.share').get(0)});

            dialog.showBox(function(){
                var close = $('#dialog-' + dialog.id).find('.close');

                close.bind('click', function(){
                   $('#dialog-' + dialog.id).find('object').remove();
                   dialog.hideBox(true);
                   delete dialog;
                   isActive = false;
                });
            });
        }

        // initalization
        var carouselSetup = {
            queue : '.pages',
            vertical : true,
            initCallback : self.setupVideoQueue,
            onBeforeScrollCallback : self.scrolled,
            onAfterScrollCallback : self.setupVideoQueue,
            context : self
        }

        $(target).carousel(carouselSetup);
    }

})(jQuery);
(function($){

    TWP.Module.GlobalNewsletterForm = function(config){

        var config = config;
        var ctx = config.context;
        var errors = [];

        // Get form checkboxes
        var chxBoxes = $(ctx).find('input[type="checkbox"]');
        var email = $(ctx).find(".email:eq(0)");
        var errMsg = $(ctx).find('.errors:eq(0)');
        var token = '';

        var defaultText = {
            "distribution-subscribe" : "Your e-mail address"
        };

        var userId = TWP.Util.User.getUserId();

        if(userId){
            var isEmail = TWP.Util.FormValidation.validateEmailAddress(userId);
            if(isEmail){
                email.val(userId).attr('disabled', "disabled");
            }
        } else {
            email = $(email).get(0);
            if(email){
                email.defaultValue = "Enter your e-mail address";
            }
        }

        function determineReg(newsletter, returnURL){
            // recognized users will have a uprof cookie and a wpniuser cookie
            var uprof = TWP.Util.Cookie.read("UPROF");
            var wpniuser = TWP.Util.Cookie.read("wpniuser");;

            if (wpniuser != null && uprof != null){
                //User is recognized
                window.open("http://www.washingtonpost.com/ac2/wp-dyn?node=admin/email/express&action=subscribe&newsletter_code=" + newsletter, "", "scrollbars=no,toolbar=no,width=300,height=232");
            } else {
                //User is not recognized
                location.href = "http://www.washingtonpost.com/ac2/wp-dyn?node=admin/registration/register&destination=register&nextstep=gather&newsletter_code=" + newsletter + "&application=Origin%20Page&applicationURL=" + returnURL;
            }
        }

        function validate(){
            var isValid = false;
            token = '';

            if($(chxBoxes).length == 0){
                token = $(ctx).find('.hiddenToken').attr('name');
                isValid = true;
            }

            $(chxBoxes).each(function(i){
                if(this.checked){
                    var val = $(this).attr('name');
                    token = (token != '') ? token + ',' + val : val;
                    isValid = true
                }
            });

            return isValid;
        }
        
        $('#distribution').submit(function(){
            var emailAddy = $(email).val();
            var validEmail = TWP.Util.FormValidation.validateEmailAddress(emailAddy);
            var hasNewsletter = validate();

            errors = [];

            if(!validEmail || validEmail == null){
                errors.push("Please enter a valid email address.");
            }

            if(hasNewsletter == false){
                errors.push("Please select one or more newsletters.");
            }

            $(errMsg).empty();

            $(errors).each(function(i){
                $(errMsg).append("<li>" + errors[i] + "</li>");
                $(errMsg).show();
            });

            if(errors.length == 0){
                determineReg(token, window.location);
            }
            
            return false;
        });
    }
})(jQuery);
TWP.Module.DynamicLedeStacked = {
    
	carousel : null,
    strLoadingImg : '',
    intvObj : null,
    interval : 10000,
    arrSections : [],
    nav : null,
    carouselPackage : [],  // Array of packages
    currIndex : 0,
    carouselPos : [],
    navIntvObj : null,
    observers : [],


    init : function()
    {
		var inst = this;
		this.carousel = $(".hero-dynamic-lede:eq(0)");
		this.nav = $("ul.packages", this.carousel);
		this.carouselPackage = $("li.package", this.nav);
		this.bindHover();
		this.start();  // Starts the auto cycle
    },

    bindHover : function(){
		var inst = this;

		$(this.carouselPackage).each(function(i){

			$(this).mouseover(function(){

				var currObj = this;

				// this interval controls carousel cycling
				inst.intvObj.stop();


				// this interval controls nav
				if(inst.navIntvObj === null){
					inst.navIntvObj = new Interval(400);
				}


				inst.navIntvObj.listen('run', function(e){
					inst.getPackageByMouse(currObj, i);
					inst.navIntvObj.stop();
				});

				inst.navIntvObj.start();

			});

			$(this).mouseout(function(){
				inst.intvObj.restart();

				if(inst.navIntvObj !== null){
					inst.navIntvObj.stop();
					inst.navIntvObj = null;
				}
			});
		});
    },

    getPackageByMouse : function(currObj, i){
		// if package is showing, do nothing
        var len = this.carouselPackage.length;
		if($(currObj).hasClass('selected')){
			return;
		}

		$(this.carouselPackage).removeClass('selected').removeClass('previous');
		$(currObj).addClass('selected');
		$(currObj).prev().addClass('previous');

		$('div.content div.package-content', currObj).css("display", "none");

		var pkgContent = $('div.content div.package-content', currObj);

		this.showContent(pkgContent, i);
		this.notify(pkgContent);
    },

    start : function(){

		var inst = this;
		var totalPkgs = this.carouselPackage.length;

		if(this.intvObj === null){
			this.intvObj = new Interval(parseInt(this.interval));
		}

		this.intvObj.listen('run', function(e){

		    if (inst.currIndex == totalPkgs - 1) {
		        inst.currIndex = 0;
		    } else {
		        inst.currIndex++;
		    }

			inst.selectPackage(inst.carouselPackage[inst.currIndex], inst.currIndex);
		});

		this.intvObj.start();
    },

    selectPackage : function(carouselPackage, index){

		var inst = this;

		if($(carouselPackage).hasClass('selected')){
			return;
		}

		$(this.carouselPackage).each(function(i){
			$(this).removeClass('selected').removeClass('previous');
			// removes the border from the previous item
			if(i == (index - 1)){
				$(this).addClass("previous");
			}

			$('div.content div.package-content', this).css("display", "none");
		});

		$(carouselPackage).addClass('selected');

		var pkgContent = $('div.content div.package-content', carouselPackage);

		this.showContent(pkgContent, index);
		this.notify(pkgContent);
    },

    showContent : function(pkgContent, index){
		if($.browser.msie){
			$(pkgContent).show();
		} else {
			$(pkgContent).fadeIn(300);
		}

		this.currIndex = index;
    },

    hideContent : function(){

		$('div.content div.package-content', this.carouselPackage[this.currIndex]).hide();
    },

    subscribe : function(obj){
		if(obj){
			this.observers.push(obj);
		}
    },

    notify : function(context){
		if(this.observers.length > 0){
			for(var c in this.observers){
				var b = this.observers[c];
				b.obj[b.callback](context)
			}
		}
    }
};
TWP.Module.DialogBoxManager = {

    counter : 0,
    instances : [],
    subscribers : [],
    multiInstance : false,
    isActive : false,

    createBox : function(config){
        var dBox = null;

        if(this.isActive){
            return;
        }

        if(config && config.modal){
            this.isActive = true;
        }

        //this.isActive = true;
        //this.subscribers.push(subscriber);

        // add the id to the config
        if(!config.hasOwnProperty('id')){
            config.id = this.instances.length;
        }

        dBox = new TWP.Module.DialogBox(config);

        if(typeof dBox == 'object'){
            this.instances.push({
                box : dBox,
                id : config.id
            });
        }

        return dBox;
    },

    destroyBox : function(instanceId){
        var inst;

        for(var a in this.instances){
           if(this.instances[a].id == instanceId){

                // TO DO: clean up this.instances

                //console.log(a)
                //console.log(this.instances[a].id)
                inst = this.instances[a];
                //this.instances.splice(a, 1);
                //console.log(this.instances);
                delete inst;
           }
        }
    }
}



/*	SWFObject v2.2 <http://code.google.com/p/swfobject/> 
	is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();
(function($){

    TWP.Module.CarouselModule = function(obj){

        var self = this;

        this.init = function(carousel){

            self.carouselProps = carousel.props;

            // bind navigation
            self.ctrls = $(obj).find('.controls');
            var prev = $('.prev', self.ctrls);
            var pages = $('.nav-page', self.ctrls);
            var next = $('.next', self.ctrls);

            $(prev).bind('click', function(){
                carousel.previous();
                return false;
            });

            $(next).bind('click', function(){
                carousel.next();
                return false;
            });

            $(pages).each(function(i){
                $(this).bind('click', function(i){
                    return false;
                });
            });
        }

        this.scrolled = function(){

            var idx = self.carouselProps.currIndex;
            // update pages
            $('.nav-page', self.ctrls).each(function(i){
                if(i == idx){
                    $(this).addClass('selected');
                } else {
                    $(this).removeClass('selected');
                }
            });

            // update share widgets if any
            $(obj).find('.share').each(function(){
                var self = this;
                new TWP.Module.ShareWidget({context : self});
            });
        }

        var queue = ($(obj).find('.pages').length > 0) ? '.pages' : '.queue';

        // initalization
        var carouselSetup = {
            queue : '.pages',
            vertical : true,
            initCallback : self.init,
            onNewPageCallback : self.newPage,
            onBeforeScrollCallback : self.scrolled,
            context : self
        }

        $(obj).carousel(carouselSetup);
    };
})(jQuery);

