// /js/jquery.jcarousel.js
/**
 * jCarousel - Riding carousels with jQuery
 *   http://sorgalla.com/jcarousel/
 *
 * Copyright (c) 2006 Jan Sorgalla (http://sorgalla.com)
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * Built on top of the jQuery library
 *   http://jquery.com
 *
 * Inspired by the "Carousel Component" by Bill Scott
 *   http://billwscott.com/carousel/
 */

(function($) {
    /**
     * Creates a carousel for all matched elements.
     *
     * @example $("#mycarousel").jcarousel();
     * @before <ul id="mycarousel" class="jcarousel-skin-name"><li>First item</li><li>Second item</li></ul>
     * @result
     *
     * <div class="jcarousel-skin-name">
     *   <div class="jcarousel-container">
     *     <div disabled="disabled" class="jcarousel-prev jcarousel-prev-disabled"></div>
     *     <div class="jcarousel-next"></div>
     *     <div class="jcarousel-clip">
     *       <ul class="jcarousel-list">
     *         <li class="jcarousel-item-1">First item</li>
     *         <li class="jcarousel-item-2">Second item</li>
     *       </ul>
     *     </div>
     *   </div>
     * </div>
     *
     * @name jcarousel
     * @type jQuery
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.fn.jcarousel = function(o) {
        return this.each(function() {
            new $jc(this, o);
        });
    };

    // Default configuration properties.
    var defaults = {
        vertical: false,
        start: 1,
        offset: 1,
        size: null,
        scroll: 3,
        visible: null,
        animation: 'normal',
        easing: 'swing',
        auto: 0,
        wrap: null,
        initCallback: null,
        reloadCallback: null,
        itemLoadCallback: null,
        itemFirstInCallback: null,
        itemFirstOutCallback: null,
        itemLastInCallback: null,
        itemLastOutCallback: null,
        itemVisibleInCallback: null,
        itemVisibleOutCallback: null,
        buttonNextHTML: '<div></div>',
        buttonPrevHTML: '<div></div>',
        buttonNextEvent: 'click',
        buttonPrevEvent: 'click',
        buttonNextCallback: null,
        buttonPrevCallback: null
    };

    /**
     * The jCarousel object.
     *
     * @constructor
     * @name $.jcarousel
     * @param Object e The element to create the carousel for.
     * @param Hash o A set of key/value pairs to set as configuration properties.
     * @cat Plugins/jCarousel
     */
    $.jcarousel = function(e, o) {
        this.options    = $.extend({}, defaults, o || {});

        this.locked     = false;

        this.container  = null;
        this.clip       = null;
        this.list       = null;
        this.buttonNext = null;
        this.buttonPrev = null;

        this.wh = !this.options.vertical ? 'width' : 'height';
        this.lt = !this.options.vertical ? 'left' : 'top';

        // Extract skin class
        var skin = '', split = e.className.split(' ');

        for (var i = 0; i < split.length; i++) {
            if (split[i].indexOf('jcarousel-skin') != -1) {
                $(e).removeClass(split[i]);
                var skin = split[i];
                break;
            }
        }

        if (e.nodeName == 'UL' || e.nodeName == 'OL') {
            this.list = $(e);
            this.container = this.list.parent();

            if (this.container.hasClass('jcarousel-clip')) {
                if (!this.container.parent().hasClass('jcarousel-container'))
                    this.container = this.container.wrap('<div></div>');

                this.container = this.container.parent();
            } else if (!this.container.hasClass('jcarousel-container'))
                this.container = this.list.wrap('<div></div>').parent();
        } else {
            this.container = $(e);
            this.list = $(e).find('>ul,>ol,div>ul,div>ol');
        }

        if (skin != '' && this.container.parent()[0].className.indexOf('jcarousel-skin') == -1)
        	this.container.wrap('<div class=" '+ skin + '"></div>');

        this.clip = this.list.parent();

        if (!this.clip.length || !this.clip.hasClass('jcarousel-clip'))
            this.clip = this.list.wrap('<div></div>').parent();

        this.buttonPrev = $('.jcarousel-prev', this.container);

        if (this.buttonPrev.size() == 0 && this.options.buttonPrevHTML != null)
            this.buttonPrev = this.clip.before(this.options.buttonPrevHTML).prev();

        this.buttonPrev.addClass(this.className('jcarousel-prev'));

        this.buttonNext = $('.jcarousel-next', this.container);

        if (this.buttonNext.size() == 0 && this.options.buttonNextHTML != null)
            this.buttonNext = this.clip.before(this.options.buttonNextHTML).prev();

        this.buttonNext.addClass(this.className('jcarousel-next'));

        this.clip.addClass(this.className('jcarousel-clip'));
        this.list.addClass(this.className('jcarousel-list'));
        this.container.addClass(this.className('jcarousel-container'));

        var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
        var li = this.list.children('li');

        var self = this;

        if (li.size() > 0) {
            var wh = 0, i = this.options.offset;
            li.each(function() {
                self.format(this, i++);
                wh += self.dimension(this, di);
            });

            this.list.css(this.wh, wh + 'px');

            // Only set if not explicitly passed as option
            if (!o || o.size === undefined)
                this.options.size = li.size();
        }

        // For whatever reason, .show() does not work in Safari...
        this.container.css('display', 'block');
        this.buttonNext.css('display', 'block');
        this.buttonPrev.css('display', 'block');

        this.funcNext   = function() { self.next(); };
        this.funcPrev   = function() { self.prev(); };
        this.funcResize = function() { self.reload(); };

        if (this.options.initCallback != null)
            this.options.initCallback(this, 'init');

        if ($.browser.safari) {
            this.buttons(false, false);
            $(window).bind('load', function() { self.setup(); });
        } else
            this.setup();
    };

    // Create shortcut for internal use
    var $jc = $.jcarousel;

    $jc.fn = $jc.prototype = {
        jcarousel: '0.2.3'
    };
	 
    $jc.fn.extend = $jc.extend = $.extend;

    $jc.fn.extend({
        /**
         * Setups the carousel.
         *
         * @name setup
         * @type undefined
         * @cat Plugins/jCarousel
         */
        setup: function() {
            this.first     = null;
            this.last      = null;
            this.prevFirst = null;
            this.prevLast  = null;
            this.animating = false;
            this.timer     = null;
            this.tail      = null;
            this.inTail    = false;

            if (this.locked)
                return;

            this.list.css(this.lt, this.pos(this.options.offset) + 'px');
            var p = this.pos(this.options.start);
            this.prevFirst = this.prevLast = null;
            this.animate(p, false);

            $(window).unbind('resize', this.funcResize).bind('resize', this.funcResize);
        },

        /**
         * Clears the list and resets the carousel.
         *
         * @name reset
         * @type undefined
         * @cat Plugins/jCarousel
         */
        reset: function() {
            this.list.empty();

            this.list.css(this.lt, '0px');
            this.list.css(this.wh, '10px');

            if (this.options.initCallback != null)
                this.options.initCallback(this, 'reset');

            this.setup();
        },

        /**
         * Reloads the carousel and adjusts positions.
         *
         * @name reload
         * @type undefined
         * @cat Plugins/jCarousel
         */
        reload: function() {
            if (this.tail != null && this.inTail)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + this.tail);

            this.tail   = null;
            this.inTail = false;

            if (this.options.reloadCallback != null)
                this.options.reloadCallback(this);

            if (this.options.visible != null) {
                var self = this;
                var di = Math.ceil(this.clipping() / this.options.visible), wh = 0, lt = 0;
                $('li', this.list).each(function(i) {
                    wh += self.dimension(this, di);
                    if (i + 1 < self.first)
                        lt = wh;
                });

                this.list.css(this.wh, wh + 'px');
                this.list.css(this.lt, -lt + 'px');
            }

            this.scroll(this.first, false);
        },

        /**
         * Locks the carousel.
         *
         * @name lock
         * @type undefined
         * @cat Plugins/jCarousel
         */
        lock: function() {
            this.locked = true;
            this.buttons();
        },

        /**
         * Unlocks the carousel.
         *
         * @name unlock
         * @type undefined
         * @cat Plugins/jCarousel
         */
        unlock: function() {
            this.locked = false;
            this.buttons();
        },

        /**
         * Sets the size of the carousel.
         *
         * @name size
         * @type undefined
         * @param Number s The size of the carousel.
         * @cat Plugins/jCarousel
         */
        size: function(s) {
            if (s != undefined) {
                this.options.size = s;
                if (!this.locked)
                    this.buttons();
            }

            return this.options.size;
        },

        /**
         * Checks whether a list element exists for the given index (or index range).
         *
         * @name get
         * @type bool
         * @param Number i The index of the (first) element.
         * @param Number i2 The index of the last element.
         * @cat Plugins/jCarousel
         */
        has: function(i, i2) {
            if (i2 == undefined || !i2)
                i2 = i;

            if (this.options.size !== null && i2 > this.options.size)
            	i2 = this.options.size;

            for (var j = i; j <= i2; j++) {
                var e = this.get(j);
                if (!e.length || e.hasClass('jcarousel-item-placeholder'))
                    return false;
            }

            return true;
        },

        /**
         * Returns a jQuery object with list element for the given index.
         *
         * @name get
         * @type jQuery
         * @param Number i The index of the element.
         * @cat Plugins/jCarousel
         */
        get: function(i) {
            return $('.jcarousel-item-' + i, this.list);
        },

        /**
         * Adds an element for the given index to the list.
         * If the element already exists, it updates the inner html.
         * Returns the created element as jQuery object.
         *
         * @name add
         * @type jQuery
         * @param Number i The index of the element.
         * @param String s The innerHTML of the element.
         * @cat Plugins/jCarousel
         */
        add: function(i, s) {
            var e = this.get(i), old = 0, add = 0;

            if (e.length == 0) {
                var c, e = this.create(i), j = $jc.intval(i);
                while (c = this.get(--j)) {
                    if (j <= 0 || c.length) {
                        j <= 0 ? this.list.prepend(e) : c.after(e);
                        break;
                    }
                }
            } else
                old = this.dimension(e);

            e.removeClass(this.className('jcarousel-item-placeholder'));
            typeof s == 'string' ? e.html(s) : e.empty().append(s);

            var di = this.options.visible != null ? Math.ceil(this.clipping() / this.options.visible) : null;
            var wh = this.dimension(e, di) - old;

            if (i > 0 && i < this.first)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - wh + 'px');

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) + wh + 'px');

            return e;
        },

        /**
         * Removes an element for the given index from the list.
         *
         * @name remove
         * @type undefined
         * @param Number i The index of the element.
         * @cat Plugins/jCarousel
         */
        remove: function(i) {
            var e = this.get(i);

            // Check if item exists and is not currently visible
            if (!e.length || (i >= this.first && i <= this.last))
                return;

            var d = this.dimension(e);

            if (i < this.first)
                this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) + d + 'px');

            e.remove();

            this.list.css(this.wh, $jc.intval(this.list.css(this.wh)) - d + 'px');
        },

        /**
         * Moves the carousel forwards.
         *
         * @name next
         * @type undefined
         * @cat Plugins/jCarousel
         */
        next: function() {
            this.stopAuto();

            if (this.tail != null && !this.inTail)
                this.scrollTail(false);
            else
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'last') && this.options.size != null && this.last == this.options.size) ? 1 : this.first + this.options.scroll);
        },

        /**
         * Moves the carousel backwards.
         *
         * @name prev
         * @type undefined
         * @cat Plugins/jCarousel
         */
        prev: function() {
            this.stopAuto();

            if (this.tail != null && this.inTail)
                this.scrollTail(true);
            else
                this.scroll(((this.options.wrap == 'both' || this.options.wrap == 'first') && this.options.size != null && this.first == 1) ? this.options.size : this.first - this.options.scroll);
        },

        /**
         * Scrolls the tail of the carousel.
         *
         * @name scrollTail
         * @type undefined
         * @param Bool b Whether scroll the tail back or forward.
         * @cat Plugins/jCarousel
         */
        scrollTail: function(b) {
            if (this.locked || this.animating || !this.tail)
                return;

            var pos  = $jc.intval(this.list.css(this.lt));

            !b ? pos -= this.tail : pos += this.tail;
            this.inTail = !b;

            // Save for callbacks
            this.prevFirst = this.first;
            this.prevLast  = this.last;

            this.animate(pos);
        },

        /**
         * Scrolls the carousel to a certain position.
         *
         * @name scroll
         * @type undefined
         * @param Number i The index of the element to scoll to.
         * @param Bool a Flag indicating whether to perform animation.
         * @cat Plugins/jCarousel
         */
        scroll: function(i, a) {
            if (this.locked || this.animating)
                return;

            this.animate(this.pos(i), a);
        },

        /**
         * Prepares the carousel and return the position for a certian index.
         *
         * @name pos
         * @type Number
         * @param Number i The index of the element to scoll to.
         * @cat Plugins/jCarousel
         */
        pos: function(i) {
            if (this.locked || this.animating)
                return;

            if (this.options.wrap != 'circular')
                i = i < 1 ? 1 : (this.options.size && i > this.options.size ? this.options.size : i);

            var back = this.first > i;
            var pos  = $jc.intval(this.list.css(this.lt));

            // Create placeholders, new list width/height
            // and new list position
            var f = this.options.wrap != 'circular' && this.first <= 1 ? 1 : this.first;
            var c = back ? this.get(f) : this.get(this.last);
            var j = back ? f : f - 1;
            var e = null, l = 0, p = false, d = 0;

            while (back ? --j >= i : ++j < i) {
                e = this.get(j);
                p = !e.length;
                if (e.length == 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    c[back ? 'before' : 'after' ](e);
                }

                c = e;
                d = this.dimension(e);

                if (p)
                    l += d;

                if (this.first != null && (this.options.wrap == 'circular' || (j >= 1 && (this.options.size == null || j <= this.options.size))))
                    pos = back ? pos + d : pos - d;
            }

            // Calculate visible items
            var clipping = this.clipping();
            var cache = [];
            var visible = 0, j = i, v = 0;
            var c = this.get(i - 1);

            while (++visible) {
                e = this.get(j);
                p = !e.length;
                if (e.length == 0) {
                    e = this.create(j).addClass(this.className('jcarousel-item-placeholder'));
                    // This should only happen on a next scroll
                    c.length == 0 ? this.list.prepend(e) : c[back ? 'before' : 'after' ](e);
                }

                c = e;
                var d = this.dimension(e);
                if (d == 0) {
                    //alert('jCarousel: No width/height set for items. This will cause an infinite loop. Aborting...');
                    return 0;
                }

                if (this.options.wrap != 'circular' && this.options.size !== null && j > this.options.size)
                    cache.push(e);
                else if (p)
                    l += d;

                v += d;

                if (v >= clipping)
                    break;

                j++;
            }

             // Remove out-of-range placeholders
            for (var x = 0; x < cache.length; x++)
                cache[x].remove();

            // Resize list
            if (l > 0) {
                this.list.css(this.wh, this.dimension(this.list) + l + 'px');

                if (back) {
                    pos -= l;
                    this.list.css(this.lt, $jc.intval(this.list.css(this.lt)) - l + 'px');
                }
            }

            // Calculate first and last item
            var last = i + visible - 1;
            if (this.options.wrap != 'circular' && this.options.size && last > this.options.size)
                last = this.options.size;

            if (j > last) {
                visible = 0, j = last, v = 0;
                while (++visible) {
                    var e = this.get(j--);
                    if (!e.length)
                        break;
                    v += this.dimension(e);
                    if (v >= clipping)
                        break;
                }
            }

            var first = last - visible + 1;
            if (this.options.wrap != 'circular' && first < 1)
                first = 1;

            if (this.inTail && back) {
                pos += this.tail;
                this.inTail = false;
            }

            this.tail = null;
            if (this.options.wrap != 'circular' && last == this.options.size && (last - visible + 1) >= 1) {
                var m = $jc.margin(this.get(last), !this.options.vertical ? 'marginRight' : 'marginBottom');
                if ((v - m) > clipping)
                    this.tail = v - clipping - m;
            }

            // Adjust position
            while (i-- > first)
                pos += this.dimension(this.get(i));

            // Save visible item range
            this.prevFirst = this.first;
            this.prevLast  = this.last;
            this.first     = first;
            this.last      = last;

            return pos;
        },

        /**
         * Animates the carousel to a certain position.
         *
         * @name animate
         * @type undefined
         * @param mixed p Position to scroll to.
         * @param Bool a Flag indicating whether to perform animation.
         * @cat Plugins/jCarousel
         */
        animate: function(p, a) {
            if (this.locked || this.animating)
                return;

            this.animating = true;

            var self = this;
            var scrolled = function() {
                self.animating = false;

                if (p == 0)
                    self.list.css(self.lt,  0);

                if (self.options.wrap == 'both' || self.options.wrap == 'last' || self.options.size == null || self.last < self.options.size)
                    self.startAuto();

                self.buttons();
                self.notify('onAfterAnimation');
            };

            this.notify('onBeforeAnimation');

            // Animate
            if (!this.options.animation || a == false) {
                this.list.css(this.lt, p + 'px');
                scrolled();
            } else {
                var o = !this.options.vertical ? {'left': p} : {'top': p};
                this.list.animate(o, this.options.animation, this.options.easing, scrolled);
            }
        },

        /**
         * Starts autoscrolling.
         *
         * @name auto
         * @type undefined
         * @param Number s Seconds to periodically autoscroll the content.
         * @cat Plugins/jCarousel
         */
        startAuto: function(s) {
            if (s != undefined)
                this.options.auto = s;

            if (this.options.auto == 0)
                return this.stopAuto();

            if (this.timer != null)
                return;

            var self = this;
            this.timer = setTimeout(function() { self.next(); }, this.options.auto * 1000);
        },

        /**
         * Stops autoscrolling.
         *
         * @name stopAuto
         * @type undefined
         * @cat Plugins/jCarousel
         */
        stopAuto: function() {
            if (this.timer == null)
                return;

            clearTimeout(this.timer);
            this.timer = null;
        },

        /**
         * Sets the states of the prev/next buttons.
         *
         * @name buttons
         * @type undefined
         * @cat Plugins/jCarousel
         */
        buttons: function(n, p) {
            if (n == undefined || n == null) {
                var n = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'first') || this.options.size == null || this.last < this.options.size);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'first') && this.options.size != null && this.last >= this.options.size)
                    n = this.tail != null && !this.inTail;
            }

            if (p == undefined || p == null) {
                var p = !this.locked && this.options.size !== 0 && ((this.options.wrap && this.options.wrap != 'last') || this.first > 1);
                if (!this.locked && (!this.options.wrap || this.options.wrap == 'last') && this.options.size != null && this.first == 1)
                    p = this.tail != null && this.inTail;
            }

            var self = this;

            this.buttonNext[n ? 'bind' : 'unbind'](this.options.buttonNextEvent, this.funcNext)[n ? 'removeClass' : 'addClass'](this.className('jcarousel-next-disabled')).attr('disabled', n ? false : true);
            this.buttonPrev[p ? 'bind' : 'unbind'](this.options.buttonPrevEvent, this.funcPrev)[p ? 'removeClass' : 'addClass'](this.className('jcarousel-prev-disabled')).attr('disabled', p ? false : true);

            if (this.buttonNext.length > 0 && (this.buttonNext[0].jcarouselstate == undefined || this.buttonNext[0].jcarouselstate != n) && this.options.buttonNextCallback != null) {
                this.buttonNext.each(function() { self.options.buttonNextCallback(self, this, n); });
                this.buttonNext[0].jcarouselstate = n;
            }

            if (this.buttonPrev.length > 0 && (this.buttonPrev[0].jcarouselstate == undefined || this.buttonPrev[0].jcarouselstate != p) && this.options.buttonPrevCallback != null) {
                this.buttonPrev.each(function() { self.options.buttonPrevCallback(self, this, p); });
                this.buttonPrev[0].jcarouselstate = p;
            }
        },

        notify: function(evt) {
            var state = this.prevFirst == null ? 'init' : (this.prevFirst < this.first ? 'next' : 'prev');

            // Load items
            this.callback('itemLoadCallback', evt, state);

            if (this.prevFirst !== this.first) {
                this.callback('itemFirstInCallback', evt, state, this.first);
                this.callback('itemFirstOutCallback', evt, state, this.prevFirst);
            }

            if (this.prevLast !== this.last) {
                this.callback('itemLastInCallback', evt, state, this.last);
                this.callback('itemLastOutCallback', evt, state, this.prevLast);
            }

            this.callback('itemVisibleInCallback', evt, state, this.first, this.last, this.prevFirst, this.prevLast);
            this.callback('itemVisibleOutCallback', evt, state, this.prevFirst, this.prevLast, this.first, this.last);
        },

        callback: function(cb, evt, state, i1, i2, i3, i4) {
            if (this.options[cb] == undefined || (typeof this.options[cb] != 'object' && evt != 'onAfterAnimation'))
                return;

            var callback = typeof this.options[cb] == 'object' ? this.options[cb][evt] : this.options[cb];

            if (!$.isFunction(callback))
                return;

            var self = this;

            if (i1 === undefined)
                callback(self, state, evt);
            else if (i2 === undefined)
                this.get(i1).each(function() { callback(self, this, i1, state, evt); });
            else {
                for (var i = i1; i <= i2; i++)
                    if (i !== null && !(i >= i3 && i <= i4))
                        this.get(i).each(function() { callback(self, this, i, state, evt); });
            }
        },

        create: function(i) {
            return this.format('<li></li>', i);
        },

        format: function(e, i) {
            var $e = $(e).addClass(this.className('jcarousel-item')).addClass(this.className('jcarousel-item-' + i));
            $e.attr('jcarouselindex', i);
            return $e;
        },

        className: function(c) {
            return c + ' ' + c + (!this.options.vertical ? '-horizontal' : '-vertical');
        },

        dimension: function(e, d) {
            var el = e.jquery != undefined ? e[0] : e;

            var old = !this.options.vertical ?
                el.offsetWidth + $jc.margin(el, 'marginLeft') + $jc.margin(el, 'marginRight') :
                el.offsetHeight + $jc.margin(el, 'marginTop') + $jc.margin(el, 'marginBottom');

            if (d == undefined || old == d)
                return old;

            var w = !this.options.vertical ?
                d - $jc.margin(el, 'marginLeft') - $jc.margin(el, 'marginRight') :
                d - $jc.margin(el, 'marginTop') - $jc.margin(el, 'marginBottom');

            $(el).css(this.wh, w + 'px');

            return this.dimension(el);
        },

        clipping: function() {
            return !this.options.vertical ?
                this.clip[0].offsetWidth - $jc.intval(this.clip.css('borderLeftWidth')) - $jc.intval(this.clip.css('borderRightWidth')) :
                this.clip[0].offsetHeight - $jc.intval(this.clip.css('borderTopWidth')) - $jc.intval(this.clip.css('borderBottomWidth'));
        },

        index: function(i, s) {
            if (s == undefined)
                s = this.options.size;

            return Math.round((((i-1) / s) - Math.floor((i-1) / s)) * s) + 1;
        }
    });

    $jc.extend({
        /**
         * Gets/Sets the global default configuration properties.
         *
         * @name defaults
         * @descr Gets/Sets the global default configuration properties.
         * @type Hash
         * @param Hash d A set of key/value pairs to set as configuration properties.
         * @cat Plugins/jCarousel
         */
        defaults: function(d) {
            return $.extend(defaults, d || {});
        },

        margin: function(e, p) {
            if (!e)
                return 0;

            var el = e.jquery != undefined ? e[0] : e;

            if (p == 'marginRight' && $.browser.safari) {
                var old = {'display': 'block', 'float': 'none', 'width': 'auto'}, oWidth, oWidth2;

                $.swap(el, old, function() { oWidth = el.offsetWidth; });

                old['marginRight'] = 0;
                $.swap(el, old, function() { oWidth2 = el.offsetWidth; });

                return oWidth2 - oWidth;
            }

            return $jc.intval($.css(el, p));
        },

        intval: function(v) {
            v = parseInt(v);
            return isNaN(v) ? 0 : v;
        }
    });

})(jQuery);

