var Cap_Social_Media_Center = {};

//box.store('authToken').addDatas('facebookToken',jQuery.get("https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=112314185509530&client_secret=6ca775e2721fbb5f2d7f96fa7dbcbf70"));
//console.log($.get("https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=112314185509530&client_secret=6ca775e2721fbb5f2d7f96fa7dbcbf70"));

box.store('l10n').addDatas('Cap_Social_Media_Center', {
    accessPageFB: 'Go to Facebook of {$user} (new window)',
    accessPageYoutube: 'Go to  Youtube page of {$user} (new window)',
    accessVideo: 'Go to the video {$video} (new window)',
    authorFrom: 'From : ',
    viewsCountYoutube: ' views',
    url: { 
        FBFanPage: 'http://www.facebook.com/profile.php?id=',
        FBScriptFansCount: 'http://graph.facebook.com/LOrealParisCanada?callback=Cap_Social_Media_Center.FBDisplayFansCount',
        /*FBScriptPosts: 'https://graph.facebook.com/lorealpariscanada/posts?access_token=112314185509530|Gac1IwLTBviWkaRDyEk-ydS8bUU&callback=Cap_Social_Media_Center.FBDisplayPosts',*/
        YoutubeDisplayFansCount: 'http://gdata.youtube.com/feeds/api/users/LOrealParisCanada?alt=json-in-script&callback=Cap_Social_Media_Center.YoutubeDisplayFansCount',
        YoutubeDisplayFocus: 'http://gdata.youtube.com/feeds/users/LOrealParisCanada/uploads?alt=json-in-script&callback=Cap_Social_Media_Center.YoutubeDisplayFocus&max-results=1&orderby=published',
        YoutubeDisplayMostViewed: 'http://gdata.youtube.com/feeds/users/LOrealParisCanada/uploads?alt=json-in-script&callback=Cap_Social_Media_Center.YoutubeDisplayMostViewed&max-results=4&orderby=viewCount',
		TwitterFeed: 'http://twitter.com/statuses/user_timeline/lorealpariscan.json?callback=Cap_Social_Media_Center.TwitterFeedDisplay',
		SyncapseRSS: 'http://loreal.socialfeeds.syncapse.com/feed/rss?l=MTAwMDE',
        GoogleFeedAPI: 'https://www.google.com/jsapi?autoload=%7B%22modules%22%3A%5B%7B%22name%22%3A%22feeds%22%2C%22version%22%3A%221%22%2C%22callback%22%3A%22Cap_Social_Media_Center.FBRSSDisplayPosts%22%2C%22nocss%22%3A%22true%22%7D%5D%7D&key=ABQIAAAAq3Fe78LaltSbJMg5H9OHIRS7FEeQt28MiNsgoQs9QXrujS5PkhR1ihyIu4zqWd59px-eglOPdQeGhg'

    },
    months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
});

