﻿/*
  Insider blog:
    sliding preview articles, 
    right menu highlighting, 
    YouTube insertions,
    dancing social icons
*/

(function() {
    var ytActive = true; // Set to false to deactivate YouTube videos

    jQ(document).ready(function() {
        articles();
    });

    var articles = function() {
        var indArticle = {};
        var speed = 500;
        var localeBasePath = mcLaren.utils.locale;

        var init = function() {

            // Article list (home and category pages)
            jQ('.article-preview').each(function(i) {
                var that = this;
                var jQobjRoot = jQ(that).parents('li');
                var hasPreview = (jQobjRoot.find('.has-preview').length > 0) ? true : false;

                // Determine if images are completely loaded for animation height purposes
                if (jQobjRoot.find('.article-preview').find('img').length > 0) {
                    detectImagesLoaded(jQobjRoot.find('.article-preview'), prContinueProcessing);
                } else {
                    prContinueProcessing();
                }

                function prContinueProcessing() {
                    var prevH = jQ(that).height();

                    // Has a preview break point
                    if (hasPreview) {
                        var jQbtn = jQobjRoot.find('.iN-more');
                        var ajaxUrl = '/' + localeBasePath + 'insider/themes/insider/post-ajax.aspx?postid=' + jQbtn.attr('data-blogid') + '&site=' + escape(document.location.protocol + '%2F%2F' + document.location.hostname);

                        // Instantiate the class
                        indArticle[i] = new Article(jQobjRoot, prevH, ajaxUrl, hasPreview);

                        jQ(jQbtn).click(function(i) {
                            return function(e) {
                                indArticle[i].open();
                                return false;
                            };
                        } (i));

                        jQobjRoot.append('<a href="#" class="iN-close replaced"><span> </span>Close</a>');
                        jQobjRoot.find('.iN-close').click(function(i) {
                            return function(e) {
                                indArticle[i].close();
                                return false;
                            };
                        } (i)).hide();

                        // Youtube parser
                        if (ytActive) {
                            if (jQobjRoot.find('.social-video').length > 0) {
                                indArticle[i].ajax('initialising');
                            }
                        }
                    }
                    // Does not have a preview break point
                    else {
                        // Instantiate the class
                        indArticle[i] = new Article(jQobjRoot, prevH, '', hasPreview);
                        if (ytActive) {
                            if (jQobjRoot.find('.social-video').length > 0) {
                                socialVideo(jQobjRoot);
                            }
                        }
                        // Load icons via javascript
                        socialShare(jQobjRoot, indArticle[i]);
                    }
                }
            });

            // Single Article
            if (jQ('#iN-single-article').length > 0) {
                if (ytActive) {
                    if (jQ('#iN-single-article').find('.social-video').length > 0) {
                        socialVideo(jQ('#iN-single-article'));
                    }
                }
                bindSocialAnimation();
            }
        }

        // Constructor
        function Article(jQobjRoot, previewHeight, url, hasPreview) {
            this.jQobj = jQobjRoot;
            this.previewHeight = previewHeight;
            this.hasPreview = hasPreview;
            this.fullHeight = 0;
            this.url = url;
            this.active = false;
            this.socialVideo = false;
            this.shareIconsActive;
        }

        // Methods
        Article.prototype = {
            open: function() {
                var that = this;
                if (that.active) return false;

                if (that.jQobj.find('.article-full').length === 0) {
                    that.ajax();
                } else {
                    that.active = true;
                    that.jQobj.find('.iN-more, .iN-close').toggle();
                    that.jQobj.find('.iN-categories-post').show();
                    if (that.socialVideo === false) that.jQobj.find('.article-preview, .article-full').toggle();

                    that.jQobj.find('.article-full').animate({ height: that.fullHeight }, speed, function() {
                        that.active = false;
                        if (!that.shareIconsActive) {
                            bindSocialAnimation(that, 'preview');
                            that.shareIconsActive = true;
                        }
                    });
                    jQ('.iN-article-list li').each(function() {
                        if (jQ(this).find('a').text() === that.jQobj.find('h2.iN-article-title').text()) {
                            jQ(this).find('a').css({ 'color': '#fff' }).hover(
                            function() {
                                jQ(this).css({ 'color': '#666' });
                            },
                            function() {
                                jQ(this).css({ 'color': '#fff' });
                            });
                            Cufon.refresh('.iN-article-list a', {
                                hover: true
                            });

                            if (jQuery.browser.safari) {
                                jQ(this).css({ 'backgroundColor': '#F7931E' });
                            } else {
                                jQ(this).find('a').animate({ backgroundColor: '#F7931E' }, speed, function() {
                                    jQ(this).css({ 'backgroundColor': '#F7931E' });
                                });
                            }
                        }
                    });
                }
            },
            close: function() {
                var that = this;
                that.active = true;
                that.jQobj.find('.iN-more, .iN-close').toggle();
                that.jQobj.find('.iN-categories-post').hide();

                that.jQobj.find('.article-full').animate({ height: that.previewHeight }, speed, function() {
                    if (that.socialVideo === false) that.jQobj.find('.article-preview, .article-full').toggle();
                    that.active = false;
                });
                jQ('.iN-article-list li').each(function() {
                    if (jQ(this).find('a').text() === that.jQobj.find('h2.iN-article-title').text()) {
                        jQ(this).find('a').css({ 'color': '#666' }).hover(
                        function() {
                            jQ(this).css({ 'color': '#f7931e' });
                        },
                        function() {
                            jQ(this).css({ 'color': '#666' });
                        });
                        Cufon.refresh('.iN-article-list a', {
                            hover: true
                        });
                        if (jQuery.browser.safari) {
                            jQ(this).css({ 'backgroundColor': '' });
                        } else {
                            jQ(this).find('a').animate({ backgroundColor: '#fff' }, speed, function() {
                                jQ(this).css({ 'backgroundColor': '' });
                            });
                        }
                    }
                });
            },
            ajax: function(init) {
                var that = this;
                that.active = true;

                var delay = function() { that.redirectToPage(); };

                that.loadingTimer = setTimeout(delay, 15000);
                that.jQobj.append('<span class="iN-loading">Loading</span>');
                that.jQobj.find('.iN-more').toggle();

                var fullArticleRequest = jQ.ajax({
                    url: that.url,
                    cache: false,
                    dateType: 'html',
                    error: function() {
                        that.redirectToPage();
                    },
                    success: function(html) {
                        clearTimeout(that.loadingTimer);

                        html = html.substring(html.indexOf('::START::') + 9, html.indexOf('::END::'));

                        that.createFull(html, init);
                    }
                });
            },
            createFull: function(html, init) {
                var that = this;

                that.jQobj.find('.article-preview').after(html);

                var continueProcessing = function() {
                    that.fullHeight = that.jQobj.find('.article-full').height();


                    socialVideo(that.jQobj.find('.article-full'));

                    if (that.jQobj.find('.article-full').find('object').length > 0) {
                        that.socialVideo = true;
                        that.previewHeight = that.previewHeight + (that.jQobj.find('.article-preview').find('.social-video').length * 340);
                        that.fullHeight = that.fullHeight + (that.jQobj.find('.article-full').find('object').length * (340 - 10));
                        that.jQobj.find('.article-full').height(that.previewHeight).show();
                        that.jQobj.find('.article-preview').hide();
                    } else {
                        that.jQobj.find('.article-full').height(that.previewHeight);
                    }

                    that.jQobj.find('.iN-loading').remove();

                    if (that.fullHeight - 20 < that.previewHeight) {
                        that.jQobj.find('.iN-more, iN-close').remove();
                    } else {
                        that.jQobj.find('.iN-more').toggle();
                    }
                    that.active = false;

                    if (!init) that.open();
                }

                if (that.jQobj.find('.article-full').find('img').length > 0) {
                    detectImagesLoaded(that.jQobj.find('.article-full'), continueProcessing);
                } else {
                    continueProcessing();
                }

            },
            redirectToPage: function() {
                var that = this;
                window.location = that.jQobj.find('.iN-more').attr('href');
            }
        }

        init();
    }

    var socialVideo = function(jQparentObj) {
        // Convert p to div for more stable swfobject replacement
        jQparentObj.find('.social-video').each(function(i) {
            jQ(this).replaceWith(jQ('<div class="social-video">' + this.innerHTML + '</div>'));
        });

        jQparentObj.find('.social-video').each(function(i) {
            try {
                var jQlink = jQ(this).find('a');
                var href = jQlink.attr('href');

                if (href.indexOf('youtube.com/watch?v') !== -1) {
                    var href = href.substring(href.indexOf('=') + 1, href.length);
                    var now = new Date();
                    now = now.getTime();
                    var id = 'yTobj' + i + href + now;
                    jQ(this).attr('id', id);
                    var swf = "http://www.youtube.com/v/" + href + '&hl=en&fs=1&';

                    var flashvars = {};
                    var params = {};
                    params.allowfullscreen = "true";
                    params.allowscriptaccess = "always";
                    params.wmode = "transparent";

                    swfobject.embedSWF(swf, id, "420", "340", "10.0.0", "/global/flash/expressInstall.swf", flashvars, params);
                }
            } catch (err) { };

        });
    }

    // All images need to be fully loaded before determining the elements height
    var detectImagesLoaded = function(obj, callback) {
        var imgCount = 0;

        var addImage = function() {
            imgCount++;
            if (imgCount === obj.find('img').length) {
                callback();
            }
        }

        for (i = 0; i < obj.find('img').length; i++) {
            // If image not loaded put on load. Has to be array rather than 'each' for .complete to work
            if (!obj.find('img')[i].complete) {
                jQ(obj.find('img')[i]).load(function() {
                    addImage();
                });
            } else {
                addImage();
            }
        }
    }

    // On list page, if no preview break then add social icons
    // (because CKS:EBE can't deal with hostname outside of post.xsl)
    var socialShare = function(jQobj, articleObj) {
        var curHeading = jQobj.find('h2 a');
        var url = document.location.protocol + document.location.host + curHeading.attr('href');
        var title = curHeading.text();

        var shareText = '\n\
        <span class="iN-categories-post">\n\
            &#160;\n\
            <a href="http://www.facebook.com/share.php?u=' + url + '" target="_blank" title="Facebook">\n\
                <img src="/global/siteware/image/social/facebook.gif" alt=""/>Facebook\n\
            </a>\n\
            &#160;\n\
            <a href="http://twitter.com/home?status=Currently reading ' + url + '" target="_blank" title="Click to share this post on Twitter">\n\
                <img src="/global/siteware/image/social/twitter.gif" alt=""/>Twitter\n\
            </a>\n\
            &#160;\n\
            <a href="http://www.stumbleupon.com/submit?url=' + url + '&amp;title=' + title + '" target="_blank" title="Add to StumbleUpon">\n\
                <img src="/global/siteware/image/social/stumbleupon.gif" alt=""/>StumbleUpon\n\
            </a>\n\
            &#160;\n\
            <a href="http://reddit.com/submit?url=' + url + '&amp;title=' + title + '" target="_blank" title="Reddit">\n\
                <img src="/global/siteware/image/social/reddit.gif" alt=""/>Reddit\n\
            </a>\n\
            &#160;\n\
            <a href="http://digg.com/submit?phase=2&amp;url=' + url + '" target="_blank" title="Digg it">\n\
                <img src="/global/siteware/image/social/digg.gif" alt=""/>Digg\n\
            </a>\n\
            &#160;\n\
            <a href="http://del.icio.us/post?url=' + url + '&amp;title=' + title + '" target="_blank" title="Add to del.icio.us">\n\
                <img src="/global/siteware/image/social/delicious.gif" alt=""/>Delicious\n\
            </a>\n\
        </span>';
        jQobj.find('.article-preview').each(function() {
            if (jQ(this).find('.iN-categories-post').length === 0) {
                jQ(this).append(shareText);
            }
        });
        bindSocialAnimation(articleObj, 'preview');
    }

    var bindSocialAnimation = function(articleObj, view) {
        var delay = 100;
        var openSpeed = 100;
        var closeSpeed = 600;
        var rightPadding = 20;
        var jQlinks;
        var that;

        if (view === 'preview') {
            that = articleObj;
            jQlinks = articleObj.jQobj.find('.iN-categories-post a');
        } else {
            that = this;
            jQlinks = jQ('.iN-categories-post a');
        }
        that.shareIconAry = new Array();

        init = function() {
            jQlinks.each(function(i) {
                that.shareIconAry[i] = new ShareIcon(i, jQ(this), jQ(this).width() + rightPadding);

                jQ(this).hover(function() { //mouse in
                    return function(e) {
                        that.shareIconAry[i].jQobj.stop();
                        openItem(that.shareIconAry[i]);
                    } ();

                }, function() { //mouse out
                    return function(e) {
                        that.shareIconAry[i].jQobj.stop();
                        closeItem(that.shareIconAry[i]);
                    } ();
                });

                closeItem(that.shareIconAry[i]);
            });
        }

        openItem = function(obj) {
            obj.jQobj.animate({ width: obj.startWidth }, openSpeed);
        }

        closeItem = function(obj) {
            obj.jQobj.animate({ width: '0' }, closeSpeed);
        }

        function ShareIcon(id, jQobj, startWidth) {
            this.id = id;
            this.jQobj = jQobj;
            this.startWidth = startWidth;
        }

        init();
    }

})();