// /js/jquery.cookies.2.1.0.min.js
/**
 * Copyright (c) 2005 - 2009, James Auldridge
 * All rights reserved.
 *
 * Licensed under the BSD, MIT, and GPL (your choice!) Licenses:
 *  http://code.google.com/p/cookies/wiki/License
 *
 */
var jaaulde=window.jaaulde||{};jaaulde.utils=jaaulde.utils||{};jaaulde.utils.cookies=(function()
{var cookies=[];var defaultOptions={hoursToLive:null,path:'/',domain:null,secure:false};var resolveOptions=function(options)
{var returnValue;if(typeof options!=='object'||options===null)
{returnValue=defaultOptions;}
else
{returnValue={hoursToLive:(typeof options.hoursToLive==='number'&&options.hoursToLive!==0?options.hoursToLive:defaultOptions.hoursToLive),path:(typeof options.path==='string'&&options.path!==''?options.path:defaultOptions.path),domain:(typeof options.domain==='string'&&options.domain!==''?options.domain:defaultOptions.domain),secure:(typeof options.secure==='boolean'&&options.secure?options.secure:defaultOptions.secure)};}
return returnValue;};var expiresGMTString=function(hoursToLive)
{var dateObject=new Date();dateObject.setTime(dateObject.getTime()+(hoursToLive*60*60*1000));return dateObject.toGMTString();};var assembleOptionsString=function(options)
{options=resolveOptions(options);return((typeof options.hoursToLive==='number'?'; expires='+expiresGMTString(options.hoursToLive):'')+'; path='+options.path+
(typeof options.domain==='string'?'; domain='+options.domain:'')+
(options.secure===true?'; secure':''));};var splitCookies=function()
{cookies={};var pair,name,value,separated=document.cookie.split(';');for(var i=0;i<separated.length;i=i+1)
{pair=separated[i].split('=');name=pair[0].replace(/^\s*/,'').replace(/\s*$/,'');value=decodeURIComponent(pair[1]);cookies[name]=value;}
return cookies;};var constructor=function(){};constructor.prototype.get=function(cookieName)
{var returnValue;splitCookies();if(typeof cookieName==='string')
{returnValue=(typeof cookies[cookieName]!=='undefined')?cookies[cookieName]:null;}
else if(typeof cookieName==='object'&&cookieName!==null)
{returnValue={};for(var item in cookieName)
{if(typeof cookies[cookieName[item]]!=='undefined')
{returnValue[cookieName[item]]=cookies[cookieName[item]];}
else
{returnValue[cookieName[item]]=null;}}}
else
{returnValue=cookies;}
return returnValue;};constructor.prototype.filter=function(cookieNameRegExp)
{var returnValue={};splitCookies();if(typeof cookieNameRegExp==='string')
{cookieNameRegExp=new RegExp(cookieNameRegExp);}
for(var cookieName in cookies)
{if(cookieName.match(cookieNameRegExp))
{returnValue[cookieName]=cookies[cookieName];}}
return returnValue;};constructor.prototype.set=function(cookieName,value,options)
{if(typeof value==='undefined'||value===null)
{if(typeof options!=='object'||options===null)
{options={};}
value='';options.hoursToLive=-8760;}
var optionsString=assembleOptionsString(options);document.cookie=cookieName+'='+encodeURIComponent(value)+optionsString;};constructor.prototype.del=function(cookieName,options)
{var allCookies={};if(typeof options!=='object'||options===null)
{options={};}
if(typeof cookieName==='boolean'&&cookieName===true)
{allCookies=this.get();}
else if(typeof cookieName==='string')
{allCookies[cookieName]=true;}
for(var name in allCookies)
{if(typeof name==='string'&&name!=='')
{this.set(name,null,options);}}};constructor.prototype.test=function()
{var returnValue=false,testName='cT',testValue='data';this.set(testName,testValue);if(this.get(testName)===testValue)
{this.del(testName);returnValue=true;}
return returnValue;};constructor.prototype.setOptions=function(options)
{if(typeof options!=='object')
{options=null;}
defaultOptions=resolveOptions(options);};return new constructor();})();(function()
{if(window.jQuery)
{(function($)
{$.cookies=jaaulde.utils.cookies;var extensions={cookify:function(options)
{return this.each(function()
{var i,resolvedName=false,resolvedValue=false,name='',value='',nameAttrs=['name','id'],nodeName,inputType;for(i in nameAttrs)
{if(!isNaN(i))
{name=$(this).attr(nameAttrs[i]);if(typeof name==='string'&&name!=='')
{resolvedName=true;break;}}}
if(resolvedName)
{nodeName=this.nodeName.toLowerCase();if(nodeName!=='input'&&nodeName!=='textarea'&&nodeName!=='select'&&nodeName!=='img')
{value=$(this).html();resolvedValue=true;}
else
{inputType=$(this).attr('type');if(typeof inputType==='string'&&inputType!=='')
{inputType=inputType.toLowerCase();}
if(inputType!=='radio'&&inputType!=='checkbox')
{value=$(this).val();resolvedValue=true;}}
if(resolvedValue)
{if(typeof value!=='string'||value==='')
{value=null;}
$.cookies.set(name,value,options);}}});},cookieFill:function()
{return this.each(function()
{var i,resolvedName=false,name='',value,nameAttrs=['name','id'],iteration=0,nodeName;for(i in nameAttrs)
{if(!isNaN(i))
{name=$(this).attr(nameAttrs[i]);if(typeof name==='string'&&name!=='')
{resolvedName=true;break;}}}
if(resolvedName)
{value=$.cookies.get(name);if(value!==null)
{nodeName=this.nodeName.toLowerCase();if(nodeName==='input'||nodeName==='textarea'||nodeName==='select')
{$(this).val(value);}
else
{$(this).html(value);}}}
iteration=0;});},cookieBind:function(options)
{return this.each(function()
{$(this).cookieFill().change(function()
{$(this).cookify(options);});});}};$.each(extensions,function(i)
{$.fn[i]=this;});})(window.jQuery);}})();
// /js/jquery.timers.js
jQuery.fn.extend({
	everyTime: function(interval, label, fn, times, belay) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, times, belay);
		});
	},
	oneTime: function(interval, label, fn) {
		return this.each(function() {
			jQuery.timer.add(this, interval, label, fn, 1);
		});
	},
	stopTime: function(label, fn) {
		return this.each(function() {
			jQuery.timer.remove(this, label, fn);
		});
	}
});