box.subscribe({
    name: 'load>lop:capsule.Cap_Social_Media_Center.home',
    handler: function(oEvt) {
        var oContainer = this.rootElm,
            nContainerW = oContainer.width(), 
            nSectionW = oContainer.width() - oContainer.find('div.expands').width(),
            oCurrent, bAvailable,
            l10n = box.get('l10n:Cap_Social_Media_Center');
         
        //oContainer.find('div.content').width(nSectionW);
        oContainer.find('div.visual').hover(function() {
            box.dom(this.parentNode).addClass('hovered');
        }, function() {
            box.dom(this.parentNode).removeClass('hovered');
        }).click(function(e) { 
			 
			
			if(e.target === this) {
                var oItem = box.dom(this.parentNode);
                
                if(oItem.hasClass('on')) {  
                    oItem.removeClass('on');
                    oItem.animate({
                        width: 129
                    }, 500, function() {
                        oCurrent = null;
                    });
                } else {
                    if(bAvailable !== false) {
                        bAvailable = false; 
                        oItem.addClass('on').animate(
                            {
                                width: 692
                            }, {
                                duration: 500,
                                step: function(nWidth) {
                                    if(oCurrent) {
                                        oCurrent.width(129);
                                    }
                                }, 
                                complete: function() {
                                    if(oCurrent) {
                                        oCurrent.removeClass('on');
                                    }
                                    bAvailable = true;
                                    oCurrent = oItem;
                                }
                            }
                        );
                    }
                }
            }
			
			
        });     
		  
		  
		 
        box.get('ui').modifyConfig('scroll', {
            bar: '<a href="#" class="{$barCls}"><span class="start"></span><span class="end"></span></a>'
        });
        
        var getYearMonthDay = (function() {
            var reDate = /^(\d{4})-(\d{2})-(\d{2}).+$/;
            
            return function(sDate) {
                var aMatch = sDate.match(reDate);
                return {
                    year: Number(aMatch[1]),
                    month: Number(aMatch[2]), 
                    day: Number(aMatch[3])
                };
            };
        }());
        
        var linkize = (function() {
            var reUrl = /(https?:[^\s]+)/g,
                reSuffix = /^(.+)([.,;:!?()]+)$/;
            
            return function(sContent) {
                return !sContent ? '' : sContent.replace(reUrl, function(sAll, sMatch) {
                    var aMatch = sMatch.match(reSuffix),
                        sUrl = aMatch ? aMatch[1] : sMatch,
                        sSuffix = aMatch ? aMatch[2] : '';
                    return '<a href="' + sUrl + '" target="_blank">' + sUrl + '</a>' + sSuffix;
                });
            };
        })();
        
        Cap_Social_Media_Center.FBDisplayFansCount = function(oResponse) {
            oContainer.find('div#content-facebook .counter span').html(oResponse.likes);
        };
        
		
		Cap_Social_Media_Center.TwitterFeedDisplay = function(oResponse) {
			//load twitter functions
			jQuery.getScript("http://platform.twitter.com/widgets.js");
			
			 var sHTML = '',
                oItem,
                i = -1,
                oItem = oResponse,
                //l = oItem.length,
                oDate, sDate;
				
				
				for (tweet in oItem){
					//29 Jul 2011 20:06:44
					var tweetDate = oItem[tweet]['created_at'].split(" ");
					tweetDate = tweetDate[0]+" "+tweetDate[1]+" "+ tweetDate[2]+" "+ tweetDate[3];
					oContainer.find('div#content-twitter').append(
					"<div class=\"tweet\">" + 
					"<img src=\"http://a1.twimg.com/profile_images/1282757601/twitterloreal_reasonably_small.jpg\">"+
					"<span class=\"user-id\"><a href=\"http://twitter.com/#!/lorealparisCAN\">LorealParisCAN</a></span>"+
					linkize(oItem[tweet]['text']) +
					"<span class=\"tweet-date\">"+tweetDate+"</span></div>"
					
					);	
				}
				 
				// oContainer.find('div#content-twitter').append(sHTML);
				 
			  box.get('ui').create('scroll.twitter', {
                rootElm: '#content-twitter',
                buttons: true,
                bar: true, // mandatory when buttons are present
                barMinSize: 70
            });
			
		};
		
        Cap_Social_Media_Center.FBRSSDisplayPosts = function (oResponse) {
            var feed = new google.feeds.Feed(l10n.url.SyncapseRSS);
            feed.setNumEntries(50);
			//feed.includeHistoricalEntries();
			
          feed.load(function(result){
			  
                if (!result.error) {
                    var sHTML = '';
                    for (var i = 0; i < result.feed.entries.length; i++) {
                        var entry = result.feed.entries[i];
                        postDate = new Date(entry.publishedDate);
                        sDate =  l10n.months[postDate.getMonth()] + ' ' + postDate.getDate() + ' ' + postDate.getFullYear();
                        sHTML += '<div class="item">' +
                                     '<div class="blurb">' +
                                         '<h3>L\'Oréal Paris Canada</h3><p><a href="'+entry.link+'" target="_blank"  datas-stats="Facebook">' +
                                          '' + linkize(entry.content) + '</a></p>' +
                                     '</div>';
                            sHTML += '<p class="date">' + sDate + '</p>';
                         sHTML += '</div>';

                        
                    }
                    oContainer.find('div#content-facebook').append(sHTML);
                    box.get('ui').create('scroll.facebook', {
                        rootElm: '#content-facebook',
                        buttons: true,
                        bar: true,
                        barMinSize: 70
                    });
                }

            });

        };
		
		
        Cap_Social_Media_Center.FBDisplayPosts = function(oResponse) {
         /*   var sHTML = '',
                oItem,
                i = -1,
                oItem = oResponse.data,
                l = oItem.length,
                oDate, sDate;
            
            while(++i < l) {
                oItem = oResponse.data[i];
                oDate = getYearMonthDay(oItem.created_time);
                sDate = oDate.day + ' ' + l10n.months[oDate.month - 1] + ' ' + oDate.year;
                
                sHTML += '<div class="item">'
                    + '<div class="blurb">'
                    +  '<h3><a href="' + l10n.url.FBFanPage + oItem.from.id + '" target="_blank" title="' + l10n.accessPageFB.replace('{$user}', oItem.from.name) + '" datas-stats="Facebook">' + oItem.from.name + '</a></h3>'
                    + '<p>' + linkize(oItem.message) + '</p>'
                    + '</div>';
                
                if((oItem.type == 'photo' || oItem.type == 'link') && oItem.picture) {
                    sHTML += '<div class="media">'
                        + '<div class="thumb">'
                        + '<a href="' + oItem.link + '" target="_blank" datas-stats="Facebook"><img alt="" src="' + oItem.picture + '" height="130"></a>'
                        + '</div>'
                        + '</div>';
                } else if(oItem.type == 'video') {
                    sHTML += '<div class="media">'
                        + '<div class="thumb">'
                        + '<a href="' + oItem.link + '" target="_blank" title="' + l10n.accessVideo.replace('{$video}', oItem.name) + '" datas-stats="Facebook"><img alt="' + l10n.accessVideo.replace('{$video}', oItem.name) + '" src="' + oItem.picture + '" height="90"></a>'
                        + '</div>'
                        + '<div class="legend">'
                        + '<a href="' + oItem.link + '" target="_blank" title="' + l10n.accessVideo.replace('{$video}', oItem.name) + '" datas-stats="Facebook">' + oItem.name + '</a>'
                        + '</div>'
                        + '</div>';
                }
                sHTML += '<p class="date">' + sDate + '</p>';
                sHTML += '</div>';
            };
            
            oContainer.find('div#content-facebook').append(sHTML);
            
            box.get('ui').create('scroll.facebook', {
                rootElm: '#content-facebook',
                buttons: true,
                bar: true, // mandatory when buttons are present
                barMinSize: 70
            });
			*/
        };
        
        Cap_Social_Media_Center.YoutubeDisplayFansCount = function(oResponse) {
            oContainer.find('div#content-youtube .counter span').html(oResponse.entry.yt$statistics.subscriberCount);
        };
        
        Cap_Social_Media_Center.YoutubeDisplayFocus = function(oResponse) {
            var sHTML = '', oItem = oItem = oResponse.feed.entry[0] || null, oDate, sDate;
            
            if(oItem) {
                oDate = getYearMonthDay(oItem.published.$t);
                sDate = oDate.day + ' ' + l10n.months[oDate.month - 1] + ' ' + oDate.year;
                
                sHTML += '<h3><a href="' + oItem.link[0].href + '" target="_blank" title="' + l10n.accessVideo.replace('{$video}', oItem.title.$t) + '" datas-stats="Youtube">' + oItem.title.$t + '</a></h3>'
                    + '<ul>'
                    + '<li>' + l10n.authorFrom + '<a href="http://www.youtube.com/' + oItem.author[0].name.$t + '" target="_blank" title="' + l10n.accessPageYoutube.replace('{$user}', oItem.author[0].name.$t) + '" datas-stats="Youtube">' + oItem.author[0].name.$t + '</a></li>'
                    + '<li>' + sDate + '</li>'
                    + '<li class="special-item">' + ((oItem.yt$statistics)? oItem.yt$statistics.viewCount + l10n.viewsCountYoutube : '') + '</li>'
                    + '</ul>'
                    + '<div class="thumb">'
                    + '<a href="' + oItem.link[0].href + '" target="_blank" title="' + l10n.accessVideo.replace('{$video}', oItem.title.$t) + '" datas-stats="Youtube"><img alt="' + l10n.accessVideo.replace('{$video}', oItem.title.$t) + '" src="' + oItem.media$group.media$thumbnail[0].url + '" width="490" height="367"></a>'
                    + '</div>';
            
                oContainer.find('div#content-youtube .focus').append(sHTML);
            }
        };
        
        Cap_Social_Media_Center.YoutubeDisplayMostViewed = function(oResponse) {
            var sHTML = '',
                oItem,
                i = -1,
                oItem = oResponse.feed.entry,
                l = oItem.length,
                sTitle;
            
            sHTML += '<ul>';
            
            while(++i < l) {
                oItem = oResponse.feed.entry[i];
                sTitle = oItem.title.$t;
                sTitle = sTitle.length > 30 ? sTitle.substring(0, 30) + '…' : sTitle;
                
                sHTML += '<li>'
                    + '<a href="' + oItem.link[0].href + '" target="_blank" title="' + l10n.accessVideo.replace('{$video}', oItem.title.$t) + '" datas-stats="Youtube">'
                    + '<img alt="' + l10n.accessVideo.replace('{$video}', oItem.title.$t) + '" src="' + oItem.media$group.media$thumbnail[2].url + '" width="95" height="71">'
                    + '<span>' + sTitle + '</span>'
                    + '<em>' + oItem.yt$statistics.viewCount + l10n.viewsCountYoutube + '</em>'
                    + '</a>'
                    + '</li>';
            }
            
            sHTML += '<ul>';
            
            oContainer.find('div#content-youtube .more').append(sHTML);
            
            box.get('ui').create('scroll.youtube', {
                rootElm: '#content-youtube',
                buttons: true,
                bar: true, // mandatory when buttons are present
                barMinSize: 70
            });
			
			
			
        };
        
        var oFBScriptFansCount = box.getJDoc()[0].createElement('script'),
            /*oFBScriptPosts = box.getJDoc()[0].createElement('script'),*/
            oYoutubeDisplayFansCount = box.getJDoc()[0].createElement('script'),
            oYoutubeDisplayFocus = box.getJDoc()[0].createElement('script'),
            oYoutubeDisplayMostViewed = box.getJDoc()[0].createElement('script'),
            oTwitterFeed = box.getJDoc()[0].createElement('script');
            oGoogleFeed = box.getJDoc()[0].createElement('script');
        oFBScriptFansCount.src = l10n.url.FBScriptFansCount;
        /*oFBScriptPosts.src = l10n.url.FBScriptPosts;*/
        oYoutubeDisplayFansCount.src = l10n.url.YoutubeDisplayFansCount;
        oYoutubeDisplayFocus.src = l10n.url.YoutubeDisplayFocus;
        oYoutubeDisplayMostViewed.src = l10n.url.YoutubeDisplayMostViewed;
        oTwitterFeed.src = l10n.url.TwitterFeed;
        oGoogleFeed.src = l10n.url.GoogleFeedAPI;
        oContainer.append(oFBScriptFansCount, /*oFBScriptPosts,*/ oYoutubeDisplayFansCount, oYoutubeDisplayFocus, oYoutubeDisplayMostViewed, oTwitterFeed,oGoogleFeed);

    }
});

