/************************************************************

Chatelaine - main.js

July 2010

************************************************************/

$(document).ready(function () {


    // legacy placeholder support
    $('input[placeholder], textarea[placeholder]').each(function () {
        new Xteam.Ui.Form.Placeholder(this);
    });



    // external links (new window)

    $('a[rel=_blank]').click(function () {
        this.target = "_blank";
    });

    //
    $('.td_tops_mostpopular ul:eq(2)').addClass('td_tops_mostpopular_ul');
    $('.td_toplist li:has(img)').addClass('td_hasimage');
    $('.td_toplist li:has(em)').addClass('td_hasem');


    if ($.browser.opera) {

        // add body class for opera
        $('body').addClass('opera');

    }

    if ($.browser.safari) {

        // add body class for opera
        $('body').addClass('safari');

    }

    // if browser is IE
    if (($.browser.msie)) {
        $(".td_main .td_new .td_mod_bd li:first").css("margin-left", "6px");
        $(".td_nav_popup_feature p").css("letter-spacing", "0.01em");
        $('.td_quiz .td_mod_tools a:first-child').css({ 'float': 'left' });
        $('.td_list_02 .td_tsr:first-child').css({ 'margin-left': '0' });
        $('.td_top5_bd li:last-child a').css({ 'background': 'none' });
        $('.td_top5_bd li:last-child a').css({ 'padding-bottom': '10px' });
        $('.td_top5_bd li:first-child a').css({ 'padding-top': '10px' });
        $('.td_tops_mostpopular li:last-child a').css({ 'background': 'none' });
        $('.td_tops_mostpopular li:last-child a').css({ 'padding-bottom': '10px' });
        $('.td_tops_mostpopular li:first-child a').css({ 'padding-top': '10px' });
        $('.td_blognews li:first-child a').css({ 'padding-top': '10px' });
        $('.td_blognews li:last-child a').css({ 'padding-bottom': '10px' });
        $('.td_blogged .td_list_01 .td_tsr').css({ 'border': '0' });
        $('.td_roundup li:last-child').css({ 'margin-right': '0' });
        $('.td_recipeindex .td_top5_bd li a:last-child').css({ 'background-image': 'none' });
        $('.td_meta dd:last-child').css({ 'border': '0' });
        $('.td_rssfeeds a:first-child').css({ 'background': 'url(images/ico_rss-small.png) no-repeat center left' });
        $('.td_tops_mostpopular .td_tops_mostpopular_ul li:first-child .td_tops_mostpopular_section a').css({ 'padding-top': '0' });
        $('.td_tops_mostpopular .td_tops_mostpopular_ul li:first-child strong').css({ 'padding-left': '0' });

    }

    // if browser is IE
    if ($.browser.msie) {
        $('body').addClass('ie')
    }

    // if browser is IE8
    if (($.browser.msie) && ($.browser.version == "8.0")) {

        // add body class for IE8
        $('body').addClass('ie8');

    }

    // if browser is IE7
    if (($.browser.msie) && ($.browser.version == "7.0")) {
        $('.td_ctwrap img:first-child').css({ 'float': 'left' });
        // add body class for IE7
        $('body').addClass('ie7');

    }

    // if browser is IE6
    if (($.browser.msie) && ($.browser.version == "6.0")) {

        // add body class for IE6
        $('body').addClass('ie6');
        $(".td_watch .td_carousel li:first").css("margin-left", "20px");
        $('.td_ctwrap img:first-child').css({ 'float': 'left' });
        // png support for IE6
    }





    // Tabs
    $.each(['.td_tabs a'], function (i, selector) {
        new UITabs(selector, 'td_active');
    });


    //containerSelector, slideContainerSelector, slideSelector, slideGroup, controlsSelector, paginationSelector, paginationCurrentClass, afterChangeCallback


    // Global defaults
    UICarousel.prototype.options.controlsNextSelector = '.td_next';
    UICarousel.prototype.options.controlsPrevSelector = '.td_prev';
    UICarousel.prototype.options.paginationCurrentClass = 'td_active';
    UICarousel.prototype.options.paginationSelector = '.td_pagination li';
    UICarousel.prototype.options.slideCurrentClass = 'td_current';

    // Featured Carousel
    var featured_carousel = new UICarousel({
        containerSelector: '.td_featured',
        slideContainerSelector: '.td_carousel',
        controlsSelector: '.td_carousel_controls a'
    });

    // Magazine Carousel
    var magazine_carousel = new UICarousel({
        containerSelector: '.td_frommag',
        slideContainerSelector: '.td_carousel',
        controlsSelector: '.td_carousel_controls a'
    });

    // Watch Carousel
    var watch_carousel = new UICarousel({
        containerSelector: '.td_watch',
        slideGroup: 3,
        slideContainerSelector: '.td_carousel',
        controlsSelector: '.td_carousel_controls a'
    });

    // Recipe Carousel
    var recipe_carousel = new UICarousel({
        containerSelector: '.td_recipecarousel',
        slideGroup: 3,
        slideContainerSelector: '.td_carousel',
        controlsSelector: '.td_carousel_controls a'
    });

    var gallery_carousel = new UICarousel({
        containerSelector: '.td_gal_slideshow',
        slideContainerSelector: '.td_gal_slides > ul',
        controlsSelector: '.td_gal_nav a, .td_gal_slides > a',
        afterChangeCallback: function () {
            this.container.find('.td_current_image').text(this.currentSlide + 1);
            this.controls.filter('.td_gal_nav_prev').find('span').text(this.slides.eq(this.move(-1)).find('h3').text());
            this.controls.filter('.td_gal_nav_next').find('span').text(this.slides.eq(this.move(1)).find('h3').text());
        }
    });


    var article_carousel = new UICarousel({
        containerSelector: '.td_article_carousel',
        slideContainerSelector: '.td_article_carousel_ul',
        slideCurrentClass: '',
        controlsSelector: '.td_carousel_controls a',
        hideSlideCallback: function (slide) {
            //slide.find('.td_article_carousel_img').hide();
            slide.find('a').removeClass('td_active');

            return slide;
        },
        showSlideCallback: function (slide) {
            if ($("#Subvertical").length == 0) {
                slide.find('.td_article_carousel_img').show();
                slide.find('a').addClass('td_active');
            }

            return slide;
        }
    });
    $('.td_article_carousel_ul a').bind('mouseenter', function () {
        article_carousel.loadSlide(this);
    });

    // Custom Scrollbar
    $('.td_tops_twitter .td_mod_bd').jScrollPane({
        showArrows: true,
        scrollbarWidth: 17,
        reinitialiseOnImageLoad: true
    });

    $('input[type="radio"]').each(function () {
        new Xteam.Ui.Form.Radio(this);
    });

    //overlay
    if ($(".td_overlay").length) {
        $("a.td_overlay_trigger[rel]").overlay({
            mask: {
                color: '#000',
                loadSpeed: 200,
                opacity: 0.52
            },
            fixed: false,
            top: "35%"
        });
    }

});