jQuery.extend({
	timer: {
		guid: 1,
		global: {},
		regex: /^([0-9]+)\s*(.*s)?$/,
		powers: {
			// Yeah this is major overkill...
			'ms': 1,
			'cs': 10,
			'ds': 100,
			's': 1000,
			'das': 10000,
			'hs': 100000,
			'ks': 1000000
		},
		timeParse: function(value) {
			if (value == undefined || value == null)
				return null;
			var result = this.regex.exec(jQuery.trim(value.toString()));
			if (result[2]) {
				var num = parseInt(result[1], 10);
				var mult = this.powers[result[2]] || 1;
				return num * mult;
			} else {
				return value;
			}
		},
		add: function(element, interval, label, fn, times, belay) {
			var counter = 0;
			
			if (jQuery.isFunction(label)) {
				if (!times) 
					times = fn;
				fn = label;
				label = interval;
			}
			
			interval = jQuery.timer.timeParse(interval);

			if (typeof interval != 'number' || isNaN(interval) || interval <= 0)
				return;

			if (times && times.constructor != Number) {
				belay = !!times;
				times = 0;
			}
			
			times = times || 0;
			belay = belay || false;
			
			if (!element.$timers) 
				element.$timers = {};
			
			if (!element.$timers[label])
				element.$timers[label] = {};
			
			fn.$timerID = fn.$timerID || this.guid++;
			
			var handler = function() {
				if (belay && this.inProgress) 
					return;
				this.inProgress = true;
				if ((++counter > times && times !== 0) || fn.call(element, counter) === false)
					jQuery.timer.remove(element, label, fn);
				this.inProgress = false;
			};
			
			handler.$timerID = fn.$timerID;
			
			if (!element.$timers[label][fn.$timerID]) 
				element.$timers[label][fn.$timerID] = window.setInterval(handler,interval);
			
			if ( !this.global[label] )
				this.global[label] = [];
			this.global[label].push( element );
			
		},
		remove: function(element, label, fn) {
			var timers = element.$timers, ret;
			
			if ( timers ) {
				
				if (!label) {
					for ( label in timers )
						this.remove(element, label, fn);
				} else if ( timers[label] ) {
					if ( fn ) {
						if ( fn.$timerID ) {
							window.clearInterval(timers[label][fn.$timerID]);
							delete timers[label][fn.$timerID];
						}
					} else {
						for ( var fn in timers[label] ) {
							window.clearInterval(timers[label][fn]);
							delete timers[label][fn];
						}
					}
					
					for ( ret in timers[label] ) break;
					if ( !ret ) {
						ret = null;
						delete timers[label];
					}
				}
				
				for ( ret in timers ) break;
				if ( !ret ) 
					element.$timers = null;
			}
		}
	}
});

if (jQuery.browser.msie)
	jQuery(window).one("unload", function() {
		var global = jQuery.timer.global;
		for ( var label in global ) {
			var els = global[label], i = els.length;
			while ( --i )
				jQuery.timer.remove(els[i], label);
		}
	});

// /js/globalFunctions.jquery.js

// jQuery Plugins and Functions

/**
 * Animate Backgrounds
 * @author Alexander Farkas
 * v. 1.1
 */

(function($){
	
	if(!document.defaultView || !document.defaultView.getComputedStyle){
		var oldCurCSS = jQuery.curCSS;
		jQuery.curCSS = function(elem, name, force){
			if(name !== 'backgroundPosition' || !elem.currentStyle || elem.currentStyle[ name ]){
				return oldCurCSS.apply(this, arguments);
			}
			var style = elem.style;
			if ( !force && style && style[ name ] ){
				return style[ name ];
			}
			return oldCurCSS(elem, 'backgroundPositionX', force) +' '+ oldCurCSS(elem, 'backgroundPositionY', force);
		};
	}
})(jQuery);

(function($) {
	
	function toArray(strg){
		strg = strg.replace(/left|top/g,'0px');
		strg = strg.replace(/right|bottom/g,'100%');
		strg = strg.replace(/([0-9\.]+)(\s|\)|$)/g,"$1px$2");
		var res = strg.match(/(-?[0-9\.]+)(px|\%|em|pt)\s(-?[0-9\.]+)(px|\%|em|pt)/);
		return [parseFloat(res[1],10),res[2],parseFloat(res[3],10),res[4]];
	}
	
	$.fx.step. backgroundPosition = function(fx) {
		if (!fx.bgPosReady) {
			
			var start = $.curCSS(fx.elem,'backgroundPosition');
			if(!start){//FF2 no inline-style fallback
				start = '0px 0px';
			}
			
			start = toArray(start);
			fx.start = [start[0],start[2]];
			
			var end = toArray(fx.options.curAnim.backgroundPosition);
			fx.end = [end[0],end[2]];
			
			fx.unit = [end[1],end[3]];
			fx.bgPosReady = true;
		}
		
		var nowPosX = [];
		nowPosX[0] = ((fx.end[0] - fx.start[0]) * fx.pos) + fx.start[0] + fx.unit[0];
		nowPosX[1] = ((fx.end[1] - fx.start[1]) * fx.pos) + fx.start[1] + fx.unit[1];           
		fx.elem.style.backgroundPosition = nowPosX[0]+' '+nowPosX[1];

	};
})(jQuery);

// AD SYNCHING ------------------------------------------------------------------------
var adTile = 1;
var ordinal = Math.floor( (Math.random() * 100000000));


function loadAds ()
{
    var banner = document.getElementById("thetopContainer");
    var bbox = document.getElementById("bigboxContainer");
    
//    if (banner != null && banner != 'undefined')
//    {
//        var adUrl = getAdUrl ("thetop", ""); 
//        multiTagSyncRoadBlock ("thetop");
//    }   
    if (bbox != null && bbox != 'undefined')
    {
        var adUrl = getAdUrl ("bigbox", "");
        multiTagSyncRoadBlock ("bigbox");
    }   
}


function getAdSize(type) 
{ 
    var size = "";
    if( type.toLowerCase() == 'banner' || type.toLowerCase() == 'thetop'  ) 
        size = "468x60";

    if( type.toLowerCase() == 'bbox' || type.toLowerCase() == 'bigbox' ) 
        size = "250x250";

    if( type.toLowerCase() == 'sky' ) 
        size = "120x240";
        
    return size;        
} 

function getAdUrl(location, kws) 
{
    var zone = getZone();
    var keywords = "kw=globaltv;" + 
                getKeywords(zone) + 
                ";" + kws;
    var adSize = getAdSize (location);  
    var adUrl = "";  

    adUrl = "http://ad.ca.doubleclick.net/N6872/adi/global_prg.com" + zone + ";" + keywords + ";sz=" + adSize + ";tile=1;dc_seed=213106815";
    
    return adUrl;
}

function getZone ()
{
    var url = "";
    var startPos = 0;

    //remove the domain...
    url = document.location.toString().replace("http://", "");
    startPos = url.indexOf("/");
    url = url.substring(startPos, url.length);
    
    //remove question marks
    startPos = url.indexOf("?");
    if (startPos>0)
        url = url.substring(0, startPos);

    //remove #
    startPos = url.indexOf("#");
    if (startPos>0)
        url = url.substring(0, startPos);
            
    //remove html, htm...
    url = url.replace(".html", "").replace(".htm", "");
    
    return url + ";";    
}  

function getKeywords (zone)
{
    if (zone == null || zone == 'undefined')
        return "";
    var parts= zone.split('/');
    if (parts == null || parts == 'undefined' || parts.length ==0)
        return "";
    var i=0;
    var kws = "";
    
    for (i=0; i<parts.length; i++)
        if (parts[i] != null && parts[i] != "" && parts[i] != "/")
            kws+= "kw=" + parts[i] + ";";
    return kws;
}  


/**************************************
	Instantiations Begin
************************************/


function submitSearch(value) {
	if (!value)
		return false;
	
    var urlBuilder = new UrlBuilder("/pages/SearchResult.aspx");
    urlBuilder.setSearch(value, "NewsSearch");
    window.location.replace(urlBuilder.toString());

    return false;    
}

/* 
 * SEARCH BOX BEHAVIOR START 
 */
$(function() { //document ready
    // START MAIN SEARCH
    var mainOriginal = $(".hybridSearch").attr("value");
    $("#headerInner .hybridSearch").focus(function(ev) {
        $(this).addClass("focused");
        if ($(this).val() == mainOriginal) {
            $(this).val("").css("color", "#000000");
        }
    });
    $("#headerInner .hybridSearch").blur(function(ev) {
        $(this).removeClass("focused");
        if ($(this).val() == "") {
            $(this).val(mainOriginal).css("color", "#666666");
        }
    });
    $("#headerInner .hybridSearch").keyup(function(ev) {
        if (ev.keyCode == 13) {
            if ($(this).val() == "" || $(this).val() == mainOriginal) {
                $(this).focus();
            } else {
                // Do not remove this from here and place in inline onclick.
				ev.preventDefault();
                return submitSearch($(this).val());
            }
        }
    });
    $("#headerInner .search_button").click(function(ev) {
		if (($("#headerInner.hybridSearch").val() == mainOriginal) || ($("#headerInner.hybridSearch").val() == "")) {
            $("#headerInner.hybridSearch").focus();
        } else {
			ev.preventDefault();
            submitSearch($("#headerInner .hybridSearch").val());
        }
        return false;
    });
    // END MAIN SEARCH	

    // START SEARCH PAGE CODE
	
	$("#Search #Submit").click(function(ev) {
		ev.preventDefault();
		submitSearch($("#Search .q").val());
	});
	
	// PREVENT Enter-key presses in the main body search area from firing
	// the main form's default submit button, and fire the one we want instead. 
	$("#Search .q").keypress(function(ev) {
		if (ev.keyCode == 13) {
			ev.preventDefault();
			submitSearch($("#Search .q").val());
		}
	});
	

/* 
	SEARCH BOX BEHAVIOR END
*/
/* 
	HOMEPAGE NEWS VIDEO SLIDER WIDGET BEGIN 
*/
	//$(".newsVideo ul li:first").addClass("noLeftMargin")

	try {
		$(".newsVideo ul").jcarousel({
	        // Configuration goes here	
	    });
	} catch (err) {};

/* 
	HOMEPAGE NEWS VIDEO SLIDER WIDGET END 
*/
/* 
	HOMEPAGE LOCAL WIDGET START 
*/
	var localStationCookie = $.cookies.get('localStation');
	if(!localStationCookie){
		//if no cookie.  show BC
		$("#widgetLocalNewsBC").show();
		$.cookies.set('localStation', 'BC', {hoursToLive:672});
		var localStation = "BC"
	} else {
		var localStationID = "#widgetLocalNews" + localStationCookie;
		$(localStationID).show();
	}
	
	$("#widgetLocalNewsSelect select").change(function(){ 
		var target = $(this).val(); 
		$(".localNewsContent").hide();
		$(target).show(); 
		$.cookies.set('localStation', target.substr(16), {hoursToLive:24*7*4} );
	});
	
	$("#newsSelect select").change(function()
		{
			var target = $(this).val();
			if ((target != "http://www.globalnews.ca") && (target != "http://www.globalnational.com") && (target != "http://www.chbcnews.ca"))
			{
				target = target.replace(/http\:\/\/www\.global(tv)?/gi, "");
				target = target.replace(/\.com/gi, "");
				target = target.substr(0, 1).toUpperCase() + target.substr(1);
			}
			else if (target == "http://www.chbcnews.ca")
			{
				target = 'Okanagan';
			}
			$.cookies.set('localStation', target, {hoursToLive:672} );
		}
	);
/* 
	HOMEPAGE LOCAL WIDGET END 
*/
/*
	Breaking News
*/
	$("#breakingNews").hover(
		function () {
			$(this).animate(
				{backgroundPosition:"(56px 0px)"}, 
				{duration:500, easing:"linear"}
			).animate(
				{backgroundPosition:"(0px 0px)"}, 
				{duration:0}
			);
			$(this).everyTime(500, 'scrollBack', function(){
				$(this).animate(
					{backgroundPosition:"(56px 0px)"}, 
					{duration:500, easing:"linear"}
				).animate(
					{backgroundPosition:"(0px 0px)"}, 
					{duration:0}
				);
			/*
			
			var bgImageSrc = $(this).css("background-image").replace(/url\(/, "");
			var bgImageSrc = bgImageSrc.replace(/\)/, "");
			var bgImage = new Image();
			bgImage.src = bgImageSrc;
			var bgPos = $(this).css("background-position").split(" ");
			var newLeftBgPos = bgPos[0].replace(/px/, "");
			newLeftBgPos++;
			if(newLeftBgPos >= bgImage.width){
				newLeftBgPos = 0
			}
			var newBgPos = newLeftBgPos + "px " + bgPos[1];
			$(this).css("background-position", newBgPos);
			*/
			});
		}, 
		function () {
			$(this).stopTime('scrollBack');
		}
    );

/*
	End Doc Ready.
*/
});



// /js/tabbedSections.js



/* widget tabbed sections */	

$(function(){
	
	$(".widgetTabbedSections .tabsContainer").css("display","block");
	if($(".widgetTabbedSections #tabHeadlines ul li")[0]){
		$(".widgetTabbedSections #tabHeadlines").tabs();
		$(".widgetTabbedSections #tabHeadlines .tabTitleList").lavaLamp({
			fx: 'easeOutSine',
			autoReturn: false,
			speed: 500
		});
	} else {
		$(".widgetTabbedSections #tabHeadlines").remove();
		$("#tabHeadlinesItem").remove();
	}
	if($(".widgetTabbedSections #tabPopular ul li")[0]){
		$(".widgetTabbedSections #tabPopular").tabs();
		$(".widgetTabbedSections #tabPopular .tabTitleList").lavaLamp({
			fx: 'easeOutSine',
			autoReturn: false,
			speed: 500
		});
	} else {
		$(".widgetTabbedSections #tabPopular").remove();
		$("#tabPopularItem").remove();
	}
	if($(".widgetTabbedSections #tabVideo ul li")[0]){
		$(".widgetTabbedSections #tabVideo").tabs();
		$(".widgetTabbedSections #tabVideo .tabTitleList").lavaLamp({
			fx: 'easeOutSine',
			autoReturn: false,
			speed: 500
		});
	} else {
		$(".widgetTabbedSections #tabVideo").remove();
		$("#tabVideoItem").remove();
	}
	try {
		$(".widgetTabbedSections").tabs();
	} catch (e) {};
	//$(".widgetTabbedSections #tabVideo").tabs();

	/*
	$(".widgetTabbedSections #tabVideo .tabTitleList").lavaLamp({
		fx: 'easeOutSine',
		autoReturn: false,
		speed: 500
	});
	*/
	//$("a[href='#tabPopular']").parent().remove();
	cycleTime = 5000;
	initTime = 10000;
	idleTime = 20000;

	currTab = "tabHeadlines";
	currTabNum = 1;
	prevTab = "";
	
	//set up a one time timer to trigger tab animation after initTime
	$(".widgetTabbedSections #"+currTab).oneTime(initTime,'tabsListTimer',initTabsListTimer);	
	//both the animation timer and the idle timer use the same timer ref, tabsListTimer
	//since neither will be active at the same time
	
	//set height of itemMediaAbstract to height of ul+h5 elements, so that overflow will produce scrollbars
	var h = $(".widgetTabbedSections #"+currTab+" .tabTitleList").height() + $("#"+currTab+" h5").height();
	if(h<280){h=280;}
	$(".widgetTabbedSections .itemMediaAbstract").css("height", h);
	
	$(".widgetTabbedSections .tabsList a").each(function(i){
		$(this).click(function(e){
			//when click new tab set curr num to 1
			currTabNum = 1;
			//update previous tab to current tab
			prevTab = currTab;
			//find new tab name from a href
			currTab = $(this).attr("href").substr(1);
			
			//set height of itemMediaAbstract to height of ul+h5 elements, so that overflow will produce scrollbars
			var h = $(".widgetTabbedSections #"+currTab+" .tabTitleList").height() + $("#"+currTab+" h5").height() + 20;
			//$(".widgetTabbedSections .itemMediaAbstract").css("height", h);
			if(h<280){h=280;}
			$(".widgetTabbedSections #"+currTab).css("height", h);
			
			//make sure first link in headlineTitleList is triggered
			$(".widgetTabbedSections #"+currTab+" a:eq("+(currTabNum-1)+")").click();
			//but also need backLava to jump immediately, not animate up
			move($(".widgetTabbedSections #"+currTab+" li:first").get(0));

			/* believe this is redundant since the mouse over/out code should catch when user leaves the list
			but may need cause initial idleTime is not working currently */
			//if new tab has backLava ul
			if(e.pageX){
				//stop previous cycle
				//had to move timer on/off here cause code inited trigger was causing initTime timer to overwrite with idleTime
				$(".widgetTabbedSections #"+prevTab).stopTime('tabsListTimer');
				if( $(".widgetTabbedSections #"+currTab+" a.backLava") ){
					$(".widgetTabbedSections #"+currTab).oneTime(idleTime,'tabsListTimer',initTabsListTimer);
				}
			}
		})		
	});
	//set this up so when user clicks a link it updates the currTabNum
	$(".widgetTabbedSections .tabsContainer div.tabList ul li a").each(function(){
		$(this).click(function(e){
			//update currTabNum to reflect the one clicked
			currTabNum = $(this).attr("href").substr( $(this).attr("href").length-1 );
			currTabDivID = $(this).attr("href");
			//if is no event pageX value, then user did not trigger click action
			if(e.pageX){
				$(".widgetTabbedSections #"+currTab).stopTime('tabsListTimer');
				//set up new timer to restart after n seconds
				//$(".widgetTabbedSections #"+currTab).oneTime(idleTime,'tabsListTimer',initTabsListTimer);
				if(!$(this).hasClass("readyToClick")){
					$(".readyToClick").removeClass("readyToClick");
					$(this).addClass("readyToClick");
				} else {
					window.location = $($(this).attr("href")+" h4 a").attr("href");
				}
			} else {
				if(!$(this).hasClass("readyToClick")){
					$(".readyToClick").removeClass("readyToClick");
					$(this).addClass("readyToClick");
				} 
			}
			//currTabNum is being set twice, once here and once in tabsListAnimate
		});
	});

	//when user mouses over the tabsContainer, stop all animation
	$(".widgetTabbedSections .tabsContainer").mouseenter(function(){
		$(".widgetTabbedSections #"+currTab).stopTime('tabsListTimer');
		//alert("enter");
	}).mouseleave(function(){
		$(".widgetTabbedSections #"+currTab).oneTime(idleTime,'tabsListTimer',initTabsListTimer);
		//alert("out");
	});
	
/*	
	$(".widgetTabbedSections .tabTitleList li a").focus(function(event){
		$(this).trigger("click");
	}); 
	$(".widgetTabbedSections .tabTitleList li a").click(function(e){
		if(e.pageX){
			// user click
			// GOOGLE: track click
			// if 2nd click
		}
	}); 
*/


	$(".widgetTabbedSections .tabsList a:first").click(); // Required in order to ensure overflow and height calculation on first item  This line should be the last line in this document ready block.
	
});