box.subscribe({
    name: 'load>lop:capsule.Cap_Experts_TV.home',
    handler: function(oEvt) {
        this.rootElm.find('div.item').hover(function() {
            box.dom(this).addClass('hovered');
        }, function() {
            box.dom(this).removeClass('hovered');
        });
    }
});


box.subscribe({
    name: 'load>lop:capsule.Cap_Backstage_TV.home',
    handler: function(oEvt) {
        this.rootElm.find('div.item').hover(function() {
            box.dom(this).addClass('hovered');
        }, function() {
            box.dom(this).removeClass('hovered');
        });
    }
});

box.subscribe({
    name: 'load>lop:capsule.Cap_Trailer_Video.home',
    handler: function(oEvt) {
        this.rootElm.find('div.item').hover(function() {
            box.dom(this).addClass('hovered');
        }, function() {
            box.dom(this).removeClass('hovered');
        });
    }
});
/* cap_couleur_infallible */
/*global box: false*/
box.get('ui').modifyConfig('scroll', {
    bar: '<a href="#" class="{$barCls}"><span class="start"></span><span class="end"></span></a>'
});

(function() {
    var tooltipElm,
        setTooltipHTML, manageMouseOver, manageMouseOut, manageMouseMove, isAspx = box.getWin().location.href.indexOf('.aspx') > -1;
    
    var getExt = function(sExt) {
        return isAspx ? '.aspx' : sExt;
    };
    
    setTooltipHTML = function(jElm, jCategory) {
        $('#revitalift10-shades-tooltip').html(
            '<span class="title">' + jElm.data('name') + '</span>' +
            '<span class="product ' + jCategory.attr('class') + '"><strong>' + jElm.data('type') + '</strong></span>'
        );
    };
    
    manageMouseOver = function(oView) {
        return function(oEvt) {
            if(oEvt.target.parentNode.tagName === 'A' && oEvt.target.parentNode.getAttribute('data-name')) {
                var jElm = $(oEvt.target),
                    jCategory = $(oEvt.target).parents('ul').eq(0),
                    nTop = oEvt.pageY,
                    nLeft = oEvt.pageX,
                    nWidth,
                    nHeight;
                    setTooltipHTML(jElm.parent(), jCategory);
                nWidth = tooltipElm.outerWidth();
                nHeight = tooltipElm.outerHeight();
                tooltipElm.css({ top: nTop - nHeight - 10, left: nLeft - (nWidth / 2) });
                jElm.mouseout(manageMouseOut(oView)).mousemove(manageMouseMove(oView));
            }
        };
    };
    
    manageMouseOut = function(oView) {
        return function(oEvt) {
            $(this).unbind('mouseout mousemove');
            tooltipElm.css('left', '-10000px');
        };
    };
    
    manageMouseMove = function(oView) {
        return function(oEvt) {
            var nTop = oEvt.pageY,
                nLeft = oEvt.pageX,
                nWidth = tooltipElm.outerWidth(),
                nHeight = tooltipElm.outerHeight();
            tooltipElm.css({ top: nTop - nHeight - 10, left: nLeft - (nWidth / 2) });
        };
    };
    
    box.subscribe(
        {
            name: 'load>lop:capsule.Cap_Couleur_Infallible.video',
            handler: function(oEvt) {
                var oVideo = box.get('ui').create('player.Cap_Couleur_Infallible', {
                    player: {
                        id: 'Cap_Couleur_Infallible_Flash',
                        width: 950,
                        height: 650,
                        controls: {
                            restart: false,
                            timeline: false,
                            time: false,
                            mute: false,
                            volume: false
                        }
                    },
                    
                    medias: {
                        autoplay: true,
                        path: '/_en/_ca/home/capsules/Cap_Couleur_Infallible/video/',
                        exts: [ 'mp4' ],
                        playlist: [
                            {
                                file: 'intro',
                                tag: 'Cap_Revitalift10_Intro'
                            }
                        ]
                    },
                    
                    l10n: box.get('l10n:player'),
                    
                    flash: {
                        params: { menu: 'false', allowFullScreen: 'true', allowScriptAccess: 'always', bgcolor: '#070707' }
                    }
                });
            }
        }, {
            name: 'unload>lop:capsule.Cap_Couleur_Infallible.video',
            handler: function(oEvt) {
                this.stopPlaying();
                box.get('ui').destroy('player.Cap_Couleur_Infallible');
            }
        }, {
            name: 'startplaying>lop:capsules-players.Cap_Couleur_Infallible',
            handler: function(oEvt) {
                $('#Cap_Couleur_Infallible .cap-content .main').append('<a href="/_en/_ca/home/capsules/Cap_Couleur_Infallible/benefits' + getExt('.html') + '" class="close box[target=self]">' + box.get('l10n:capsule').close + '</a>');
            }
        }, {
            name: 'beforefirstcompute>ui:scroll.products-revitalift10',
            handler: function(oEvt) {
                var jLargeSubItems = box.dom('#revitalift10-shades-listing li.large'),
                    jLongSubItems = box.dom('#revitalift10-shades-listing li.long'),
                    jItems = box.dom('#revitalift10-shades-listing ul'),
                    nShadeListingWidth = (jLargeSubItems.length * jLargeSubItems.eq(0).getSize('margin-box').width) + (jLongSubItems.length * jLongSubItems.eq(0).getSize('margin-box').width) + (jItems.length * parseInt(jItems.eq(0).css('margin-right'), 10)),
                    jListing = box.dom('#revitalift10-shades-listing');
                
                jListing.width(nShadeListingWidth).parent().width(jListing.prev().outerWidth(true) + nShadeListingWidth);
            }
        }, {
            name: 'load>lop:capsule.Cap_Couleur_Infallible.products',
            handler: function(oEvt) {
                // create a mask for popins
                box.get('ui').create('mask.products-revitalift10', {
                    html: '<div id="products-revitalift10-mask"></div>',
                    insertTarget: '#Cap_Couleur_Infallible div.main',
                    insertStyles: {opacity: 0, width: '#Cap_Couleur_Infallible div.main:content-box', height: '#Cap_Couleur_Infallible div.main:content-box'},
                    insertAnimStyles: {opacity: 0.8},
                    insertAnimDuration: 200,
                    removeAnimStyles: {opacity: 0},
                    removeAnimDuration: 150
                });
                
                // create a new popin object
                box.get('ui').create('popin.products-revitalift10', {
                    mask: 'products-revitalift10',
                    
                    insertTarget: '#Cap_Couleur_Infallible div.main',
                    insertStyles: {opacity: 0, top: '#Cap_Couleur_Infallible div.main:in-middle', 'min-top': 0, left: '#Cap_Couleur_Infallible div.main:in-middle', 'min-left': 0},
                    insertAnimStyles: {opacity: 1},
                    insertAnimDuration: 200,
                    removeAnimStyles: {opacity: 0},
                    removeAnimDuration: 200,
                    
                    openTest: function(oElm) {
                        return (oElm.tagName === 'A' && $(oElm).getBoxDatas('target') === 'products-revitalift10');
                    },
                    closeTest: function(oElm) {
                        return (oElm.tagName === 'A' && $(oElm).getBoxDatas('target') === 'products-revitalift10-close');
                    }
                });
                
                box.get('ui:popin.products-revitalift10').addToCache('#products-revitalift10');
                
                box.get('ui').create('scroll.products-revitalift10', {
                    rootElm: '#Cap_Couleur_Infallible div.scroll',
                    buttons: true,
                    bar: true,
                    horizontal: true,
                    barMinSize: 70
                });
                
                tooltipElm = $('<div id="revitalift10-shades-tooltip" style="position:absolute; left:-10000px;"></div>').appendTo('body');
                $('#revitalift10-shades-listing').mouseover(manageMouseOver(this));
            }
        }, {
            name: 'unload>lop:capsule.Cap_Couleur_Infallible.products',
            handler: function() {
                tooltipElm.remove();
            }
        }, {
            name: 'load>lop:capsule.Cap_Couleur_Infallible.article',
            handler: function(oEvt) {
                box.get('ui').create('scroll.article-revitalift10', {
                    rootElm: '#Cap_Couleur_Infallible div.scroll',
                    buttons: true,
                    bar: true,
                    barMinSize: 70
                });
            }
        }, {
            name: 'beforeopen>ui:popin.products-revitalift10',
            handler: function(oEvt) {
                oEvt.source.datas.hash = '#' + oEvt.source.id;
            }
        }, {
            name: 'addtodom>ui:popin.products-revitalift10',
            handler: function(oEvt) {
                var jElm = oEvt.source.element,
                    jSource = oEvt.source,
                    jOpener = oEvt.source.datas.opener,
                    oDatasOpener = jOpener.data();
                jElm.addClass(jOpener.parents('ul').eq(0).attr('class')).addClass(jOpener.parents('li').eq(0).attr('class'));
                jElm.find('h2').html(oDatasOpener.name);
                jElm.find('p.product strong').html(oDatasOpener.type);
                jElm.find('div.visual img').attr('src', jOpener.find('img').attr('src').replace('230x250', '220x239').replace('165x424', '130x324'));
                jElm.find('a.btn').eq(0).attr('href', oEvt.source.datas.url);
            }
        }
    );
}());
/* end cap_couleur_infallible */