function UITabs(tabSelector, currentClassName) {

    // Construct an object if we're called as a function
    if (this.constructor === window.constructor) {
        return new UITabs(tabSelector);
    }

    this.tabs = $(tabSelector);


    if (this.tabs.length === 0) {
        return false;
    }

    this.tabContent = {};
    this.tabLinks = {};

    this.currentClassName = currentClassName || 'current';
    this.current = $();

    this.initialTab = this.tabs.first().attr('href').replace('#', '');

    this.tabs.each(this.initTab.bind(this));

    if (document.location.hash) {
        var doc_hash = document.location.hash.replace('#', '');

        if (this.tabContent.hasOwnProperty(doc_hash)) {
            this.initialTab = doc_hash;
            window.setTimeout(function() {
                window.scrollTo(0, 0);
            }, 500);
        }
    }


    this.loadTab(this.initialTab)
}

UITabs.prototype.initTab = function(index, element) {
    element = $(element);
    var tabID = element.attr('href').replace('#', '');


    if (element.closest('.' + this.currentClassName).length > 0) {
        this.initialTab = tabID;
    }

    this.tabLinks[tabID] = element;
    this.tabContent[tabID] = $('#' + tabID).attr('id', '').hide();

    element.click(this.handleClick.bindAsEventListener(this));
};

UITabs.prototype.handleClick = function(event) {
    var element = $(event.target).closest('a'),
		tabID = element.attr('href').replace('#', ''),
		tab = this.tabContent[tabID];

    this.loadTab(tabID);
};

UITabs.prototype.loadTab = function(tabID) {
    var tabElement = this.tabContent[tabID],
		tabLink = this.tabLinks[tabID];

    this.current.hide();
    this.tabs.closest('.' + this.currentClassName).removeClass(this.currentClassName);
    tabElement.show();
    tabLink.parent().addClass(this.currentClassName);
    this.current = tabElement;
};