function initTabsListTimer(){
	$(".widgetTabbedSections #"+currTab).everyTime(cycleTime,'tabsListTimer',tabsListAnimate);
};

function tabsListAnimate(){
	if(currTabNum>$(".widgetTabbedSections #"+currTab+" ul li").length){
		currTabNum = 1;
	} else {
		currTabNum++
	}
	//use trigger instead so can differentiate between user clicks and animated trigger
	$(".widgetTabbedSections #"+currTab+" a:eq("+(currTabNum-1)+")").trigger('click');
};

//stole this function from the lavalamp plugin so can have the backLava jump to first a when switch tabs
function move(el) {
	// .backLava element border check and animation fix
	var bx=0, by=0, px=0;
	$back = $(".widgetTabbedSections #"+currTab+" .backLava");
	//if browser is not IE
	if (!jQuery.browser.msie) {
		bx = Math.floor(($back.outerWidth() - $back.innerWidth())/2);
		by = Math.floor(($back.outerHeight() - $back.innerHeight())/2);
	//if is IE 8
	} else if(jQuery.browser.msie==true && jQuery.browser.version=="8.0"){
		px=0;
	//for other IE versions
	} else {
		px=1;
	}
	$back.stop()
	.animate({
		left: el.offsetLeft-bx+px,
		top: el.offsetTop-by,
		width: el.offsetWidth,
		height: el.offsetHeight
	}, 0, 'easeOutSine');
};

// /js/jquery.lavalamp.1.3.2.js
/**
 * LavaLamp - A menu plugin for jQuery with cool hover effects.
 *** MODIFIED ***
 */

(function(jQuery) {
jQuery.fn.lavaLamp = function(o) {
	o = jQuery.extend({ fx: 'swing', 
					  	speed: 500, 
						click: function(){return true}, 
						startItem: 'no',
						autoReturn: true,
						returnDelay: 0,
						setOnClick: true,
						homeTop:0,
						homeLeft:0,
						homeWidth:0,
						homeHeight:0,
						returnHome:false
						}, 
					o || {});

	return this.each(function() {
		var path = location.pathname + location.search + location.hash;
		var $selected = new Object;
		var delayTimer;
		var $back;
		var $home;
		var ce;
		
		//
		// create homeLava element if origin and dimensions set and startItem == off
		if (o.homeTop || o.homeLeft) { 
			$home = jQuery('<li class="homeLava selectedLava"></li>').css({ left:o.homeLeft, top:o.homeTop, width:o.homeWidth, height:o.homeHeight, position:'absolute' });
			jQuery(this).prepend($home);
		}
		
		var $li = jQuery('li', this);
		// check for complete path match, if so flag element into $selected
		if ( o.startItem == 'no' )
			$selected = jQuery('li a[href$="' + path + '"]', this).parent('li');
			
		// double check, this may be just an anchor match
		if ($selected.length == 0 && o.startItem == 'no' && location.hash)
			$selected = jQuery('li a[href$="' + location.hash + '"]', this).parent('li');

		// no default selected element matches worked, 
		// or the user specified an index via startItem
		if ($selected.length == 0 || o.startItem != 'no') {
			// always default to first item, if no startItem specified.
			if (o.startItem == 'no') o.startItem = 0;
			$selected = jQuery($li[o.startItem]);
		}
		// set up raw element - this allows user override by class .selectedLava on load
		ce = jQuery('li.selectedLava', this)[0] || jQuery($selected).addClass('selectedLava')[0];

		
		// add mouseover event for every sub element
		/*
		$li.mouseover(function() {
			if (jQuery(this).hasClass('homeLava')) {
				ce = jQuery(this)[0];
			}
			move(this);
		});
		*/
		
		//modified from original lavalamp to fit with widgetTabbedSections
		$li.find("a").click(function(){
			//move(this);
			move($(this).parent().get(0));
		});


		$back = jQuery('<li class="backLava"><div class="leftLava"></div><div class="bottomLava"></div><div class="cornerLava"></div></li>').appendTo(this);
		
		// after we leave the container element, move back to default/last clicked element
		jQuery(this).mouseout( function() {
			if (o.autoReturn) {
				
				if (o.returnHome && $home) {
					move($home[0]);
				}
				else if (o.returnDelay) {
					if(delayTimer) clearTimeout(delayTimer);
					delayTimer = setTimeout(move,o.returnDelay + o.speed);
				}
				else {
					move();
				}
			}
		});
		

		$li.click(function(e) {
			if (o.setOnClick) {
				jQuery(ce).removeClass('selectedLava');
				jQuery(this).addClass('selectedLava');
				ce = this;
			}
			return o.click.apply(this, [e, this]);
		});

		// .backLava element border check and animation fix
		var bx=0, by=0, px=0;
		//if browser is not IE
		if (!jQuery.browser.msie) {
			bx = Math.floor(($back.outerWidth() - $back.innerWidth())/2);
			by = Math.floor(($back.outerHeight() - $back.innerHeight())/2);
		//if is IE 8
		} else if(jQuery.browser.msie==true && jQuery.browser.version=="8.0"){
			//$(".tabsList li:last").append(jQuery.browser.msie+" "+jQuery.browser.version);
			px=0;
		//for other IE versions
		} else {
			px=1;
		}
		// set the starting position for the lavalamp hover element: .back
		if (o.homeTop || o.homeLeft) 
			$back.css({ left:o.homeLeft, top:o.homeTop, width:o.homeWidth, height:o.homeHeight });
		else
			$back.css({ left: ce.offsetLeft-bx+px, top: ce.offsetTop-by, width: ce.offsetWidth, height: ce.offsetHeight });


		function move(el) {
			if (!el) el = ce;
			// .backLava element border check and animation fix
			var bx=0, by=0, px=0;
			//if browser is not IE
			if (!jQuery.browser.msie) {
				bx = Math.floor(($back.outerWidth() - $back.innerWidth())/2);
				by = Math.floor(($back.outerHeight() - $back.innerHeight())/2);
			//if is IE 8
			} else if(jQuery.browser.msie==true && jQuery.browser.version=="8.0"){
				//$(".tabsList li:last").append(jQuery.browser.msie+" "+jQuery.browser.version);
				px=0;
			//for other IE versions
			} else {
				px=1;
			}
			$back.stop()
			.animate({
				left: el.offsetLeft-bx+px,
				top: el.offsetTop-by,
				width: el.offsetWidth,
				height: el.offsetHeight
			}, o.speed, o.fx);
		};
	});
};
})(jQuery);

// /js/jquery.easing.1.3.js

/*
 * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/
 *
 * Uses the built In easIng capabilities added In jQuery 1.1
 * to offer multiple easIng options
 *
 * Copyright (c) 2007 George Smith
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

// t: current time, b: begInnIng value, c: change In value, d: duration
jQuery.easing['jswing'] = jQuery.easing['swing'];

jQuery.extend( jQuery.easing,
{
	def: 'easeOutQuad',
	swing: function (x, t, b, c, d) {
		//alert(jQuery.easing.default);
		return jQuery.easing[jQuery.easing.def](x, t, b, c, d);
	},
	easeInQuad: function (x, t, b, c, d) {
		return c*(t/=d)*t + b;
	},
	easeOutQuad: function (x, t, b, c, d) {
		return -c *(t/=d)*(t-2) + b;
	},
	easeInOutQuad: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t + b;
		return -c/2 * ((--t)*(t-2) - 1) + b;
	},
	easeInCubic: function (x, t, b, c, d) {
		return c*(t/=d)*t*t + b;
	},
	easeOutCubic: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t + 1) + b;
	},
	easeInOutCubic: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t + b;
		return c/2*((t-=2)*t*t + 2) + b;
	},
	easeInQuart: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t + b;
	},
	easeOutQuart: function (x, t, b, c, d) {
		return -c * ((t=t/d-1)*t*t*t - 1) + b;
	},
	easeInOutQuart: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
		return -c/2 * ((t-=2)*t*t*t - 2) + b;
	},
	easeInQuint: function (x, t, b, c, d) {
		return c*(t/=d)*t*t*t*t + b;
	},
	easeOutQuint: function (x, t, b, c, d) {
		return c*((t=t/d-1)*t*t*t*t + 1) + b;
	},
	easeInOutQuint: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
		return c/2*((t-=2)*t*t*t*t + 2) + b;
	},
	easeInSine: function (x, t, b, c, d) {
		return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
	},
	easeOutSine: function (x, t, b, c, d) {
		return c * Math.sin(t/d * (Math.PI/2)) + b;
	},
	easeInOutSine: function (x, t, b, c, d) {
		return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
	},
	easeInExpo: function (x, t, b, c, d) {
		return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
	},
	easeOutExpo: function (x, t, b, c, d) {
		return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
	},
	easeInOutExpo: function (x, t, b, c, d) {
		if (t==0) return b;
		if (t==d) return b+c;
		if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
		return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
	},
	easeInCirc: function (x, t, b, c, d) {
		return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
	},
	easeOutCirc: function (x, t, b, c, d) {
		return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
	},
	easeInOutCirc: function (x, t, b, c, d) {
		if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
		return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
	},
	easeInElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
	},
	easeOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b;
	},
	easeInOutElastic: function (x, t, b, c, d) {
		var s=1.70158;var p=0;var a=c;
		if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
		if (a < Math.abs(c)) { a=c; var s=p/4; }
		else var s = p/(2*Math.PI) * Math.asin (c/a);
		if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
		return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
	},
	easeInBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*(t/=d)*t*((s+1)*t - s) + b;
	},
	easeOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158;
		return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
	},
	easeInOutBack: function (x, t, b, c, d, s) {
		if (s == undefined) s = 1.70158; 
		if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
		return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
	},
	easeInBounce: function (x, t, b, c, d) {
		return c - jQuery.easing.easeOutBounce (x, d-t, 0, c, d) + b;
	},
	easeOutBounce: function (x, t, b, c, d) {
		if ((t/=d) < (1/2.75)) {
			return c*(7.5625*t*t) + b;
		} else if (t < (2/2.75)) {
			return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
		} else if (t < (2.5/2.75)) {
			return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
		} else {
			return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
		}
	},
	easeInOutBounce: function (x, t, b, c, d) {
		if (t < d/2) return jQuery.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b;
		return jQuery.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b;
	}
});
// /js/jquery.plugins.js

/* jQuery Slider */
(function($){$.fn.jCarouselLite=function(o){o=$.extend({btnPrev:null,btnNext:null,btnGo:null,mouseWheel:false,auto:null,speed:200,easing:null,vertical:false,circular:true,visible:3,start:0,scroll:1,beforeStart:null,afterEnd:null},o||{});return this.each(function(){var b=false,animCss=o.vertical?"top":"left",sizeCss=o.vertical?"height":"width";var c=$(this),ul=$("ul",c),tLi=$("li",ul),tl=tLi.size(),v=o.visible;if(o.circular){ul.prepend(tLi.slice(tl-v-1+1).clone()).append(tLi.slice(0,v).clone());o.start+=v}var f=$("li",ul),itemLength=f.size(),curr=o.start;c.css("visibility","visible");f.css({overflow:"hidden",float:o.vertical?"none":"left"});ul.css({margin:"0",padding:"0",position:"relative","list-style-type":"none","z-index":"1"});c.css({overflow:"hidden",position:"relative","z-index":"2",left:"0px"});var g=o.vertical?height(f):width(f);var h=g*itemLength;var j=g*v;f.css({width:f.width(),height:f.height()});ul.css(sizeCss,h+"px").css(animCss,-(curr*g));c.css(sizeCss,j+"px");if(o.btnPrev)$(o.btnPrev).click(function(){return go(curr-o.scroll)});if(o.btnNext)$(o.btnNext).click(function(){return go(curr+o.scroll)});if(o.btnGo)$.each(o.btnGo,function(i,a){$(a).click(function(){return go(o.circular?o.visible+i:i)})});if(o.mouseWheel&&c.mousewheel)c.mousewheel(function(e,d){return d>0?go(curr-o.scroll):go(curr+o.scroll)});if(o.auto)setInterval(function(){go(curr+o.scroll)},o.auto+o.speed);function vis(){return f.slice(curr).slice(0,v)};function go(a){if(!b){if(o.beforeStart)o.beforeStart.call(this,vis());if(o.circular){if(a<=o.start-v-1){ul.css(animCss,-((itemLength-(v*2))*g)+"px");curr=a==o.start-v-1?itemLength-(v*2)-1:itemLength-(v*2)-o.scroll}else if(a>=itemLength-v+1){ul.css(animCss,-((v)*g)+"px");curr=a==itemLength-v+1?v+1:v+o.scroll}else curr=a}else{if(a<0||a>itemLength-v)return;else curr=a}b=true;ul.animate(animCss=="left"?{left:-(curr*g)}:{top:-(curr*g)},o.speed,o.easing,function(){if(o.afterEnd)o.afterEnd.call(this,vis());b=false});if(!o.circular){$(o.btnPrev+","+o.btnNext).removeClass("disabled");$((curr-o.scroll<0&&o.btnPrev)||(curr+o.scroll>itemLength-v&&o.btnNext)||[]).addClass("disabled")}}return false}})};function css(a,b){return parseInt($.css(a[0],b))||0};function width(a){return a[0].offsetWidth+css(a,'marginLeft')+css(a,'marginRight')};function height(a){return a[0].offsetHeight+css(a,'marginTop')+css(a,'marginBottom')}})(jQuery);

/* jQuery Easing */
//commented out because easing plugin is in default globals.inc, and was causing conflict with such in other widgets
/*jQuery.easing = {
	easein: function(x, t, b, c, d) {
		return c*(t/=d)*t + b; // in
	},
	easeinout: function(x, t, b, c, d) {
		if (t < d/2) return 2*c*t*t/(d*d) + b;
		var ts = t - d/2;
		return -2*c*ts*ts/(d*d) + 2*c*ts/d + c/2 + b;		
	},
	easeout: function(x, t, b, c, d) {
		return -c*t*t/(d*d) + 2*c*t/d + b;
	},
	linear: function(x, t, b, c, d) {
		return c*t/d + b; //linear
	}
};*/

/* Accordion */
$(document).ready(function(){
    $('.accordion .children').hide();
    $('.accordion .head').click(function() {
        var idParent = '#' + $(this).parent().parent().parent().attr('id');
        $(idParent + ' .children').slideUp('slow');
        if (!$(this).hasClass('on')) {
            $(idParent + ' .head').removeClass('on');
            $(this).addClass('on');
            $(idParent + ' .' + $(this).attr('title')).slideDown('slow');
       }else{
            $(idParent + ' .head').removeClass('on');
        }
    });
});

/* Tabs */
$(document).ready(function(){
    $('.tabbox .tabcontent').hide();
    $('.tabbox .tabcontent-01').show();
    $('.tabbox .tab-01').addClass('on');
    $('.tab a').click(function() {
        var idParent = '#' + $(this).parent().parent().parent().attr('id');
        $(idParent + ' .tab').removeClass('on');
        $(this).parent().addClass('on');
        $(idParent + ' .tabcontent').hide();
        $(idParent + ' ' + $(this).attr('title')).show();
    });
});

var isMenuAnimating = false;
/* Shows Drop Down */
$(document).ready(function(){
    var pxHeight = $('#GlobalShowsNav').height();
    function showNav() {
        $('#playerFrame').css('visibility','hidden');
        $('#GlobalHeaderNav_Shows a').addClass('on');
        $('#GlobalShowsNav').show();
		$('select#lstRegion').hide();
    }
    function hideNav() {
        $('#GlobalHeaderNav_Shows a').removeClass('on');
        $('#GlobalShowsNav').stop().hide();
        $('#playerFrame').css('visibility','visible');
		$('select#lstRegion').show();
    }
    $('#GlobalShowsNav .tab a').click(function() {
        pxHeight = $('#GlobalShowsNav ' + $(this).attr('title')).height()+125;
        $('#GlobalShowsNav').stop().height(pxHeight);
    });
    $('#GlobalHeaderNav_Shows a').click(function() {
			if (!isMenuAnimating){
				isMenuAnimating = true;
				setTimeout("isMenuAnimating=false",1000); // prevents double-clicking
				if ($('#GlobalShowsNav').css('display') == 'none') {
					$('#GlobalShowsNav').css('left', (($(window).width() - 959) / 2) + 'px');
					showNav();
				}else{
					hideNav();
				}
			}
    });
    $('#GlobalShowsNavClose a').click(hideNav);
});

/* Search Boxes */
$(document).ready(function(){
    var stbInstructions = new Array;
    $('input.SearchTextBox').each(function() {
        stbInstructions[$(this).attr('id')] = $(this).val();
    });
    $('input.SearchTextBox').focus(function() {
        if ($(this).val() == stbInstructions[$(this).attr('id')]) {
            $(this).val('');
        }
    });
    $('input.SearchTextBox').blur(function() {
        if (!$(this).val()) {
            $(this).val(stbInstructions[$(this).attr('id')]);
        }
    });
});

/* Footer Slider */
$(document).ready(function(){
    $("#GFooterSliderWrapper #GFooterSliderWindow").jCarouselLite({
        btnNext: "#GFooterSliderWrapper .ScrollBlogNext",
        btnPrev: "#GFooterSliderWrapper .ScrollBlogPrevious",
        speed: 1500,
        easing: "easeInOutQuad",
        visible: 4,
        scroll: 4
    });
});

/* Canada Network Redirect */
$(document).ready(function(){
    $('#CanadaNetworkContainer select').change(function() {
        document.location = $(this).val();
    });
});

/* IE7 Bug Fix (margin bottom issue when float left) */
var detectAgent = navigator.userAgent.toLowerCase();
if (detectAgent.indexOf('msie') > -1) {
    var arVersion = navigator.appVersion.split("MSIE");
    var version = parseFloat(arVersion[1]);
    if (version == 7) {
        $(document).ready(function(){
            $('div').each(function() {
                if ($(this).css('float') == 'left' && $(this).css('margin-bottom') != '0px') {
                    $(this).css('padding-bottom',$(this).css('margin-bottom'));
                }
            });
        });
    }
}