function UICarousel(options) {


    this.options = $.extend(true, {}, this.options, options || {});


    this.container = $(this.options.containerSelector);

    this.slideContainer = this.container.find(this.options.slideContainerSelector);
    this.slides = this.slideContainer.find(this.options.slideSelector);

    this.controls = this.container.find(this.options.controlsSelector);

    if (!this.options.paginationSelector) {
        this.pagination = false;
    }
    else {
        this.pagination = this.container.find(this.options.paginationSelector);
    }

    this.currentSlide = 0

    if (this.options.slideCurrentClass) {
        var defaultSlide = this.slides.filter('.' + this.options.slideCurrentClass);
        if (defaultSlide.length) {
            this.currentSlide = this.slides.index(defaultSlide);
        }
    }

    this.options.hideSlideCallback(this.slides.not(this.getSlides(this.currentSlide)));
    this.currentVisible = this.options.showSlideCallback(this.getSlides(this.currentSlide)).length;


    this.controls.bind(this.options.controlEvents, this.handleControlClick.bindAsEventListener(this));
    if (this.pagination) {
        this.pagination.bind(this.options.paginationEvents, this.handlePaginationClick.bindAsEventListener(this));
    }
}

UICarousel.prototype.options = {
    // Selectors
    containerSelector: '.carousel',
    slideContainerSelector: 'ul',
    slideSelector: 'li',
    slideCurrentClass: 'current',
    slideGroup: 1,

    controlsSelector: '.controls a',
    controlsNextSelector: '.next',
    controlsPrevSelector: '.prev',

    paginationSelector: '.pagination a',
    paginationCurrentClass: 'current',

    // Callbacks
    afterChangeCallback: function() { },
    beforeChangeCallback: function() { },
    hideSlideCallback: function(slide) {
        return slide.hide();
    },
    showSlideCallback: function(slide) {
        return slide.show();
    },

    // Events
    controlEvents: 'click',
    paginationEvents: 'click'

};

UICarousel.prototype.move = function(direction) {
    var newSlide = this.currentSlide + (this.currentVisible * direction);

    while (newSlide > this.slides.length - 1) {
        newSlide = newSlide - this.slides.length;
    }

    while (newSlide < 0) {
        newSlide = newSlide + Math.ceil(this.slides.length / this.options.slideGroup) * this.options.slideGroup;
    }

    return newSlide;
};

UICarousel.prototype.loadSlide = function(newSlide) {
    var oldSlide = this.currentSlide;

    if (typeof newSlide !== 'number') {
        newSlide = this.slides.index($(newSlide).closest(this.options.slideSelector));
    }

    this.options.beforeChangeCallback.call(this, newSlide);

    this.options.hideSlideCallback(this.getSlides(this.currentSlide));
    this.currentVisible = this.options.showSlideCallback(this.getSlides(newSlide)).length;

    this.slides.eq(this.currentSlide).removeClass(this.options.slideCurrentClass);
    this.slides.eq(newSlide).addClass(this.options.slideCurrentClass);

    if (this.pagination) {
        this.pagination.eq(this.currentSlide / this.options.slideGroup).closest(this.options.paginationSelector).removeClass(this.options.paginationCurrentClass);
        this.pagination.eq(newSlide / this.options.slideGroup).closest(this.options.paginationSelector).addClass(this.options.paginationCurrentClass);
    }

    this.currentSlide = newSlide;
    this.options.afterChangeCallback.call(this, oldSlide);
};

UICarousel.prototype.getSlides = function(startFrom) {
    var slides = this.slides.eq(startFrom);

    for (var i = 0; i < this.options.slideGroup && i + startFrom <= this.slides.length; i++) {
        slides = slides.add(this.slides.eq(startFrom + i));
    }

    return slides;
};

UICarousel.prototype.handleControlClick = function(event) {
    event.preventDefault();

    var element = $(event.target);

    if (element.closest(this.options.controlsNextSelector).length > 0) {
        this.loadSlide(this.move(1));
    }
    else if (element.closest(this.options.controlsPrevSelector).length > 0) {
        this.loadSlide(this.move(-1));
    }
};

UICarousel.prototype.handlePaginationClick = function(event) {
    event.preventDefault();

    this.loadSlide(this.options.slideGroup * this.pagination.index($(event.target).closest(this.pagination.selector)));
};