/* jQuery.scrollTo */
;(function( $ ){
	
	var $scrollTo = $.scrollTo = function( target, duration, settings ){
		$(window).scrollTo( target, duration, settings );
	};

	$scrollTo.defaults = {
		axis:'xy',
		duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
	};

	// Returns the element that needs to be animated to scroll the window.
	// Kept for backwards compatibility (specially for localScroll & serialScroll)
	$scrollTo.window = function( scope ){
		return $(window).scrollable();
	};

	// Hack, hack, hack... stay away!
	// Returns the real elements to scroll (supports window/iframes, documents and regular nodes)
	$.fn.scrollable = function(){
		return this.map(function(){
			var elem = this,
				isWin = !elem.nodeName || $.inArray( elem.nodeName.toLowerCase(), ['iframe','#document','html','body'] ) != -1;

				if( !isWin )
					return elem;

			var doc = (elem.contentWindow || elem).document || elem.ownerDocument || elem;
			
			return $.browser.safari || doc.compatMode == 'BackCompat' ?
				doc.body : 
				doc.documentElement;
		});
	};

	$.fn.scrollTo = function( target, duration, settings ){
		if( typeof duration == 'object' ){
			settings = duration;
			duration = 0;
		}
		if( typeof settings == 'function' )
			settings = { onAfter:settings };
			
		if( target == 'max' )
			target = 9e9;
			
		settings = $.extend( {}, $scrollTo.defaults, settings );
		// Speed is still recognized for backwards compatibility
		duration = duration || settings.speed || settings.duration;
		// Make sure the settings are given right
		settings.queue = settings.queue && settings.axis.length > 1;
		
		if( settings.queue )
			// Let's keep the overall duration
			duration /= 2;
		settings.offset = both( settings.offset );
		settings.over = both( settings.over );

		return this.scrollable().each(function(){
			var elem = this,
				$elem = $(elem),
				targ = target, toff, attr = {},
				win = $elem.is('html,body');

			switch( typeof targ ){
				// A number will pass the regex
				case 'number':
				case 'string':
					if( /^([+-]=)?\d+(\.\d+)?(px)?$/.test(targ) ){
						targ = both( targ );
						// We are done
						break;
					}
					// Relative selector, no break!
					targ = $(targ,this);
				case 'object':
					// DOMElement / jQuery
					if( targ.is || targ.style )
						// Get the real position of the target 
						toff = (targ = $(targ)).offset();
			}
			$.each( settings.axis.split(''), function( i, axis ){
				var Pos	= axis == 'x' ? 'Left' : 'Top',
					pos = Pos.toLowerCase(),
					key = 'scroll' + Pos,
					old = elem[key],
					Dim = axis == 'x' ? 'Width' : 'Height';

				if( toff ){// jQuery / DOMElement
					attr[key] = toff[pos] + ( win ? 0 : old - $elem.offset()[pos] );

					// If it's a dom element, reduce the margin
					if( settings.margin ){
						attr[key] -= parseInt(targ.css('margin'+Pos)) || 0;
						attr[key] -= parseInt(targ.css('border'+Pos+'Width')) || 0;
					}
					
					attr[key] += settings.offset[pos] || 0;
					
					if( settings.over[pos] )
						// Scroll to a fraction of its width/height
						attr[key] += targ[Dim.toLowerCase()]() * settings.over[pos];
				}else
					attr[key] = targ[pos];

				// Number or 'number'
				if( /^\d+$/.test(attr[key]) )
					// Check the limits
					attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max(Dim) );

				// Queueing axes
				if( !i && settings.queue ){
					// Don't waste time animating, if there's no need.
					if( old != attr[key] )
						// Intermediate animation
						animate( settings.onAfterFirst );
					// Don't animate this axis again in the next iteration.
					delete attr[key];
				}
			});

			animate( settings.onAfter );			

			function animate( callback ){
				$elem.animate( attr, duration, settings.easing, callback && function(){
					callback.call(this, target, settings);
				});
			};

			// Max scrolling position, works on quirks mode
			// It only fails (not too badly) on IE, quirks mode.
			function max( Dim ){
				var scroll = 'scroll'+Dim;
				
				if( !win )
					return elem[scroll];
				
				var size = 'client' + Dim,
					html = elem.ownerDocument.documentElement,
					body = elem.ownerDocument.body;

				return Math.max( html[scroll], body[scroll] ) 
					 - Math.min( html[size]  , body[size]   );
					
			};

		}).end();
	};

	function both( val ){
		return typeof val == 'object' ? val : { top:val, left:val };
	};

})( jQuery );
/* Check links against redirect xml */
function removeLinks(target) {
	$.ajax({
		type: "GET",
		url: "/_data/Shows.xml",
		dataType: "xml",
		success: function(data){
			var validShows = new Array();
			$(data).find("id").each(function(){
				validShows.push($(this).text())
			});
			$(target).each(function(){
				var showValid = false;
				var text = $(this).text();
				var redirObj = breakupRedirect($(this).attr('href'));
				var show = redirObj.show;
				for(i=0;i<validShows.length;i++){
					if(show.toLowerCase() == validShows[i].toLowerCase()){
						showValid = true;
					}
				}
				if(!showValid){
					$(this).parent().text(text).addClass("linkRemoved");
					$(this).remove();
				} 
			});
			doSpecialCases(target);
		}
	});
}
function doSpecialCases(target) {
	var returnMe = true;
	var callSign = readCookie("CallSign");
	$.ajax({
		type: "GET",
		url: "/_data/SpecialCases.xml",
		dataType: "xml",
		success: function(data){
			var specialCases = new Array();
			$(data).find("id").each(function(){
				specialCases.push($(this).text())
				//alert($(this).text());
			});
			$(target).each(function(){
				var redirObj = breakupRedirect($(this).attr('href'));
				for(i=0;i<specialCases.length;i++){
					if(redirObj.show.toLowerCase() == specialCases[i].toLowerCase()){
					//alert(specialCases[i]);
					$(this).attr("href", redirObj.loc + "?" + redirObj.root + "/" + redirObj.show + callSign + "/" + redirObj.type);
					}
				}
			});
			
		},
		error: function(data){
			returnMe = false;
		}
	});
	return returnMe;
}
function breakupRedirect(url){
	// http://www.globaltv.com/scripts/redirect.aspx?shows/90210/url - Example URL
	// loc?root/show/type - Example Sections
	// loc?params - Example Sections
	var loc = url.split("?")[0];
	var params = url.split("?")[1];
	var root = params.split("/")[0];
	var show = params.split("/")[1];
	var type = params.split("/")[2];
	var returnMe = new Object();
	returnMe.url = url;
	returnMe.loc = loc;
	returnMe.params = params;
	returnMe.root = root;
	returnMe.show = show;
	returnMe.type = type;
	return returnMe;
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

// /js/datetime.js
/*
 * Date Format 1.2.2
 * (c) 2007-2008 Steven Levithan <stevenlevithan.com>
 * MIT license
 * Includes enhancements by Scott Trenda <scott.trenda.net> and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 *
 * http://blog.stevenlevithan.com/archives/date-time-format
 */
var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && (typeof date == "string" || date instanceof String) && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date();
		if (isNaN(date)) throw new SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

Date.prototype.firstDayInMonth = function() {
	return new Date(this.setDate(1));
};

Date.prototype.lastDayInMonth = function() {
	var next_month = new Date(this.setMonth(this.getMonth+1));
	next_month = new Date(next_month.setDate(1));
	return next_month;
};

Date.prototype.setFullDate = function(year, month, day, hour, minute, second) {
	var date = new Date(year, month, day);
	date = new Date(date.setHours(hour));
	date = new Date(date.setMinutes(minute));
	date = new Date(date.setSeconds(second));
	
	return date;
}
// /js/misc.js
// SEARCH ----------------------------------------------------------------
//var currentSearchTextBox = 1;



// /js/trafficWebcam.js
// JavaScript Document
function flink (whereto) {
	var webcamWindow=window.open(whereto,'trafficWebcamFrame','resizable=no,width=430,height=430');
	webcamWindow.focus();
	if(webcamWindow.closed){
		alert("Please Disable any popup blockers you may have installed in order to view this content.");
		return false;
	} else {
		return webcamWindow;
	}
}
// /js/StationSchedule.js

/**********************************************************************************
* Author : Jeremy Foster
* Contains objects to control the Station Schedule and Calendar objects
*
*
***********************************************************************************/
/*********************************************
* Object used to display the full schedule
**********************************************/
var default_SlideCount = 6;


var GlobalStationScheduleControl = function (scheduleWindowDiv, scheduleDiv, startColumn, columnWidth, slideCount, slideDelay, columns) {
	var ScheduleWindowDiv; // Div that holds the sliding Div
	var ScheduleDiv; // Sliding Div that contains the schedule events
	var StartColumn; // 38 = 7:00PM
	var ColumnWidth; // 120 default
	var SlideCount = default_SlideCount; // 6 default
	var SlideDelay; // 750 default
	var Timer;
	var PixelForgiveness;
	var Columns; // 48 for a 24 hours

	this.init(scheduleWindowDiv, scheduleDiv, startColumn, columnWidth, slideCount, slideDelay, columns);

	return true;
}

// Initialize object
GlobalStationScheduleControl.prototype.init = function(scheduleWindowDiv, scheduleDiv, startColumn, columnWidth, slideCount, slideDelay, columns) {
	if(!startColumn)startColumn=0;
	if(!columnWidth)columnWidth=120;
	if(!slideCount)slideCount=default_SlideCount;
	if(!slideDelay)slideDelay=750;
	if(!columns)columns=48;
	this.ScheduleWindowDiv = jQuery("#" + scheduleWindowDiv);
	this.ScheduleDiv = jQuery("#" + scheduleDiv);
	this.StartColumn = startColumn;
	this.ColumnWidth = columnWidth;
	this.SlideCount = slideCount;
	this.SlideDelay = slideDelay;
	this.PixelForgiveness = 6;
	this.Columns = columns;

	// Slide the schedule over to the start column.
	this.ScheduleDiv.css({position:'relative'}).animate({left:"-=" + (columnWidth * startColumn) + "px"}, 0);
	// Display the SlideRight button in the top right column
	this.checkOverflow();
}

GlobalStationScheduleControl.prototype.slideLeft = function() {
	if (this.StartColumn > 0)
	{
		window.clearTimeout(this.Timer);
		this.clearOverflow();
		var slide = default_SlideCount; //this.SlideCount;
		if (this.StartColumn - 6 < 0) slide = default_SlideCount;
		this.ScheduleDiv.css({position:'relative'}).animate({left:"+=" + this.ColumnWidth * slide + "px"}, this.SlideDelay);
		jQuery("#ScheduleSlideRight" + (this.StartColumn + 6)).find(".STBRight").hide();
		this.StartColumn -= slide;
		window.setTimeout("CDMGlobalStationScheduleControl.checkOverflow()", this.SlideDelay + 15);
		styleLinks();
	}
}

GlobalStationScheduleControl.prototype.slideRight = function() {
	if (this.StartColumn < this.Columns - 7)
	{
		window.clearTimeout(this.Timer);
		this.clearOverflow();
		var slide = default_SlideCount; //this.SlideCount;
		
		if (this.StartColumn + 6 >= this.Columns - this.SlideCount) slide = default_SlideCount;
		this.ScheduleDiv.css({position:'relative'}).animate({left:"-=" + this.ColumnWidth * slide + "px"}, this.SlideDelay);
		jQuery("#ScheduleSlideRight" + (this.StartColumn + 6)).find(".STBRight").hide();
		this.StartColumn += slide;
		window.setTimeout("CDMGlobalStationScheduleControl.checkOverflow()", this.SlideDelay + 15);
		styleLinks();
	}
}

GlobalStationScheduleControl.prototype.showRightButton = function(startColumn) {
	jQuery("#ScheduleSlideRight" + (startColumn)).find(".STBRight").show();
}

GlobalStationScheduleControl.prototype.checkOverflow = function() {
	this.showRightButton(this.StartColumn + 6);
	var window_left = this.ScheduleWindowDiv.position().left; // Schedule window left
	var window_right = this.ScheduleWindowDiv.position().left + this.ScheduleWindowDiv.outerWidth(); // Schedule window right
	var pixel_forgive = this.PixelForgiveness;
	// Loop through and add overlap
	this.ScheduleWindowDiv.find(".ScheduleEvent").each(function() {
		var event = jQuery(this);
		if((event.offset().left < window_left - pixel_forgive
			&& event.offset().left + event.outerWidth() > window_left + pixel_forgive)
			|| (event.offset().left + event.outerWidth() > window_right
			&& event.offset().left < window_right))
		{
			event.toggleClass("ScheduleEventOverlap");

			event.find(".ScheduleColumnContent").each(function() {
				var content = jQuery(this);
				if (event.offset().left < window_left)
				{
					var new_left = window_left - event.offset().left;
					var new_width = content.outerWidth() - new_left;
					content.css({position:"relative",left:(new_left+"px"),width:(new_width+"px")});
				}
				else if ((event.offset().left + pixel_forgive) < window_right && (event.offset().left + event.outerWidth() + pixel_forgive) > window_right)
				{
					var new_width = content.outerWidth() - (content.offset().left + content.outerWidth() - window_right + pixel_forgive);
					content.css({position:"relative",width:(new_width+"px")});
				}
			});
		}
	});
}

GlobalStationScheduleControl.prototype.clearOverflow = function() {
	// Loop through and remove overlap
	this.ScheduleWindowDiv.find(".ScheduleEventOverlap").each(function() {
		var event = jQuery(this);
		var left = event.offset().left;
		event.toggleClass("ScheduleEventOverlap");
		event.unbind();
		event.find(".ScheduleColumnContent").each(function() {
				var content = jQuery(this);
				var width_mod = content.offset().left - left;
				var new_width = content.outerWidth() + width_mod;
				content.css({position:"relative",left:"0px",width:""});
			});
	});
}

/*********************************************
* Object used to control the StationCalendar
**********************************************/
var GlobalCalendar = function(selectedDate, firstDayAvailable, lastDayAvailable, uniqueId, objectName) {
	var Selected;
	var Month;
	var FirstDayAvailable;
	var LastDayAvailable;
	var UniqueId; // A uniqueId that is a part of the id's within the calendar control
	var Increment;
	var ObjectName; // The name of the variable for this GlobalCalendar (i.e. var CMDGlobalCalendar = new GlobalCalendar)

	// Text objects
	var SelectedDayTitle;
	var SelectedMonthTitle;
	var SelectedCalendarTitle;

	this.init(selectedDate, firstDayAvailable, lastDayAvailable, uniqueId, objectName);

	return true;
}

// Initialize object
GlobalCalendar.prototype.init = function(selectedDate, firstDayAvailable, lastDayAvailable, uniqueId, objectName) {
	this.Selected = new Date(selectedDate);
	this.Month = selectedDate.firstDayInMonth();
	this.FirstDayAvailable = firstDayAvailable;
	this.LastDayAvailable = lastDayAvailable;
	this.UniqueId = uniqueId;
	if (!uniqueId) this.UniqueId = "Calendar";
	this.ObjectName = objectName;
	this.Name = objectName;
	this.Increment = 1;
	this.AJAXReplacements; // DivId or Array of DivId's to be replaced by the AJAX call

	// Initialize Text objects
	this.SelectedDayTitle = jQuery("#" + this.UniqueId + "Day");
	this.SelectedMonthTitle = jQuery("#" + this.UniqueId + "Date");
	this.SelectedCalendarTitle = jQuery("#" + this.UniqueId + "Top");

	this.display();
}

// Display the month
GlobalCalendar.prototype.display = function(calendarMonth) {
	if (calendarMonth) this.Month = new Date(calendarMonth);

	var dt = this.startDate();
	var enddate = new Date(new Date(dt).setDate(dt.getDate() + 42)); // There are 42 calendar cells
	var cell = 0;

	this.SelectedDayTitle.html(this.Selected.format("dddd"));
	this.SelectedMonthTitle.html(this.Selected.format("mmmm d, yyyy"));
	this.SelectedCalendarTitle.html("<strong>" + this.Month.format("mmmm") + "</strong>, " + this.Month.format("yyyy"));

	// Loop through calendar cells
	while (dt <= enddate)
	{
		// Change the cell contents
		if (dt.getFullYear() == this.Selected.getFullYear() && dt.getMonth() == this.Selected.getMonth() && dt.getDate() == this.Selected.getDate())
			jQuery("#" + this.UniqueId + "Cell" + cell).html("<a class=\"Live\" href=\"javascript:void(0);\" onclick=\"" + this.Name + ".display();\">" + dt.getDate() + "</a>");
		else if (dt >= this.FirstDayAvailable && dt <= this.LastDayAvailable)
			jQuery("#" + this.UniqueId + "Cell" + cell).html("<a href=\"javascript:" + this.Name + ".selectDate(new Date(" + dt.getFullYear() + "," + dt.getMonth() + "," + dt.getDate() + ")); " + this.Name + ".display();\">" + dt.getDate() + "</a>");
		else
			jQuery("#" + this.UniqueId + "Cell" + cell).html(dt.getDate());

		cell++;
		dt = new Date(dt.getFullYear(), dt.getMonth(), dt.getDate()+1);
	}
}

// Display the next month
GlobalCalendar.prototype.next = function(months) {
	if (!months) months=this.Increment;

	this.display(new Date(this.Month.setMonth(this.Month.getMonth() + months)));
}

// Display the prior month
GlobalCalendar.prototype.previous = function(months) {
	if (!months) months=this.Increment;

	this.display(new Date(this.Month.setMonth(this.Month.getMonth() - months)));
}

// Calculates the 1st day to display on the calendar
GlobalCalendar.prototype.startDate = function(calendarMonth) {
	if (calendarMonth) this.Month = new Date(calendarMonth);

	var start = new Date(this.Month.firstDayInMonth());
	var sub = -1 * start.getDay();
	if (sub!=0) start = new Date(start.setDate(start.getDate() + sub));
	return start;
}

// Changed the selected date
GlobalCalendar.prototype.selectDate = function(selectedDate) {
	this.Selected = selectedDate;
	this.update(CDMGlobal.SelectedRegion.CallSign);
}

// Updates the schedule after making an AJAX call
GlobalCalendar.prototype.update = function(callSign, replaceDivId)
{
	var href = window.location.pathname + "?callsign=" + callSign + "&date=" + this.Selected.format("yyyy") + "/" + this.Selected.format("mm") + "/" + this.Selected.format("dd");
	if (!replaceDivId && this.AJAXReplacements) replaceDivId = this.AJAXReplacements; // Default replaceDivId's
	CDMGlobal.selectRegion(callSign); // Save the selected value
	CDMGlobal.fetchSchedule(href, replaceDivId);
}

/*********************************************
* Object to maintain region information for the page
**********************************************/
var GlobalStation = function(callSign) {
	var SelectedRegion;
	var Regions; // Array of GlobalStationRegion
	var UniqueId; // The unique Id used in various components on the page.
	var LoadingGif; // The image that will display when an AJAX call is made

	this.init(callSign);

	return true;
}

// Initialize object
GlobalStation.prototype.init = function(callSign) {
	this.Regions = [
		new GlobalStationRegion("CIHF", "Atlantic-Maritimes"), 
		new GlobalStationRegion("CHAN", "British Columbia"), 
		new GlobalStationRegion("CICT", "Calgary"),
		new GlobalStationRegion("CITV", "Edmonton"),
		new GlobalStationRegion("CISA", "Lethbridge"),
		new GlobalStationRegion("CKND", "Manitoba"),
		new GlobalStationRegion("CIII", "Ontario"),
		new GlobalStationRegion("CKMI", "Quebec"),
		new GlobalStationRegion("CFRE", "Regina"),
		new GlobalStationRegion("CFSK", "Saskatoon")];

	if (!callSign) this.selectRegion("CIII"); // Default to Ontario
	else this.selectRegion(callSign);
}

// Add a GlobalStationRegion to the array
GlobalStation.prototype.addRegion = function(callSign, name) {
	var region = new GlobalStationRegion(callSign, name);
	this.Regions.push(region);
	return region;
}

// Find the region through the callsign
GlobalStation.prototype.selectRegion = function(callSign, replaceDivId, href) {
	for(i=0; i<this.Regions.length; i++)
	{
		if (this.Regions[i].CallSign == callSign)
		{
			if (this.SelectedRegion && callSign != this.SelectedRegion.CallSign)
			{
				this.SelectedRegion = this.Regions[i];
				this.fetchSchedule(href, replaceDivId);
			}
			else this.SelectedRegion = this.Regions[i]
			return this.Regions[i];
		}
	}
	return false;
}

// Makes AJAX call to fetch data
GlobalStation.prototype.fetchSchedule = function(href, replaceDivId) {
	if (replaceDivId)
	{
		if (!href)
		{
			var date = queryString("date");
			if (date && date.length > 0) date = "&date=" + date;
			
			href = removeParamterFromURL (window.location, "callsign|date");
			if (href.toString().indexOf("?") <0)
			    href += "?";
			else 
			    href += "&";
			href += "callsign=" + this.SelectedRegion.CallSign + date;
			//href = window.location.pathname + "?callsign=" + this.SelectedRegion.CallSign + date;
			
			//added by Omer, on the search page, changing region removes the q parameter.. we should add it back
            
		}
		window.location = href;
		// For some reason IE6/7 and others can't handle jQuery(data) evaluating HTML...
		//jQuery.get(href,  function(data){CDMGlobal.update(data, replaceDivId);}, "html");
		if (this.LoadingGif) this.LoadingGif.show();
	}
}

// Initializes the dropdown list for the regions
GlobalStation.prototype.setupDropdown = function(dropdown, replaceDivId, loadingGifId) {
	if (loadingGifId) this.LoadingGif = jQuery("#" + loadingGifId);
	if (!dropdown.options) dropdown = jQuery("#" + dropdown);
	if (dropdown)
	{
		for(i=0; i<this.Regions.length; i++)
		{
			var new_option = document.createElement('option');
			new_option.value = this.Regions[i].CallSign;
			new_option.innerHTML = this.Regions[i].Name;
			
			if (this.SelectedRegion.CallSign == this.Regions[i].CallSign) // Default callsign is provided, select it from the dropdown
			{
				this.SelectedRegion = new GlobalStationRegion(this.Regions[i].CallSign, this.Regions[i].Name);
				new_option.selected = true;
			}
			dropdown.append(new_option);
		}
		return true;
	}
	return false;
}

// Update the page with the new calendar data.
GlobalStation.prototype.update = function(data, replaceDivId) {
	if (replaceDivId)
	{
		if (typeOf(replaceDivId) == "array")
		{
			// Loop through divs to be replaced with the returned data.
			for(i=0; i<replaceDivId.length; i++)
			{
				if (!replaceDivId[i]) break; // Issue occurs when the place this code originated is replaced by the AJAX call
				var section = jQuery("#" + replaceDivId[i]);
				if (!section.html()) break;

				var new_section = jQuery(data).find("#" + replaceDivId[i]);
				section.html(new_section.html());
			}
		}
		else
		{
			var s = jQuery(data).find("#" + replaceDivId);
			jQuery("#" + replaceDivId).html(s.html());
		}
		// This is required for the tab style to work correctly.
		// If someone can come up with a shorter way to do this it would be better.
		eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('m $j=1o.21();(5($){$.20.1O=5(o){o=$.23({I:F,M:F,18:F,1T:P,1t:F,16:2e,17:F,N:P,Q:1x,J:3,S:0,n:1,1b:F,1p:F},o||{});l 6.15(5(){m b=P,R=o.N?"1C":"C",1i=o.N?"p":"K";m c=$(6),q=$("q",c),11=$("1N",q),1P=11.1M(),v=o.J;9(o.Q){q.2c(11.10(1P-v-1+1).1Q()).26(11.10(0,v).1Q());o.S+=v}m f=$("1N",q),u=f.1M(),k=o.S;c.8("1h","J");f.8({1K:"1k",1E:o.N?"1d":"C"});q.8({1u:"0",1Y:"0",1L:"1R","27-28-29":"1d","z-1U":"1"});c.8({1K:"1k",1L:"1R","z-1U":"2",C:"1c"});m g=o.N?p(f):K(f);m h=g*u;m j=g*v;f.8({K:f.K(),p:f.p()});q.8(1i,h+"L").8(R,-(k*g));c.8(1i,j+"L");9(o.I)$(o.I).B(5(){l E(k-o.n)});9(o.M)$(o.M).B(5(){l E(k+o.n)});9(o.18)$.15(o.18,5(i,a){$(a).B(5(){l E(o.Q?o.J+i:i)})});9(o.1T&&c.1V)c.1V(5(e,d){l d>0?E(k-o.n):E(k+o.n)});9(o.1t)2b(5(){E(k+o.n)},o.1t+o.16);5 1s(){l f.10(k).10(0,v)};5 E(a){9(!b){9(o.1b)o.1b.1y(6,1s());9(o.Q){9(a<=o.S-v-1){q.8(R,-((u-(v*2))*g)+"L");k=a==o.S-v-1?u-(v*2)-1:u-(v*2)-o.n}T 9(a>=u-v+1){q.8(R,-((v)*g)+"L");k=a==u-v+1?v+1:v+o.n}T k=a}T{9(a<0||a>u-v)l;T k=a}b=1x;q.1w(R=="C"?{C:-(k*g)}:{1C:-(k*g)},o.16,o.17,5(){9(o.1p)o.1p.1y(6,1s());b=P});9(!o.Q){$(o.I+","+o.M).U("1B");$((k-o.n<0&&o.I)||(k+o.n>u-v&&o.M)||[]).O("1B")}}l P}})};5 8(a,b){l 25($.8(a[0],b))||0};5 K(a){l a[0].24+8(a,\'1Z\')+8(a,\'2a\')};5 p(a){l a[0].2L+8(a,\'2N\')+8(a,\'2H\')}})(1o);1o.17={2I:5(x,t,b,c,d){l c*(t/=d)*t+b},1S:5(x,t,b,c,d){9(t<d/2)l 2*c*t*t/(d*d)+b;m Z=t-d/2;l-2*c*Z*Z/(d*d)+2*c*Z/d+c/2+b},1J:5(x,t,b,c,d){l-c*t*t/(d*d)+2*c*t/d+b},2F:5(x,t,b,c,d){l c*t/d+b}};$j(y).D(5(){$j(\'.1D .1G\').Y();$j(\'.1D .1g\').B(5(){m w=\'#\'+$j(6).G().G().G().A(\'V\');$j(w+\' .1G\').2D(\'1F\');9(!$j(6).2J(\'s\')){$j(w+\' .1g\').U(\'s\');$j(6).O(\'s\');$j(w+\' .\'+$j(6).A(\'19\')).2K(\'1F\')}T{$j(w+\' .1g\').U(\'s\')}})});$j(y).D(5(){$j(\'.1f .1e\').Y();$j(\'.1f .1e-1H\').1m();$j(\'.1f .12-1H\').O(\'s\');$j(\'.12 a\').B(5(){m w=\'#\'+$j(6).G().G().G().A(\'V\');$j(w+\' .12\').U(\'s\');$j(6).G().O(\'s\');$j(w+\' .1e\').Y();$j(w+\' \'+$j(6).A(\'19\')).1m()})});$j(y).D(5(){m 13=$j(\'#r\').p();5 1j(14){14=14||2m;$j(\'#1I\').8(\'1h\',\'1k\');$j(\'#X a\').O(\'s\');$j(\'#r\').1m().1w({p:13+\'L\'},14,\'1J\')}5 1r(){$j(\'#X a\').U(\'s\');$j(\'#r\').1W().Y();$j(\'#1I\').8(\'1h\',\'J\')}$j(\'#r .12 a\').B(5(){13=$j(\'#r \'+$j(6).A(\'19\')).p()+2l;$j(\'#r\').1W().p(13)});$j(\'#X a\').B(5(){9($j(\'#r\').8(\'2h\')==\'1d\'){$j(\'#r\').8(\'C\',(($j(2i).K()-2q)/2)+\'L\').p(\'1c\');1j(2r)}});$j(\'#X a\').2y(1r);$j(\'#r\').2A(1j,1r)});$j(y).D(5(){m W=2x 2w;$j(\'1q.1l\').15(5(){W[$j(6).A(\'V\')]=$j(6).H()});$j(\'1q.1l\').2s(5(){9($j(6).H()==W[$j(6).A(\'V\')]){$j(6).H(\'\')}});$j(\'1q.1l\').2t(5(){9(!$j(6).H()){$j(6).H(W[$j(6).A(\'V\')])}})});$j(y).D(5(){$j("#1n #2v").1O({M:"#1n .2G",I:"#1n .2u",16:2z,17:"1S",J:4,n:4})});$j(y).D(5(){$j(\'#2j 2g\').2k(5(){y.2p=$j(6).H()})});m 1X=1v.2o.2C();9(1X.2n(\'2B\')>-1){m 1A=1v.2M.2f("2E");m 1z=22(1A[1]);9(1z==7){$j(y).D(5(){$j(\'2d\').15(5(){9($j(6).8(\'1E\')==\'C\'&&$j(6).8(\'1u-1a\')!=\'1c\'){$j(6).8(\'1Y-1a\',$j(6).8(\'1u-1a\'))}})})}}',62,174,'|||||function|this||css|if|||||||||||curr|return|var|scroll||height|ul|GlobalShowsNav|on||itemLength||idParent||document||attr|click|left|ready|go|null|parent|val|btnPrev|visible|width|px|btnNext|vertical|addClass|false|circular|animCss|start|else|removeClass|id|stbInstructions|GlobalHeaderNav_Shows|hide|ts|slice|tLi|tab|pxHeight|lenAnimation|each|speed|easing|btnGo|title|bottom|beforeStart|0px|none|tabcontent|tabbox|head|visibility|sizeCss|showNav|hidden|SearchTextBox|show|GFooterSliderWrapper|jQuery|afterEnd|input|hideNav|vis|auto|margin|navigator|animate|true|call|version|arVersion|disabled|top|accordion|float|slow|children|01|playerFrame|easeout|overflow|position|size|li|jCarouselLite|tl|clone|relative|easeinout|mouseWheel|index|mousewheel|stop|detectAgent|padding|marginLeft|fn|noConflict|parseFloat|extend|offsetWidth|parseInt|append|list|style|type|marginRight|setInterval|prepend|div|200|split|select|display|window|CanadaNetworkContainer|change|125|250|indexOf|userAgent|location|959|500|focus|blur|ScrollBlogPrevious|GFooterSliderWindow|Array|new|mouseleave|1500|hover|msie|toLowerCase|slideUp|MSIE|linear|ScrollBlogNext|marginBottom|easein|hasClass|slideDown|offsetHeight|appVersion|marginTop'.split('|'),0,{}));
	}
	if (this.LoadingGif) this.LoadingGif.hide();
}

/*********************************************
* Object contains station region information
**********************************************/
var GlobalStationRegion = function(callSign, name) {
	var CallSign;
	var Name;

	this.init(callSign, name);

	return true;
}

// Initialize object
GlobalStationRegion.prototype.init = function(callSign, name) {
	this.CallSign = callSign;
	this.Name = name;
}

/*********************************************
* Handy methods
**********************************************/
// Returns a query string parameter value
function queryString( name ){  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  var regexS = "[\\?&]"+name+"=([^&#]*)";  var regex = new RegExp( regexS );  var results = regex.exec( window.location.href );  if( results == null )    return "";  else    return results[1];}

// Better way to determine the typeof a variable
function typeOf(value) {    var s = typeof value;    if (s === 'object') {        if (value) {            if (value instanceof Array) {                s = 'array';            }        } else {            s = 'null';        }    }    return s;}

// Removes show links that we don't have information for
function styleLinks(){
	var primetimeStart = 38; //column 38
	if(CDMGlobalStationScheduleControl){
		var timeNow = CDMGlobalStationScheduleControl.StartColumn;
	} else if(queryString("StartHour")){
		var timeNow = queryString("StartHour")*2;//2 cols per hour
	} else {
		timeNow = 38;
	}
	//alert(timeNow);
	if(timeNow >= primetimeStart){
		jQuery("#CalendarPrimeTime").addClass("currentTime");
		jQuery("#CalendarDayTime").removeClass("currentTime");
	} else {
		jQuery("#CalendarPrimeTime").removeClass("currentTime");
		jQuery("#CalendarDayTime").addClass("currentTime");
	}
}
function addTodayLink(){
	var today = new Date();
	var todayLinkHref = "javascript:CDMCalenderGlobalCalendar.selectDate(new Date("
	+ today.getFullYear() + "," 
	+ today.getMonth() + "," 
	+ today.getDate() + ")); CDMCalenderGlobalCalendar.display();";
	jQuery('<a href="' + todayLinkHref + '">Today</a>').appendTo("#CalenderBottom");
}
/*********************************************
* Initialize Stuff
**********************************************/
var CDMGlobal = new GlobalStation();


// /js/cdmscriptmanager-1.0.js
/*************************************************************************
 CDM Script Manager 1.0
 Canwest Digital Media
 February 18, 2009
 
 DESCRIPTION:
	The script manager keeps track of previously loaded scripts and won't 
	re-load the same script name twice (unless specified).

 USAGE:
	Place this script (CDM Script Manager) within the HEAD tags of the
	master page, before any Java Script includes.
		<script type="text/javascript" src="/js/CDMScriptManager-1.0.js?v=22551"></script>

	Replace existing Java Script includes:
		<script type="text/javascript" src="/js/myscript-1.02.js?v=22551"></script>
	with the following:
		<script type="text/javascript">CDMScriptManager.load('/js/myscript-1.02.js');</script>

 FUNCTIONS:
	CDMScriptManager.load('[scriptPath]','[continueLoadOnConflict]');
		scriptPath - Path for script to load
		continueLoadOnConflict - [true|false] Force load script if it has 
								 already been loaded (Default = false)
	
	CDMScriptManager.getLoadedScripts();
		Returns an array of objects containing the info for scripts loaded

	CDMScriptManager.getQuickInfo();
		Returns a string showing the loaded scripts.		 
*/

/* Script Object */
function CDMScript(filename, path) {
	this.path = path;
	this.filename = filename;
}

/* Script Array */
function CDMScriptManager(name) {
	this.name = name;
	this.scriptCollection = new Array();
}	

/* Script Manager Functions */
CDMScriptManager.prototype = {								
	load: function(scriptPath, continueLoadOnConflict) {
		if(continueLoadOnConflict == 'undefined')
			continueLoadOnConflict = false;

		if(scriptPath == undefined) {
			document.write('<scr' + 'ipt><!-- Path is required to load "' + scriptPath + '" --></scr' + 'ipt>');
			return false;
		}

		var scriptFilename = this.getFilenameFromPath(scriptPath);				
		var isLoaded = this.isLoaded(scriptFilename);

		if(isLoaded != null)
			document.write('<scr' + 'ipt><!-- Warning: "'+scriptFilename+'" has been previously loaded. --></scr' + 'ipt>');
		
		if(isLoaded == null || continueLoadOnConflict) {										
			this.scriptCollection.push(new CDMScript(scriptFilename, scriptPath));

			document.write('<scr' + 'ipt type="text/javascript" src="' + scriptPath + '"></scr' + 'ipt>');
			
			return true;					
		}
		return false;
	},
	isLoaded: function(scriptFilename) {
		for(i=0;i<this.scriptCollection.length;i++) {
			if(this.scriptCollection[i].filename == scriptFilename) {
				return this.scriptCollection[i];
			}
		}
		return null;
	},
	getFilenameFromPath: function(path) {
		var regex = new RegExp(/([^\/\\]+)$/);
		var result = regex.exec(path);
		if (result == null)
			return null;
		else
			return result[0];
	},
	getLoadedScripts: function() {
		return this.scriptCollection;
	},
	getQuickInfo: function() {
		var result = '';
		for(i=0;i<this.scriptCollection.length;i++) {
			result += this.scriptCollection[i].path;
			result += (i != this.scriptCollection.length - 1) ? ', ' : '';
		}
		return result;
	}
}

/* Initialize Script Manager */
var CDMScriptManager = new CDMScriptManager('CDM Script Manager');
// /js/localNewsRedirect.js
// JavaScript Document
function reDirect(list) {
    var locationText = list.options[list.selectedIndex].text;
    var procookie;
    var loccodecookie;
    var stationcookie;
    var radarcookie;
    switch(locationText)
    {
        case "Global Winnipeg":
            loccodecookie = "CAXX0547";
            procookie = "mb";
            stationcookie = "gWI";
            radarcookie = "d2c8248f-5c18-4455-b46c-96ecf2ecf6d1";
            break;
        case "Global Lethbridge":
            loccodecookie = "CAXX0246";
            procookie = "ab";
            stationcookie = "gLB";
            radarcookie = "f0687d6b-82d2-4e66-a5ac-8a56e4126464";
            break;
        case "Global Calgary":
            loccodecookie = "CAXX0054";
            procookie = "ab";
            stationcookie = "gCAL";
            radarcookie = "fbb1c30d-382b-4716-ba76-b43a4c2b90e2";
            break;
        case "Global Edmonton":
            loccodecookie = "CAXX0126";
            procookie = "ab";
            stationcookie = "gED";
            radarcookie = "58c358c3-33af-4487-86d6-c95d326d7054";
            break;
        case "Global Saskatoon":
            loccodecookie = "CAXX0442";
            procookie = "sk";
            stationcookie = "gSA";
            radarcookie = "1c3de30d-2e04-424a-92af-cf01632022ab";
            break;
        case "Global Regina":
            loccodecookie = "CAXX0397";
            procookie = "sk";
            stationcookie = "gRE";
            radarcookie = "736f714f-6bc6-4786-b13f-060f59d0af5b";
            break;
        case "Global Toronto":
            loccodecookie = "CAXX0504";
            procookie = "on";
            stationcookie = "gTO";
            radarcookie = "8179195e-c811-4696-8cee-000465971a1d";
            break;
        case "Global Montreal":
            loccodecookie = "CAXX0301";
            procookie = "qc";
            stationcookie = "gMO";
            radarcookie = "45e5f33d-03c1-4ce8-a130-8ef16818e61f";
            break;
        case "CHBC News":
            loccodecookie = "CAXX0216";
            procookie = "bc";
            stationcookie = "gOK";
            radarcookie = "723bef42-a2a1-4990-be7d-74f3e2f37391";
            break;
        case "Global News":
            loccodecookie = "CAXX0504";
            procookie = "on";
            stationcookie = "gTO";
            radarcookie = "8179195e-c811-4696-8cee-000465971a1d";
            break;
		case "Global Maritimes":
            loccodecookie = "CAXX0183";
            procookie = "ns";
            stationcookie = "gMA";
            radarcookie = "37ee002e-1f58-4b16-9047-39ba0f55b084";
            break;
		case "Global BC":
			loccodecookie = "CAXX0518";
            procookie = "bc";
            stationcookie = "gBC";
            radarcookie = "ec76be22-9faa-43c8-9e32-a7f8d73509f3";
			break;
    }
	if($.cookies.get('wPro')){
		$.cookies.set('wPro', $.cookies.get('wPro'), { hoursToLive: -1 });
	}
	if($.cookies.get('wLocCode')){
		$.cookies.set('wLocCode', $.cookies.get('wLocCode'), { hoursToLive: -1 });
	}
	if($.cookies.get('wStation')){
		$.cookies.set('wStation', $.cookies.get('wStation'), { hoursToLive: -1 });
	}
	if($.cookies.get('wRadar')){
		$.cookies.set('wRadar', $.cookies.get('wRadar'), { hoursToLive: -1 });
	}
    var hoursToLive = 24 * 7 * 2;
    //$.cookies.set('wPro', procookie, { hoursToLive: hoursToLive });
    //$.cookies.set('wLocCode', loccodecookie, { hoursToLive: hoursToLive });
    //$.cookies.set('wStation', stationcookie, { hoursToLive: hoursToLive });
    $.cookies.set('wRadar', radarcookie, { hoursToLive: hoursToLive });
    location.href = list.options[list.selectedIndex].value;
    
}

// /js/classifiedTabs.js
// JavaScript Document
//classifiedTabs.inc
$(function(){
	try {
		$(".widgetClassifiedTabs").tabs();
	} catch (e) {};
});
// /js/videoSlider.js
$(function(){
	
	//setup top video slider
	var s = 3;
	$.jc = "";
	
	$('#mycarousel').css("visibility","visible")
		.jcarousel({
			start: 1,
			auto: 5,
			wrap: "both", //"circular",
			scroll: s,
			animation: 1500,
			initCallback: videoSliderCallback
	});
	
	var c = $("#widgetVideoSlider #mycarousel li").length;
	var n = 1;
	for(var i=0;i<Math.ceil(c/s);i++){
		var n = 1+(i*s);
		if(n>=c){
			n = c - (s-c%s);
		}		
		$("#widgetVideoSlider .videoSliderDots").append("<a href=\"#"+n+"\" id=\"videoSlider-"+(i+1)+"\"><img src=\"/images/global/Blank.gif\" width=\"9\" height=\"9\" /></a>");
	}
	
	$("#widgetVideoSlider .videoSliderDots a").click(function(){
		this.blur();
		var id = this.href.split("#");
		id = parseInt(id[1]);
		$.jc.startAuto(0);
		$.jc.scroll(id);
		return false;
	});
	
	
	//setup right rail video slider
	
	var sRR = 2;
	$.jcRR = "";
	$.jcRRprev = 1;
	
	$('#widgetVideoSliderRR #videoSlider').css("visibility","visible")
		.jcarousel({
			start: 1,
			auto: 5,
			scroll: sRR,
			wrap: "both",
			animation: 1500,
			buttonNextHTML: null,
			buttonPrevHTML: null,
			initCallback: videoSliderRRCallback,
			itemFirstInCallback: firstInCallBack
	});
	
	$("#widgetVideoSliderRR #videoSlider li:last").css("margin-right","0").css("padding-right","0");
	var cRR = $("#widgetVideoSliderRR #videoSlider li").length;
	var n = 1;
	for(var i=0;i<Math.ceil(cRR/sRR);i++){
		var n = 1+(i*sRR);
		if(n>=cRR){
			n = cRR - (sRR-c%sRR);
		}		
		$("#widgetVideoSliderRR .videoSliderDots").append("<a href=\"#"+n+"\" id=\"videoSlider-"+(i+1)+"\"><img src=\"/images/global/Blank.gif\" width=\"9\" height=\"9\" /></a>");
	}
	
	$("#widgetVideoSliderRR .videoSliderDots a").click(function(){
		this.blur();
		var id = this.href.split("#");
		id = parseInt(id[1]);
		$.jcRR.startAuto(0);
		$.jcRR.scroll(id);
		return false;
	});
	$("#widgetVideoSliderRR .videoSliderDots a:first").addClass("current");
	
	
});

function videoSliderCallback(e,s){
	$.jc = e;
	// Pause autoscrolling if the user moves with the cursor over the clip.
	e.clip.hover(function() {
		e.stopAuto();
	}, function() {
		e.startAuto();
	});
}
function videoSliderRRCallback(e,s){
	$.jcRR = e;
	// Pause autoscrolling if the user moves with the cursor over the clip.
	e.clip.hover(function() {
		e.stopAuto();
	}, function() {
		e.startAuto();
	});
}

function firstInCallBack(o,l,i,s){
	i /= 2;
	if($("#widgetVideoSliderRR .videoSliderDots a").eq($.jcRRprev).hasClass("current")){
		$("#widgetVideoSliderRR .videoSliderDots a").eq($.jcRRprev).removeClass("current");
	}
	$("#widgetVideoSliderRR .videoSliderDots a").eq(i).addClass("current");
	$.jcRRprev = i;
	
}

// /js/weatherWidget.js

// Home Page Weather Widget script

var localStationCookie = $.cookies.get('localStation');
var locationID;

$(document).ready(function(){

//get cookie value to determine user's location and assign appropriate location ID.
switch (localStationCookie) {
	case "BC":
		 $("#ww_forecastBC").show();
		break;
	case "Calgary":
		$("#ww_forecastCalgary").show();
		break;
	case "Edmonton":
		$("#ww_forecastEdmonton").show();
		break;
	case "Lethbridge":
		$("#ww_forecastLethBridge").show();
		break;
	case "Saskatoon":
		$("#ww_forecastSaskatoon").show();
		break;
	case "Regina":
		$("#ww_forecastRegina").show();
		break;
	case "Winnipeg":
		$("#ww_forecastWinnipeg").show();
		break;
	case "Ontario":
		$("#ww_forecastOntario").show();
		break;
	case "Quebec":
		$("#ww_forecastQuebec").show();
		break;
	case "Maritimes":
		$("#ww_forecastMaritimes").show();
		break;
	default:
		$("#ww_forecastBC").show();
};

});
/*
 * jQuery beforeafter plugin
 * @author admin@catchmyfame.com - http://www.catchmyfame.com
 * @version 1.2
 * @date October 18, 2010
 * @category jQuery plugin
 * @copyright (c) 2009 admin@catchmyfame.com (www.catchmyfame.com)
 * @license CC Attribution-NoDerivs 3.0 Unported - http://creativecommons.org/licenses/by-nc-sa/3.0/
 */
// before image : $('div:eq(2)', obj)
// after image  : $('div:eq(3)', obj)
(function($){
	$.fn.extend({ 
		beforeAfter: function(options)
		{
			var defaults = 
			{
				animateIntro : false,
				introDelay : 1000,
				introDuration : 1000,
				showFullLinks : true,
				imagePath : '/js/beforeAfter/'
			};
		var options = $.extend(defaults, options);

		var randID =  Math.round(Math.random()*100000000);
	
    		return this.each(function() {
			var o=options;
			var obj = $(this);

			var imgWidth = $('img:first', obj).width();
			var imgHeight = $('img:first', obj).height();
			
			$(obj)
			.width(imgWidth)
			.height(imgHeight)
			.css({'overflow':'hidden','position':'relative','padding':'0'});

			var bef = $('img:first', obj).attr('src');
			var aft = $('img:last', obj).attr('src');
			
			$('img:first', obj).attr('id','beforeimage'+randID);
			$('img:last', obj).attr('id','afterimage'+randID);

			$('img',obj).remove(); // jQuery 1.4.3 and the current webkit browsers don't play nice with dragging. By removing the images and using them as div background we work around this
			
			$('div', obj).css('float','left'); // Float all divs within the container left
			
			// Create an inner div wrapper (dragwrapper) to hold the images.
			$(obj).prepend('<div id="dragwrapper'+randID+'"><div id="drag'+randID+'"><img width="8" height="56" alt="handle" src="'+o.imagePath+'handle.gif" title="Drag me left or right to see the before and after images" id="handle'+randID+'" /></div></div>'); // Create drag handle
			$('#dragwrapper'+randID).css({'position':'absolute','padding':'0','left':(imgWidth/2)-($('#handle'+randID).width()/2)+'px','z-index':'20'}).width($('#handle'+randID).width()).height(imgHeight);
			$('#dragwrapper'+randID).css({'opacity':.25}); // Sets the dragwrapper and contents to .25 opacity
				
			$('div:eq(2)', obj).height(imgHeight).width(imgWidth/2).css({'background-image':'url('+bef+')','position':'absolute','overflow':'hidden','left':'0px','z-index':'10'}); // Set CSS properties of the before image div
			$('div:eq(3)', obj).height(imgHeight).width(imgWidth).css({'background-image':'url('+aft+')','position':'absolute','overflow':'hidden','right':'0px'});	// Set CSS properties of the after image div
			$('#drag'+randID).width(2).height(imgHeight).css({'background':'#888','position':'absolute','left':'3px'});	// Set drag handle CSS properties
			$('#beforeimage'+randID).css({'position':'absolute','top':'0px','left':'0px'});
			$('#afterimage'+randID).css({'position':'absolute','top':'0px','right':'0px'});
			$('#handle'+randID).css({'z-index':'100','position':'relative','cursor':'pointer','top':(imgHeight/2)-($('#handle'+randID).height()/2)+'px','left':'-3px'})
			
			$(obj).append('<img src="'+o.imagePath+'lt-small.png" width="7" height="15" id="lt-arrow'+randID+'"><img src="'+o.imagePath+'rt-small.png" width="7" height="15" id="rt-arrow'+randID+'">');

			if(o.showFullLinks)
			{	
				$(obj).after('<div class="balinks" id="links'+randID+'" style="position:relative"><span class="bflinks"><a id="showleft'+randID+'" href="javascript:void(0)">Show only before</a></span><span class="bflinks"><a id="showright'+randID+'" href="javascript:void(0)">Show only after</a></span></div>');
				$('#links'+randID).width(imgWidth);
				$('#showleft'+randID).css({'position':'relative','left':'0px'}).click(function(){
					$('div:eq(2)', obj).animate({width:imgWidth},200);
					$('#dragwrapper'+randID).animate({left:imgWidth-$('#dragwrapper'+randID).width()+'px'},200);
				});
				$('#showright'+randID).css({'position':'absolute','right':'0px'}).click(function(){
					$('div:eq(2)', obj).animate({width:0},200);
					$('#dragwrapper'+randID).animate({left:'0px'},200);
				});
			}

			var barOffset = $('#dragwrapper'+randID).offset(); // The coordinates of the dragwrapper div
			var startBarOffset = barOffset.left; // The left coordinate of the dragwrapper div
			var originalLeftWidth = $('div:eq(2)', obj).width();
			var originalRightWidth = $('div:eq(3)', obj).width();

			$('#dragwrapper'+randID).draggable({handle:$('#handle'+randID),containment:obj,axis:'x',drag: function(e, ui){
				var offset = $(this).offset();
				var barPosition = offset.left - startBarOffset;
				$('div:eq(2)', obj).width(originalLeftWidth + barPosition);
				$('#lt-arrow'+randID).stop().animate({opacity:0},0);
				$('#rt-arrow'+randID).stop().animate({opacity:0},0);
				}
			});

			if(o.animateIntro)
			{
				$('div:eq(2)', obj).width(imgWidth);
				$('#dragwrapper'+randID).css('left',imgWidth-($('#dragwrapper'+randID).width()/2)+'px');
				setTimeout(function(){
					$('#dragwrapper'+randID).css({'opacity':1}).animate({'left':(imgWidth/2)-($('#dragwrapper'+randID).width()/2)+'px'},o.introDuration,function(){$('#dragwrapper'+randID).animate({'opacity':.25},1000)});
					// The callback function at the end of the last line is there because Chrome seems to forget that the divs have overlay  hidden applied earlier
					$('div:eq(2)', obj).width(imgWidth).animate({'width':imgWidth/2+'px'},o.introDuration,function(){clickit();});
				},o.introDelay);
			}
			else
			{
				clickit();
			}

			function clickit()
			{
				$(obj).hover(function(){
						$('#lt-arrow'+randID).stop().css({'z-index':'20','position':'absolute','top':imgHeight/2-$('#lt-arrow'+randID).height()/2+'px','left':parseInt($('#dragwrapper'+randID).css('left'))-10+'px'}).animate({opacity:1,left:parseInt($('#lt-arrow'+randID).css('left'))-6+'px'},200);
						$('#rt-arrow'+randID).stop().css({'position':'absolute','top':imgHeight/2-$('#lt-arrow'+randID).height()/2+'px','left':parseInt($('#dragwrapper'+randID).css('left'))+10+'px'}).animate({opacity:1,left:parseInt($('#rt-arrow'+randID).css('left'))+6+'px'},200);
						$('#dragwrapper'+randID).animate({'opacity':1},200);
					},function(){
						$('#lt-arrow'+randID).animate({opacity:0,left:parseInt($('#lt-arrow'+randID).css('left'))-6+'px'},350);
						$('#rt-arrow'+randID).animate({opacity:0,left:parseInt($('#rt-arrow'+randID).css('left'))+6+'px'},350);
						$('#dragwrapper'+randID).animate({'opacity':.25},350);
					}
				);

				// When clicking in the container, move the bar and imageholder divs
				$(obj).click(function(e){
					
					var clickX = e.pageX - this.offsetLeft;
					var img2Width = imgWidth-clickX;
					$('#dragwrapper'+randID).stop().animate({'left':clickX-($('#dragwrapper'+randID).width()/2)+'px'},600);
					$('div:eq(2)', obj).stop().animate({'width':clickX+'px'},600);
					$('#lt-arrow'+randID).stop().animate({opacity:0},50);
					$('#rt-arrow'+randID).stop().animate({opacity:0},50);
				});
				$(obj).one('mousemove', function(){$('#dragwrapper'+randID).stop().animate({'opacity':1},500);}); // If the mouse is over the container and we animate the intro, we run this to change the opacity since the hover event doesnt get triggered yet
			}
  		});
    	}
	});
})(jQuery);
$(function(){
	$('.beforeAfter img').each(function(){
		$(this).attr('width', $(this).width()).attr('height', $(this).height())
	});	
	$('.beforeAfter').beforeAfter({
		animateIntro: true,
		showFullLinks:false,
		imagePath:'/js/jquery.beforeafter/'
	});
});


/* Lightbox Start */
(function($) {
	$.fn.cwiLB = function(op){
		//CanWestInteractive Lightbox
		// Version 1.0
		// Design by Andrew Davies. Code by Arron Gibson
		/* DEFAULTS FOR OPTIONS (op Object)*/
		if(op.target == null){
			op.target = this.attr('href');
		}
		if(op.speed == null){
			op.speed = "slow";
		}
		if(op.filter == null){
			op.filter = "#mediaGallery";
		}
		if(op.opacity == null){
			op.opacity = 0.6;
		}
		if(op.height == null){
			op.height = 700;
		}
		/*  CLICK FUNCTIONALITY */
		this.click(function(){
			if($("#cwpPlayerDiv")[0]){
				cwpTogglePause(true);
			}
			if(!$("#cwi_lb")[0]){
				$('<div id="cwi_lb" style="display:none;"><div id="cwi_lb_content" style="display:none;"><iframe id="cwi_lb_iframe" src="' + op.target + '" height="' + op.height + '" frameborder="0" ></iframe></div><div id="cwi_lb_bg"">&nbsp;</div></div>').appendTo("body");
			}
			$("#cwi_lb_bg").css("opacity", "0");
			$("#cwi_lb").show();
			$("#widgetVideoSliderRR").css('visibility', 'hidden');  // hide video widget (chrome and IE z-index issues)
			$("#cwi_lb_bg").fadeTo(op.speed, op.opacity, function (){  
				var mainCol = $("#mainColumn").offset();
				$("#cwi_lb_content").css("left", $(document).width()/2-480).css("margin-top", mainCol.top).fadeIn(op.speed, function(){ 
					$("#cwi_lb_bg").click(function(){
						$("#cwi_lb_content").fadeOut(op.speed, function(){ 
							$("#cwi_lb_bg").fadeTo(op.speed, 0.01, function(){ 
								$("#cwi_lb").remove(); 
								$("#mainColumn #theSpacer").remove();
								$("#widgetVideoSliderRR").css('visibility', 'visible');  // show video widget (chrome and IE z-index issues)
							}); 
						}); 
					});
					/*
					$.ajax({
						type: "GET",
						url: op.target,
						dataFilter: function(data){
							return $(data).filter(op.filter);
						},
						success: function(html){
							$("#cwi_lb_content").html(html);
							mediaAjaxComplete(op);
						}
					});
					*/
				});
			});
			$.scrollTo("#mainColumn", "slow");
			return false;
		});
		$(document).keyup(function(event){
			if (event.keyCode == 27) {
				$("#cwi_lb_bg").click();
			}
		});
		return this;
	}
})(jQuery);

/* Lightbox End */


/*
 * @name:        Shaw_EqualColumns
 * @description: jQuery Plugin: equalizes column heights 
 * @usage:       $('#parentContainerNode').Shaw_EqualColumns('.nodesToEqualize');
 */
(function( $ ) {
	$.fn.Shaw_EqualColumns = function(className) {
		// grab and store initial object scope
		root = $(this);
		// equalize the heights of all childNodes to whatever's tallest
		var maxHeight = 0;
		// reset to auto
		root.children(className).css('height', 'auto');
		// set to largest
		root.children(className).each(
			function() {
				maxHeight = (this.offsetHeight > maxHeight) ? this.offsetHeight : maxHeight;
			}
		).css('height', maxHeight);
		return root;
	};
})( jQuery );
/* Shaw_EqualColumns END */



/*
 * @name:        Shaw_TopicNav
 * @description: jQuery Plugin: highlights the current page in a topic nav
 * @usage:       $('#parentContainerNode').Shaw_TopicNav('.nodesToEqualize');
 */
(function( $ ) {
	$.fn.Shaw_TopicNav = function(itemClass, linkClass, activeClass) {
		// grab and store initial object scope
		root = $(this);
		if (!root) return false;

		// set defaults
		var prop = {
			'itemClass':   (itemClass)   ? itemClass   : 'menuItem' ,	// className of <li> menu items
			'linkClass':   (linkClass)   ? linkClass   : 'linkItem' ,	// className of <a> menu links
			'activeClass': (activeClass) ? activeClass : 'active'		// className of an active menu item
		};

		// get all links
		var links = root.find('.'+ prop.linkClass);
		
		// loop through links, find an href that matches current URL, and add 'active' to parent node
		links.each( function(index, element) {
			if (element.href==window.location.href) {
				$(element).parents('.'+ prop.itemClass).addClass(prop.activeClass);
			};
		});

		// return root node to maintain jQuery chainability
		return root;
	};
})( jQuery );
/* Shaw_TopicNav END */


