﻿/*
**********************************************************************************
* Global setups
* GF config and set global ajax variables
**********************************************************************************
*/
$.ajaxSetup({  
        type: "POST",
        dataType: 'json',
        contentType: 'application/json'
    });

// GF configuration
var GF = {};

//IE<9 Testing
var isIE7 = ($("html").attr("id") == "ie7");
var isIE8 = ($("html").attr("id") == "ie8");

/*
**********************************************************************************
*  Compare Array
*  [1,2,3,4].diff([1,2]);  ==>  3,4
**********************************************************************************
*/
Array.prototype.diff = function(a) {
return this.filter(function(i) { return !(a.indexOf(i) > -1); });
};


/*
**********************************************************************************
*  COOKIE FUNCTIONS
*  likes count cookie
**********************************************************************************
*/
function setCookie(c_name, value, exdays) {
    var exdate = new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
    document.cookie = c_name + "=" + c_value;
};
function getCookie(c_name) {
    var i, x, y, ARRcookies = document.cookie.split(";");
    for (i = 0; i < ARRcookies.length; i++) {
        x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
        y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
        x = x.replace(/^\s+|\s+$/g, "");
        if (x == c_name) {
            return unescape(y);
        }
    }
};
function checkCookie() {
    var username = getCookie("username");
    if (username != null && username != "") {
        alert("Welcome again " + username);
    }
    else {
        username = prompt("Please enter your name:", "");
        if (username != null && username != "") {
            setCookie("username", username, 365);
        }
    }
};


/*
**********************************************************************************
*  JSON.stringify
*  implement JSON.stringify serialization
**********************************************************************************
*/
JSON.stringify = JSON.stringify || function(obj) {
        var t = typeof (obj);
        if (t != "object" || obj === null) {
            // simple data type
            if (t == "string") obj = '"' + obj + '"';
            return String(obj);
        }
        else {
            // recurse array or object
            var n, v, json = [], arr = (obj && obj.constructor == Array);
            for (n in obj) {
                v = obj[n]; t = typeof (v);
                if (t == "string") v = '"' + v + '"';
                else if (t == "object" && v !== null) v = JSON.stringify(v);
                json.push((arr ? "" : '"' + n + '":') + String(v));
            }
            return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");
        }
    };

                        
/*
**********************************************************************************
*  GF.overFlash
*  FLASH MOUSEOVER CALLS WILL BE USED FOR GAME PLAYED FUNCTION
**********************************************************************************
*/
GF.OverFlash = function(fl) {
    var thisFlash = $('#' + fl);
    var div = thisFlash.parent();
    var divHeight = thisFlash.height() + 1 + 'px';
    div.bind('mouseover', function() {
        $(this).css('position','relative').append('<div class="test" style="position:absolute;top:0;left:0;height:100%;width:100%;" />').addClass('test');
        $('div.test',this).css('backgroundColor', '#fc0').fadeOut(1500);
        $(this).unbind('mouseover');
    });
};


/*
**********************************************************************************
*  GF.IEOverlay
*  Fix IE7 overlay bug
**********************************************************************************
*/
GF.IEOverlay = function (fl) {
    if (isIE7) {
        var header = $('#Header .tabWrap');
        $('#exposeMask').after(header);
        $('#yourStuff #awardsContainer').css({ 'margin-top': '150px' });
    }
};


/*
**********************************************************************************
*  GF.TooltipInit
*  flowplayer tooltip init
**********************************************************************************
*/
GF.TooltipInit = function (trigger, tip, position, top, left, follow) {
    if (typeof follow == "undefined") {
        follow = false;
    }

    $("#" + trigger).tooltip({
        tip: '#' + tip,
        position: position,
        offset: [top, left],
        relative: true
    });

    if (follow) {

        $("#" + trigger).tooltip({
            tip: '#' + tip,
            position: position,
            offset: [top, left],
            relative: true
        });

        $('#' + tip).each(function () {  //  Sets Position of Images when text it too long
            $(this).show();
            var offHeight = $(this).find('.description').height();
            $(this).hide();
            if (offHeight > 90)$(this).find('.badge-hover-image').addClass('adjTop');
        });

        $('#' + tip + " .badge-hover-image").mousemove(function (evt) {
            $(this).parent().children(".badge-info").css({
                left: (evt.pageX - $(this).offset().left - ($(this).width() / 2)),
                top: (evt.pageY - $(this).offset().top - ($(this).height() / 2))
            });
        });

        $('#' + tip + " .badge-hover-image").mouseleave(function (evt) {
            $('#' + tip).hide();
        });
    }
};


/*
**********************************************************************************
*  GF.CarouselInit
*  horizontal carousel init
**********************************************************************************
*/
GF.CarouselInit = function (id, next, item) {
    var itemsnum = item;
    if ( $("#" + id + " .item").length <= item) {
        $("#" + id).parent().children('.next').addClass('disabled');
    }

    $('#' + id).scrollable({
        itemsPerFrame: item,
        onBeforeSeek: function (event, index) {
            if (this.getIndex() >= this.getSize() - itemsnum) {

                if (index > this.getIndex()) {
                    return false; //disable scrollable api
                }
            }
        },
        onSeek: function (event, index) {
            if (this.getIndex() >= this.getSize() - itemsnum) {
                $('.' + next).addClass("disabled"); //hide 'next' button
            }
        }
    });
}


/*
**********************************************************************************
*  GF.SetBGImgHeight
*  set backgorund images
**********************************************************************************
*/
GF.SetBGImgHeight = function () {
    var ContainerHeight = $("#ContentContainer").height();
    if (ContainerHeight >= 912) {
        var dif = ContainerHeight - 912;
        if (dif > 100) {
            if (isIE7) {
                //$('#WrapTop').css({ 'margin-bottom': '0' });
                //$('#WrapBottom').css({ 'z-index': '2', 'height': '659px' });
            }
            else {
                $('#WrapTop').css({ 'margin-bottom': '-659px' });
                $('#WrapBottom').css({ 'height': '659px' });
            }
            
        }
    }
};


/*
**********************************************************************************
*  GF.HeaderSlide
*  show hide header animation
**********************************************************************************
*/
GF.HeaderAnimation = function (trigger) {
    $('.' + trigger).click(function (e) {
        GF.headerSlide($(this).text());
    });
};

GF.headerSlide = function (t) {
    if (t == 'Hide') {
        GF.headerClose();
    } else {
        headerFlash('expand');
     //   $.delCookie('hideHeader');
    }
};

GF.headerClose = function () {
    $(".showHide").show();
    $('.headerBanner').animate({ 'height': '100px' }, 350);
    //$.setCookie('hideHeader', 'true', { duration: 10 });
    $('.headerBanner object#flashHeader').remove();
    $('.headerBanner').append('<div id="flashHeader"></div>');
};

GF.headerExpand = function () {
    $(".showHide").hide();
    $('.headerBanner').animate({ 'height': '305px' }, 350);
};

/*
**********************************************************************************
*  UserStatus - NEEDS MAJOR CLEANUP
*  log-in, join-now, forgot-password forms and your stuff
**********************************************************************************
*/
GF.tabs = {};
GF.tabs.init = function () {
    GF.tabs = {
        "mask" : $('#exposeMask'),
        "tabWrap": $('.tabWrap'),
        "signIn": $('#signIn'),
        "joinNow": $('#joinNow'),
        "yourStuff": $('#yourStuff'),
        "signInClone": "",
        "defaultHTML": '<div id="tabContent" class="tabLoading" />'

    };
};

GF.closeTab = function () {
   
    GF.tabs.tabWrap.slideUp("normal", function () {
        if (GF.tabs.signInClone != "") {
            $('.toRemove').remove();
        }
        GF.tabs.tabWrap.css({ 'height': '0px', 'top': '-43px', 'right': '137px' });
        GF.exposeMask(true);
        if (GF.tabs.signIn.hasClass('openSignIn'))
            GF.tabs.signIn.removeClass('openSignIn');

        GF.tabs.tabWrap.html(GF.tabs.defaultHTML);

    });
}; 

GF.forgotPassword = function(tabUrl) {
    GF.tabs.tabWrap.html(GF.tabs.defaultHTML);
    GF.tabs.tabWrap.animate({ 'height': '260px', 'width': '500px' }, { duration: 200 }, function () {
        $('.tabWrap div').unbind('load'); 
    });
    GF.tabs.tabWrap.load(tabUrl, function(e) { });
};

GF.logInFromOpenTab = function (tabUrl) {
    if (GF.tabs.signIn.hasClass('openSignIn')) { GF.closeTab(); }
    else {

        if (isIE7) {
            GF.tabs.signInClone = GF.tabs.signIn.clone(true);
            GF.tabs.signInClone.prependTo('body');
            var siginPos = GF.positionTab(GF.tabs.signInClone, GF.tabs.signIn);
            GF.tabs.signInClone.addClass("toRemove");
            GF.tabs.signInClone.css({
                'position': 'absolute',
                'top': '20px',
                'right': siginPos.right + "px",
                'z-index': '9999',
                'text-transform': 'uppercase',
                'color': '#A9480E',
                'font': 'bold 11px Arial',
                'padding': '5px 3px',
                'background-color': '#fff'
            });
        }

        var tabWrapPos = GF.positionTab(GF.tabs.tabWrap, GF.tabs.signIn);
        GF.tabs.signIn.removeClass('openSignIn').addClass('openSignIn');
        GF.tabs.tabWrap.html(GF.tabs.defaultHTML);
        GF.tabs.tabWrap.animate({ 'height': '170px', 'width': '500px', 'top': '43px', 'right': tabWrapPos.right }, { duration: 200 }, function () {
            GF.tabs.tabWrap.children('div').unbind('load'); 
        });
        GF.tabs.tabWrap.load(tabUrl, function(e) { });
    }
};

GF.joinFromOpenTab = function (tabUrl) {

    if (GF.tabs.signInClone != "") {
        $('.toRemove').remove();
    }

    var tabWrapPos = GF.positionTab(GF.tabs.tabWrap, GF.tabs.yourStuff);
    GF.tabs.signIn.removeClass('openSignIn');
    GF.tabs.tabWrap.html(GF.tabs.defaultHTM);
    GF.tabs.tabWrap.animate({ 'height': '765px', 'width': '700px', 'top': '-10px', 'right': tabWrapPos.right }, { duration: 200 }, function () {
        $('.tabWrap div').unbind('load'); 
    });
    GF.tabs.tabWrap.load(tabUrl, function (e) { });
};

GF.openSignInTab = function (tabUrl) {
    if (GF.tabs.tabWrap.css('height') == "170px" || GF.tabs.tabWrap.css('height') == "300px") { GF.closeTab(); }
    else {
        if (isIE7) {
            GF.tabs.signInClone = GF.tabs.signIn.clone(true);
            GF.tabs.signInClone.prependTo('body');
            var siginPos = GF.positionTab(GF.tabs.signInClone, GF.tabs.signIn);
            GF.tabs.signInClone.addClass("toRemove");
            GF.tabs.signInClone.css({
                'position': 'absolute',
                'top': '20px',
                'right': siginPos.right + "px",
                'z-index': '9999',
                'text-transform': 'uppercase',
                'color': '#A9480E',
                'font': 'bold 11px Arial',
                'padding': '5px 3px',
                'background-color': '#fff'
            });
        }
        var tabWrapPos = GF.positionTab(GF.tabs.tabWrap, GF.tabs.signIn);
        GF.tabs.signIn.removeClass('openSignIn');
        GF.exposeMask();
        GF.tabs.tabWrap.css({ 'height': '170px', 'width': '500px', 'top': '43px', 'right': tabWrapPos.right + "px" });
        GF.tabs.tabWrap.slideDown("normal", function () { GF.tabs.tabWrap.children('div').unbind('load'); });
        GF.tabs.signIn.addClass('openSignIn');
        GF.tabs.tabWrap.load(tabUrl, function (e) { });
    }
};

GF.positionTab = function (objToPos, objPosTo) {
    
    //Checks if the parent is the body
    var parentIsBody = objToPos.parent().is("body");

    //Gets objects parent width depending on it's position on the page
    var objToPosParentWidth = (parentIsBody ? $("#WrapTop").outerWidth() : objToPos.parent().outerWidth());

    //Gets left and right position of element
    var objPosToPos = {
        "right": (parentIsBody ?
                    ($(window).width() - (objPosTo.offset().left + objPosTo.outerWidth())) :
                    (objToPosParentWidth - (objPosTo.position().left + objPosTo.outerWidth()))
                 ),
        "left": (parentIsBody ?
                    ($(window).width() - objPosTo.offset().left) :
                    (objToPosParentWidth - objPosTo.position().left)
                 )
    };

    
    return objPosToPos;
};

GF.exposeMask = function (close) {
    if (close)
        GF.tabs.mask.animate({ 'height': '0px', 'width': '0px' }, { duration: 10 }, function () { });
    else{
        GF.tabs.mask.animate({ 'height': $(document).height(), 'width': '100%' }, { duration: 10 }, function () { });
    }
};

GF.openJoinTab = function (tabUrl) {
    var tabWrapPos = GF.positionTab(GF.tabs.tabWrap, GF.tabs.yourStuff);
    GF.exposeMask();
    GF.tabs.joinNow.removeClass('openSignIn');
    GF.tabs.tabWrap.css({ "right": tabWrapPos.right + 'px', "top": "-10px", 'height': '765px', 'width': '700px' });
    GF.tabs.tabWrap.slideDown("normal", function () {
        GF.tabs.tabWrap.children('div').unbind('load');
    });
    GF.tabs.tabWrap.load(tabUrl, function(e) { });
};

GF.yourStuff = function (tabUrl) {
    if (!LoggedOn) { GF.openSignInTab('/services/UI/login.aspx'); }
    else {
        var tabWrapPos = GF.positionTab(GF.tabs.tabWrap, GF.tabs.yourStuff);
        GF.exposeMask();
        GF.tabs.yourStuff.removeClass('openSignIn');
        GF.tabs.tabWrap.css({ "right": tabWrapPos.right + 'px', "top": "-10px", 'height': '765px', 'width': '700px' });
        GF.tabs.tabWrap.slideDown("normal", function () {
            GF.tabs.tabWrap.children('div').unbind('load');
        });
        GF.tabs.tabWrap.load(tabUrl, function (e) {
            GF.omniture.myStuff();
            $('#user-name-greetingWelcome').html(UserName + "!");
            $('.welcome-message').css('display', 'block');
        });
    }
};

GF.closeBkgd = function () { GF.closeTab(); }

GF.yourStuffTabs = function () {
    $('div#yourStuff div#awardsContainer ul.nav li').click(function () {
        if ($(this).hasClass('openSignInTabs')) return false;
        var thisTab = $(this).attr('id');
        $('div#yourStuff div#awardsContainer ul.nav li').removeClass('openSignInTabs');
        $(this).addClass('openSignInTabs');
        var badgeMessage = "Click the tabs to check out your stuff, customize it, or add more!";
        switch (thisTab) {
            case 'badges':
                var badgeMessage = "View all the badges you have earned and see which badges you still need.";
                GF.omniture.MStabs('Badges');
                break;
            case 'goldfish':
                var badgeMessage = "Create your very own character and change it any time you like.";
                GF.omniture.MStabs('Character');
                break;
            case 'favorites':
                var badgeMessage = "See all of your favorite games, characters and videos.";
                GF.omniture.MStabs('Favorites');
                break;
            case 'downloads':
                var badgeMessage = "Find cool downloads, wallpapers and chat icons featuring FINN &amp; Friends.";
                GF.omniture.MStabs('Downloads');
                break;
            default:
                break;
        }
        $(".welcome-message .badge-message").html(badgeMessage);
        $('div#yourStuff div#awardsContainer div.awards').css('display', 'none');
        $('div#yourStuff div#awardsContainer div.' + thisTab).css('display', 'block');
    });
};

GF.openPhoto = function (photo) {

    $boxcontent = $("#box-content");
    $box = $('#box-overlay');

    GF.exposeMask();
    //close tab on click anywhere on box-overlay
    $('#exposeMask,#box-overlay .closeBox').click(function (e) { $box.hide(); });
    $box.click(function (e) {
        GF.closeBkgd();
        $(this).hide();
        return false;
    });
    $(window).resize(function () {
        $box = $('#box-overlay');
        var boxtop = (($(window).height() - $box.height()) / 2 + $(document).scrollTop());
        var boxleft = (($(document).width() - $box.width()) / 2 + $(document).scrollLeft());
        $box.css({ "top": boxtop + "px", "left": boxleft + "px" });
        
    });
    var boxtop = (($(window).height() - $box.height()) / 2 + $(document).scrollTop());
    var boxleft = (($(document).width() - $box.width()) / 2 + $(document).scrollLeft());
    $box.css({ "top": boxtop + "px", "left": boxleft + "px" });
    $box.fadeIn();
    $boxcontent.html('<img src="' + photo + '" alt="" />');
}

/*
**********************************************************************************
*  Site badging
*  
**********************************************************************************
*/

GF.Badging = function (config) {
    this.config = config
    this.init()
};

GF.Badging.prototype = {
    init: function () {
        // cache dom elements
        this.$badges = $('.badge', $('#pageBadges'))
        if (this.$badges.length > 0) {
            //get list of badge names
            this.badge_names = ""
            this.$badges.each($.proxy(function (e, obj) {
                this.badge_names += $(obj).attr('name')
                if ((e + 1) != this.$badges.length) {
                    this.badge_names += ","
                }
            }, this))

            //create easier lookup for badges
            this.badge_names_array = this.badge_names.split(',')
            this.badge_lookup = {};

            for (var b = 0; b < this.badge_names_array.length; b++) {
                this.badge_lookup[this.badge_names_array[b]] = this.badge_names_array[b];
            }
            this.hasBadges = true
        } else {
            this.hasBadges = false
        }


    },

    _globalTemplate: '<div id="award" class="global" style="display:none;"><div id="awardClose"></div>' +
                        '<div id="awardInner" style="background-image: url({{smallImage}})">' +
                            '<h3>' +
                              '<img src="/images/gamesDetail/awarded.gif"/>' +
                            '</h3>' +
                            '<h4 class="badge_name">' +
                              '{{name}}' +
                            '</h4>' +
                            '<p class="badge_descrip">' +
                              '{{descrip}}' +
                            '</p>' +
                        '</div>' +
                    '</div>',

    _detailsTemplate: '<div id="award" style="display:none;">' +
                        '<div id="awardInner" style="">' +
                        '<img src="{{largeImage}}" height="50" width="50"/>' +
                            '<h4 class="badge_name">' +
                              '{{name}} <span>badge awarded! great job!</span>' +
                            '</h4>' +
                        '</div>' +
                       '</div>',

    showAwardedBadges: function (badgeArray, badgeType, callback) {

        thisObj = this
        this.badgingTest = badgeArray
        this.badgeType = badgeType
        this.callbackFunc = callback;

        if (this.badgingTest.length > 0) {
            if ($('#award').length > 0) {
                $('#award').fadeOut(500, $.proxy(function () {
                    $('#award').remove()
                    if (this.badgingTest.length != 0) {
                        this.createBadge()
                    }
                }, this))
            } else {
                this.createBadge()
            }
        } else if ($('#award').length > 0) {
            $('#award').fadeOut(500, $.proxy(function () {
                if (Object.prototype.toString.call(this.callbackFunc) == "[object Function]") {
                    this.callbackFunc.call(this)
                    this.callbackFunc = ''
                }

            }, this))
        }
    },

    createBadge: function () {
        thisObj = this

        if ($('body').hasClass('flash-detail')) {
            awardTemplate = this._detailsTemplate
            currentBadges = pageBadges
            awardLocation = '#ContentContainer'
        } else {
            awardTemplate = this._globalTemplate
            currentBadges = pageBadges
            awardLocation = 'body'
        }
        if (currentBadges.badges[this.badgingTest[0]] != undefined) {
            $(awardLocation).prepend($.mustache(awardTemplate, currentBadges.badges[this.badgingTest[0]]))
            if (!$('body').hasClass('flash-detail')) {
                $('#award').css({
                    'top': function () {
                        topPos = ($(window).height() - $('#award').height() - 10);
                        return topPos
                    }
                })
            }
            $('#award').fadeIn(500)
            $('#awardClose').click(function () { $('#award').fadeOut(500, function () { $('#award').remove() }) })


            GF.omniture.badgeAward(this.badgingTest[0]);
            this.badgingTest.splice(0, 1)
            setTimeout(function () { thisObj.showAwardedBadges(thisObj.badgingTest, thisObj.badgeType, thisObj.callbackFunc); }, 8000)
        } else {
            this.badgingTest.splice(0, 1)
            setTimeout(function () { thisObj.showAwardedBadges(thisObj.badgingTest, thisObj.badgeType, thisObj.callbackFunc); }, 0)
        }

    }

}

/*
**********************************************************************************
*  Game & video chain engaigment main
*  
**********************************************************************************
*/

GF.ChainEngagement = function (config) {
    this.config = config

    this.init()
};

GF.ChainEngagement.prototype = {
    init: function () {
        this.$notificationArea = $('div#notificationArea');
        this.$notificationAreaContent = $('div#notificationAreaContent');
        this.$chainContainer = $('#chainContainer');
        this.$page_badges = $('.badge', $('#pageBadges'));
        this.$aquired_wrapper = $('#aquiredBadges');
        this.$page_chain = $('.Chain', $('#ChainEngagement'));

        //cache functions
        this.bLoadNotiArea = $.proxy(this.loadNotiArea, this)
        this.bcloseNotifcationArea = $.proxy(this.closeNotifcationArea, this)
        this.bshowChainEngagement = $.proxy(this.showChainEngagement, this)
        this.awarded_badges_count = 0
        this.timeToCloseNoti = 12000
        this.speedToCloseNoti = 500

        // cache dom elements
        this.$badges = $('.badge', $('#pageBadges'))

        //get list of badge names
        this.badge_names = ""
        this.$badges.each($.proxy(function (e, obj) {
            this.badge_names += $(obj).attr('name')
            if ((e + 1) != this.$badges.length) {
                this.badge_names += ","
            }
        }, this))

        //create easier lookup for badges
        this.badge_names_array = this.badge_names.split(',')
        this.badge_lookup = {};

        for (var b = 0; b < this.badge_names_array.length; b++) {
            this.badge_lookup[this.badge_names_array[b]] = this.badge_names_array[b];
        }

        this.setCloseLinks()
        this.setBackUrl()
        this.marginSet = false



        this.containerMargin()
        $(window).resize($.proxy(function () {
            this.containerMargin()
        }, this));
        this.bindHtmlChanged()
    },

    bindHtmlChanged: function () {
        this.$notificationArea.bind("html_changed", function () {
            if ($(document).height() > $(window).height()) {
                $('html, body').animate({ scrollTop: $(document).height() }, 1000);
            }
        })
    },

    containerMargin: function () {

        this.offset = $('#Wrapper').offset()
        this.offsetLeft = this.offset.left
        this.windowWidth = $(window).width()

        if (parseInt(this.offsetLeft) < 165 && !this.marginSet) {
            $('#Wrapper').css('margin', '0 0 0 165px')
            this.marginSet = true
        } else if (this.marginSet && this.windowWidth >= 1275) {
            $('#Wrapper').css('margin', 'auto')
            this.marginSet = false
        }
    },

    setToolTips: function () {
        thisObj = this
        $(".badge", this.$notificationAreaContent).each(
            function (e) {
                var id = $(this).attr('id');

                if ((e + 1) % 6 == 0 || (e + 1) % 7 == 0) {
                    $('#' + id + '-tooltip').addClass('tooltipEnd');
                    $('#' + id + '-tooltip').addClass('toolLeft');
                    GF.TooltipInit(id, id + '-tooltip', 'top left', 150, 181, true);
                } else {
                    GF.TooltipInit(id, id + '-tooltip', 'top left', 150, 380, true);
                }
                $(this).bind('mouseenter', $.proxy(function () {
                    thisObj.cancelTimoutCloseNotifcationArea()
                    clearTimeout(showEngagementTimeout)
                }, this))
            }
        );
    },

    setNotiBinds: function () {
        this.$notificationArea.bind({
            mouseenter: $.proxy(function () {
                this.cancelTimoutCloseNotifcationArea()
            }, this),
            mouseleave: $.proxy(function () {
                this.timoutCloseNotifcationArea()
            }, this)
        })
    },

    unsetNotiBinds: function () {
        this.$notificationArea.unbind('mouseenter')
        this.$notificationArea.unbind('mouseleave')
    },

    closeNotifcationArea: function () {
        this.$notificationArea.animate({ 'height': 0 }, this.speedToCloseNoti);
        this.$notificationArea.unbind('mouseleave')
    },

    timoutCloseNotifcationArea: function (timer) {
        this.cancelTimoutCloseNotifcationArea()
        thisObj = this
        timerTime = timer != undefined ? timer : this.timeToCloseNoti;
        this.closeTimeout = setTimeout(function () { thisObj.bcloseNotifcationArea(); }, timerTime)
    },

    cancelTimoutCloseNotifcationArea: function () {
        clearTimeout(this.closeTimeout)
    },

    setBackUrl: function () {
        $('#backHome').attr('href', function () {
            if ($.readCookie("detailsBack") != undefined) {
                return $.readCookie("detailsBack")
            } else {
                return "/"
            }
        })
    },

    setCloseLinks: function () {
        $('a.notif_close', this.$notificationArea).bind('click', $.proxy(function (e) {
            this.bcloseNotifcationArea()
            return false
        }, this));
    },

    loadNotiArea: function (tabUrl) {
        this.$notificationAreaContent.load(tabUrl, $.proxy(function () {
            var hght = null;
            while (hght == null) {
                hght = this.$notificationAreaContent.find('div').outerHeight(true);
            }
            hght = hght + 50 + 'px';

            this.$notificationArea.animate({ 'height': hght }, 1000, $.proxy(function () {

                $('a', $('div#notificationAreaContent .btns')).each($.proxy(function (e, link) {
                    if ($(link).hasClass("cancelPassword") || $(link).attr("id") == "closeJoinFormBtn") {
                        if ($(link).hasClass("cancelPassword")) {
                            $(link).unbind('click')
                        }
                        $(link).attr('onclick', '').addClass('close').bind('click', $.proxy(function (e) {
                            this.bcloseNotifcationArea()
                            return false
                        }, this));
                    } else if ($(link).hasClass("btn-signin") || $(link).attr("id") == 'signIn' || $(link).attr("id") == 'joinNowSubmit') {
                        $(link).bind('click', $.proxy(function (e) {
                            if (UserName != '') {
                                this.bcloseNotifcationArea()
                            }
                            return false
                        }, this));
                    } else if ($(link).attr("id") == "recoverPassword") {
                        $(link).unbind('click')
                        $(link).bind('click', function () {
                            recoverPassword(); return false;
                        });
                    } else if ($(link).attr('onclick') != "authenticate()") {
                        if ($(link).attr('id') == 'joinFromOpenTab') {
                            $(link).unbind('click')
                        }
                        $(link).attr('onclick', '').addClass('notification').bind('click', $.proxy(function (e) {
                            this.bLoadNotiArea(e.currentTarget.href)
                            return false
                        }, this));
                    } else {
                        $(link).addClass('notification').bind('click', $.proxy(function (e) {
                            this.bLoadNotiArea(e.currentTarget.href)
                            return false
                        }, this));
                    }
                }, this));

                this.$notificationArea.unbind('load');
                this.$notificationArea.trigger("html_changed")
            }, this));

        }, this));

    },

    badging: function (showFull, pageType) {
        this.unsetNotiBinds()
        thisObj = this
        show = showFull == false ? false : true;
        page = pageType == undefined ? "" : pageType;

        if (this.awarded_badges[0] != "" && this.awarded_badges.length > 0) {

            if (this.awarded_badges[0] != "") {
                Badging.showAwardedBadges(this.awarded_badges, 'details', $.proxy(function () {
                    this.showRemainingEngagement(show, page)
                }, this))
            }

        }
    },
    showRemainingEngagement: function (showFull, pageType) {

        show = showFull == false ? false : true;
        page = pageType == undefined ? "" : pageType;
        if (page == "video") {
            this.showRemainingBadges(true)
        } else {
            // no badges were awarded or we ran out of awarded badges
            if (this.plays <= 3 && show) {
                this.showRemainingBadges()
            } else if (this.plays >= 4 && this.plays <= 10 && show) {
                this.showChainEngagement()
            } else {
                this.setNotiBinds()
                this.timoutCloseNotifcationArea(500)
            }
        }
    },

    clearGrabAcquiredBadgesTimeout: function () {
        clearTimeout(this.acquiredBadgesTimeout)
    },

    grabAcquiredBadgesTimeout: function () {
        thisObj = this
        this.acquiredBadgesTimeout = setTimeout(function () { thisObj.grabAcquiredBadges(); }, this.timeToCloseNoti + 500)
    },

    clearChainTimeout: function () {
        clearTimeout(this.acquiredChainTimeout)
    },

    grabChainTimeout: function () {
        thisObj = this
        this.acquiredChainTimeout = setTimeout(function () { thisObj.grabChain(); }, this.timeToCloseNoti + 500)
    },

    grabChain: function () {
        this.$notificationAreaContent.children().appendTo($('#ChainEngagement'))
    },
    grabAcquiredBadges: function () {
        this.$chainContainer.append(this.$aquired_wrapper)
        $('#earned', this.$aquired_wrapper).remove()
    },

    showRemainingBadges: function (showEngagement) {
        this.unsetNotiBinds()
        /*
        loop through user's acquired badges and compare to page badges
        apply acquired css name to badges that have been acquired already
        */
        thisObj = this;
        this.awarded_badges_count = 0
        user_badges = this.response_data.BadgeAwards.total;
        this.user_badges = user_badges.split(',')
        //this.badge_lookup
        $('#earned', this.$aquired_wrapper).remove()
        for (i = 0; i < this.user_badges.length; i++) {
            if (typeof this.badge_lookup[this.user_badges[i]] != 'undefined') {
                $('[name=' + this.user_badges[i] + ']', $('#aquiredBadges')).removeClass('unacquired').removeClass('first').addClass('acquired')
                this.awarded_badges_count++
            }
        }
        if (this.$notificationArea.css('height') == "0px") {
            this.$notificationAreaContent.html('')
            this.$aquired_wrapper.prepend("<p id='earned'>You've earned " + this.awarded_badges_count + " of " + this.badge_names_array.length + " badges</p>")
            this.$aquired_wrapper.children('div').first().addClass('first')
            this.$aquired_wrapper.clone().appendTo(this.$notificationAreaContent)
            var hght = 0;
            while (hght == 0) {
                hght = this.$notificationAreaContent.find('div').outerHeight(true);
            }
            hght = hght + 50 + 'px';
            this.$notificationArea.animate({ 'height': hght }, 1000, $.proxy(function () {
                this.setToolTips()
                this.$notificationAreaContent.children().fadeIn(200)
                this.$notificationArea.trigger("html_changed")
            }, this))
        } else {
            this.$notificationAreaContent.children().fadeOut(1000, $.proxy(function () {
                this.$notificationAreaContent.html('')
                this.$aquired_wrapper.prepend("<p id='earned'>You've earned " + this.awarded_badges_count + " of " + this.badge_names_array.length + " badges</p>")
                this.$aquired_wrapper.children('div').first().addClass('first')
                this.$aquired_wrapper.clone().appendTo(this.$notificationAreaContent)
                var hght = 0;
                while (hght == 0) {
                    hght = this.$notificationAreaContent.find('div').outerHeight(true);
                }
                hght = hght + 50 + 'px';
                this.$notificationArea.animate({ 'height': hght }, 1000, $.proxy(function () {
                    this.setToolTips()
                    this.$notificationAreaContent.children().fadeIn(200)
                    this.$notificationArea.trigger("html_changed")
                }, this))
            }, this))
        }

        if (showEngagement) {
            showEngagementTimeout = setTimeout(function () { thisObj.bshowChainEngagement(); }, this.timeToCloseNoti);
            this.$notificationArea.mouseleave($.proxy(function () {
                clearTimeout(showEngagementTimeout)
                showEngagementTimeout = setTimeout(function () { thisObj.bshowChainEngagement(); }, this.timeToCloseNoti);
            }, this))
            this.$notificationArea.mouseenter($.proxy(function () {
                clearTimeout(showEngagementTimeout)
            }, this))

        } else {
            showEngagementTimeout = setTimeout('', this.timeToCloseNoti);
            this.setNotiBinds()
            this.timoutCloseNotifcationArea()
        }
    },

    showChainEngagement: function () {
        this.unsetNotiBinds()
        thisObj = this
        if (this.$page_chain.length > 0) {
            if (this.$notificationArea.css('height') == "0px") {
                this.$notificationAreaContent.html('')
                $(this.$page_chain[0]).clone().appendTo(this.$notificationAreaContent)
                var hght = 0;

                while (hght == 0) {
                    hght = this.$notificationAreaContent.find('div').outerHeight(true);
                }
                hght = hght + 50 + 'px';

                this.$notificationArea.animate({ 'height': hght }, 1000, $.proxy(function () {
                    this.$notificationAreaContent.children().fadeIn(500)
                    this.$notificationArea.trigger("html_changed")
                }, this))
            } else {
                this.$notificationAreaContent.children().fadeOut(1000, $.proxy(function () {
                    this.$notificationAreaContent.html('')
                    $(this.$page_chain[0]).clone().appendTo(this.$notificationAreaContent)
                    var hght = 0;

                    while (hght == 0) {
                        hght = this.$notificationAreaContent.find('div').outerHeight(true);
                    }
                    hght = hght + 50 + 'px';
                    this.$notificationArea.animate({ 'height': hght }, 1000, $.proxy(function () {
                        this.$notificationAreaContent.children().fadeIn(500)
                        this.$notificationArea.trigger("html_changed")
                    }, this))
                }, this))

            }

            this.$page_chain.push(this.$page_chain[0])
            this.$page_chain.splice(0, 1)
            this.setNotiBinds()
            this.timoutCloseNotifcationArea()
        } else {
            this.timoutCloseNotifcationArea()
        }
    },

    displayProfileByName: function (incoming_name) {
        this.unsetNotiBinds()
        this.$notificationAreaContent.html('')
        href = "/services/UI/UserProfile.aspx?username=" + incoming_name
        this.bLoadNotiArea(href)
        $(".badge", $('#gameBadges')).each(
            function () {
                var id = $(this).attr('id');
                GF.TooltipInit(id, id + '-tooltip', 'top left', 150, 380);
                $(this).bind('mouseenter', $.proxy(function () {
                    this.cancelTimoutCloseNotifcationArea()
                }, this))
            }
        );
        this.cancelTimoutCloseNotifcationArea()
    }
}

/*
**********************************************************************************
*  Game
*  game landing and game detail
**********************************************************************************
*/

Game = {}

Game.Details = function (config) {
    this.config = config

    this.init()
};

Game.Details.prototype = {
    init: function () {
        //cache elements
        this.$contentContainer = $('#ContentContainer');
        this.$white_modal = $('#whiteModal');
        this.$notifications = $('#container').find('a.notification');

        this.$btnok = $('.btn-ok');

        //*******chain engagement*******//
        this.detail_type = "game";
        this.userName = GoldFish.Config.UserName;
        this.loggedOn = GoldFish.Config.LoggedOn;
        this.plays = 0


        //time to handle engagement
        this.engagement = new GF.ChainEngagement()

        this.bLoadNotiArea = $.proxy(this.engagement.loadNotiArea, this.engagement)
        this.bcloseNotifcationArea = $.proxy(this.engagement.closeNotifcationArea, this.engagement)
        this.bcancelTimoutCloseNotifcationArea = $.proxy(this.engagement.cancelTimoutCloseNotifcationArea, this.engagement)
        this.bclearGrabAcquiredBadgesTimeout = $.proxy(this.engagement.clearGrabAcquiredBadgesTimeout, this.engagement)
        this.bbadging = $.proxy(this.engagement.badging, this.engagement)
        this.bshowRemainingBadges = $.proxy(this.engagement.showRemainingBadges, this.engagement)
        this.bshowChainEngagement = $.proxy(this.engagement.showChainEngagement, this.engagement)

        // create data object for json callback
        this.badge_data = '{user_name: "' + UserName + '", badges_to_check: "' + this.badge_names + '"}';

        if ($.readCookie(window.location + "_plays") == undefined) {
            this.plays = 0
            $.setCookie(window.location + "_plays", this.plays.toString(), 1)
        } else {
            this.plays = parseInt($.readCookie(window.location + "_plays"))
        }

        this.showContentContainer()
        this.setNotificationLinks()
        this.btnok()
    },

    showContentContainer: function () {
        var t = setTimeout("unhide()", 200);
        unhide = function () {
            $('#whiteModal').animate({ 'top': '0', 'left': '0', 'height': '100%', 'width': '944px' }, 550)
            $('#whiteModal').queue($.proxy(function () {
                $('#whiteModal').css('display', 'none');
                $('#whiteModal').dequeue()
                $('#whiteModal').parent('div').removeClass('hidden')
                if (!this.loggedOn && $.readCookie(window.location + "_sign_in_now") == undefined) {
                    $('.btn-sign-in-now').trigger('click')
                    $.setCookie(window.location + "_sign_in_now", '1', 1)
                }
            }, this));
        }
    },

    setNotificationLinks: function () {
        this.$notifications.each($.proxy(function (i, link) {
            $(link).bind('click', $.proxy(function (e) {
                this.bLoadNotiArea(e.currentTarget.href)
                return false
            }, this));
        }, this));
    },

    btnok: function () {
        this.$btnok.each($.proxy(function (e, link) {
            $(link).bind('click', $.proxy(function () {
                this.bcloseNotifcationArea()
                this.playSWF()
                return false
            }, this))
        }, this))
    },

    playSWF: function () {
        id = GoldFish.SWFInfo.flashId
        width = GoldFish.SWFInfo.width
        height = GoldFish.SWFInfo.height
        flashvars = GoldFish.SWFInfo.flashVars;
        shellPath = GoldFish.SWFInfo.asVersion == "2" ? flashvars.shellPath : flashvars.shellPath + "arcadeShellAS3.swf";

        newHeight = (parseInt(height) + 100)


        if (GoldFish.SWFInfo.asVersion == "2") {
            flashvars['omniSuite'] = s_account
        } else {
            flashvars['omniAccount'] = s_account
        }

        $('#notificationArea').css('top', newHeight + 42)
        if (typeof GoldFish.Config.UserName != "undefined") { user = GoldFish.Config.UserName; flashvars.user = user; }

        if (GoldFish.Config.LoggedOn) { user = GoldFish.Config.UserName; flashvars.user = user; }

        if (GoldFish.SWFInfo.asVersion == "2") {
            delete flashvars['gamePath']
            delete flashvars['shellPath']
            //delete flashvars['user']
        }
        
        $('div#ContentContainer div#notLogIn').remove();
        var params = {};
        var attributes = {};
        $('#ContentContainer').animate({ 'height': newHeight }, 500, function () { swfobject.embedSWF(shellPath, "a" + id, width, height, "9.0.0", false, flashvars, params, attributes, function () { $('.noFlash, .shareLike').show(); }) })

    },

    endGameCallBack: function () {
        this.badge_data = '{user_name: "' + UserName + '", badges_to_check: "' + this.engagement.badge_names + '", in_game_play: "false", badge_action: "flash"}';

        $.ajax({
            url: "/services/interfaces/BadgeManagementService.asmx/AwardBadge",
            data: this.badge_data,
            success: $.proxy(function (data) {
                this.chainEngagementFunc($.parseJSON(data.d))
            }, this)
        })

        this.plays = parseInt($.readCookie(window.location + "_plays")) + 1
        this.engagement.plays = this.plays
        $.setCookie(window.location + "_plays", this.plays.toString(), 1)
    },

    chainEngagementFunc: function (response_data) {

        this.engagement.response_data = response_data
        this.engagement.$notificationAreaContent.html('')

        if (this.engagement.response_data.BadgeAwards != null) {
            badge_alias = this.engagement.response_data.BadgeAwards.now
        } else {
            badge_alias = ''
        }

        this.engagement.awarded_badges = badge_alias.split(",")

        if (this.engagement.awarded_badges[0] != "" && this.engagement.awarded_badges.length > 0) {
            this.bbadging()
        } else if (this.plays <= 3) {
            if (LoggedOn) {
                this.bshowRemainingBadges()
            } else {
                this.bshowChainEngagement()
            }
        } else if (this.plays >= 4 && this.plays <= 10) {
            this.bshowChainEngagement()
        }
    },

    awardBadgeByAlias: function (incoming_badge) {
        badge_data_alias = '{user_name: "' + UserName + '", badges_to_check: "' + incoming_badge + '", in_game_play: "true"}';
        $.ajax({
            url: "/services/interfaces/BadgeManagementService.asmx/AwardBadgeInPlay",
            data: badge_data_alias,
            success: $.proxy(function (data) {
                response_data = $.parseJSON(data.d)
                if (response_data.Status == true) {
                    badge_alias = incoming_badge
                    awarded_badges = badge_alias.split(",")
                    Badging.showAwardedBadges(awarded_badges, 'details')
                }
            }, this)
        })
    },

    displayProfileByName: function (incoming_name) {
        this.engagement.displayProfileByName(incoming_name)
    },

    trackGamePlay: function () {

        if (LoggedOn) {
            var Badges_To_Check = '';

            for (var key in pageBadges) {
                var obj = pageBadges[key];
                for (var prop in obj) {
                    if (prop != undefined && prop != 'undefined') {
                        Badges_To_Check += prop + ",";
                    }
                }
            }

            Badges_To_Check = Badges_To_Check.slice(0, -1);

            awardBadgeWithActivity = '{user_name: "' + UserName + '", badges_to_check: "' + Badges_To_Check + '", object_name: "' + GoldFish.SWFInfo.contentId + '", object_type:"1", badge_action: "flash"}';
            $.ajax({
                url: "/services/interfaces/BadgeManagementService.asmx/AwardBadgeWithActivity",
                data: awardBadgeWithActivity,
                success: $.proxy(function (data) {
                    response_data = $.parseJSON(data.d)
                    if (response_data.Status == true) {
                        badge_alias = response_data.BadgeAwards.now
                        if (badge_alias != "") {
                            awarded_badges = badge_alias.split(",")
                            Badging.showAwardedBadges(awarded_badges, 'details')
                        }
                    }
                }, this)
            })
        }
    }
}


var chainEngagement = function (details) {
    details.chainEngagementFunc()
}

var closeNotiArea = function () {
    $('div#notificationArea').animate({ 'height': 0 }, 550);
}


/*******   Video Details   *********/

Video = {}

Video.Details = function (config) {
    this.config = config

    this.init()
};

Video.Details.prototype = {
    init: function () {
        //time to handle engagement
        this.engagement = new GF.ChainEngagement()

        this.bLoadNotiArea = $.proxy(this.engagement.loadNotiArea, this.engagement)
        this.bcloseNotifcationArea = $.proxy(this.engagement.closeNotifcationArea, this.engagement)
        this.bcancelTimoutCloseNotifcationArea = $.proxy(this.engagement.cancelTimoutCloseNotifcationArea, this.engagement)
        this.bclearGrabAcquiredBadgesTimeout = $.proxy(this.engagement.clearGrabAcquiredBadgesTimeout, this.engagement)
        this.bbadging = $.proxy(this.engagement.badging, this.engagement)
        this.bshowRemainingBadges = $.proxy(this.engagement.showRemainingBadges, this.engagement)
        this.bshowChainEngagement = $.proxy(this.engagement.showChainEngagement, this.engagement)

        // create data object for json callback
        this.badge_data = '{user_name: "' + UserName + '", badges_to_check: "' + this.badge_names + '", badge_action: "flash"}';

        if ($.readCookie(window.location + "_plays") == undefined) {
            this.plays = 0
            $.setCookie(window.location + "_plays", this.plays.toString(), 1)
        } else {
            this.plays = parseInt($.readCookie(window.location + "_plays"))
        }

        // cache flash vars
        this.flashId = GoldFish.SWFInfo.flashId
        this.flashWidth = GoldFish.SWFInfo.width
        this.flashHeight = GoldFish.SWFInfo.height
        this.flashVars = GoldFish.SWFInfo.flashVars
        this.engagement.$page_chain.sort(function () { return 0.5 - Math.random() })
        

        if (navigator.userAgent.match(/iPad/i) != null || navigator.userAgent.match(/iPhone/i) != null || navigator.userAgent.match(/iPod/i) != null) {
            this.html5Video()
        } else {
            this.playSWF()
        }
    },



    chainEngagementFunc: function (response_data) {
        thisObj = this

        this.engagement.response_data = response_data
        this.engagement.$notificationAreaContent.html('')
        badge_alias = this.engagement.response_data.BadgeAwards.now
        this.engagement.awarded_badges = badge_alias.split(",")


        if (this.engagement.awarded_badges[0] != "" && this.engagement.awarded_badges.length > 0) {
            this.bbadging(false, 'video')
        } else {
            if(Math.random() > 0.74){
                this.bshowRemainingBadges(true)
            } else {
                this.bshowChainEngagement()
            }
        }
    },

    videoComplete: function () {
        if (LoggedOn) {
            awardBadgeWithActivity = '{user_name: "' + UserName + '", badges_to_check: "' + this.engagement.badge_names + '", object_name: "' + GoldFish.SWFInfo.contentId + '", object_type:"2", badge_action: "flash"}';
            $.ajax({
                url: "/services/interfaces/BadgeManagementService.asmx/AwardBadgeWithActivity",
                data: awardBadgeWithActivity,
                success: $.proxy(function (data) {
                    this.chainEngagementFunc($.parseJSON(data.d))
                }, this)
            })
        } else {
            this.bshowChainEngagement()
        }
    },
    playSWF: function () {
        playerPath = GoldFish.SWFInfo.flashPath == "" || GoldFish.SWFInfo.swfName == "" ? "/videos/GoldfishVideoPlayer.swf" : GoldFish.SWFInfo.flashPath + GoldFish.SWFInfo.swfName;

        var params = {
            "allowfullscreen": "true",
            "allowscriptaccess": "always",
            "wmode": "opaque"
        };
        var attributes = {};

        this.flashVars['omniAccount'] = s_account
        if (this.flashVars.NextVideoImage == "_thumb.jpg") {
            this.flashVars.NextVideoImage = "";
        }

        swfobject.embedSWF(playerPath, "a" + this.flashId, "720px", "405px", "9.0.0", false, this.flashVars, params, attributes, function () { $('.noFlash').show(); })
    },

    _html5VidTemplate: '<video controls="controls" poster="{{ poster }}" width="720" height="405">' +
	'<source src="{{ mp4 }}" type="video/mp4" />' +
    '</video>',


    html5Video: function () {
        html5Template = this._html5VidTemplate
        videoInfo = {
            poster: GoldFish.SWFInfo.VideoImageURL,
            mp4: GoldFish.SWFInfo.flashVars.html5VideoSource,
            title: GoldFish.SWFInfo.flashVars.VideoName,
            image: GoldFish.SWFInfo.VideoImageURL
        }
        $.mustache = function (template, view, partials) {
            return Mustache.to_html(template, view, partials);
        };

        $('.flashWrap', $('#innerContainer')).prepend($.mustache(html5Template, videoInfo))
        $("#a" + this.flashId).remove()

    }
}

/*
**********************************************************************************
*  Scripts for Sharing
**********************************************************************************
*/
GF.Sharing = function () {
    $('.shareImg').live('click', function () {
        $('#shareContent').html('<span class="shareFish"></span><span id="shareCopyLnk">copy this link </span><input type="text" id="shareInput" /><a href="#cancel" class="image-link btn-close-small" ></a>');
        $('#shareContent').animate({ 'width': '325px', 'cursor': 'auto' }, 200);
        $('#btn-close-small').css("display", "block");
        copyText = document.location.href;
        $('#shareInput').val(copyText);
        $('#shareContent input').focus();
        $('#shareContent input:text').select();
        GF.omniture.share();
    });
    $('.btn-close-small').live('click', function () {
        $('#shareContent').html('<div class="shareImg"></div>');
        $("#shareContent").animate({ 'width': '75px', 'cursor': 'pointer' }, 200);
        return false;
    });

    $('#shareContent input:text').live('click', function () {
        $(this).select();
    });
    $('#shareContent span.shareFish, #shareContent span').live('click', function () {
        if ($.browser.msie) {
            copyToClipboard(document.getElementById('shareInput'));
        } else {
            highlightTxt($('#shareInput'));
        }
    });
};
function highlightTxt(target) {
    $(target).focus();
    $(target).select();
};
function copyToClipboard(target) {
    /**
    * note this only works in IE  
    */
    //window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
    highlightTxt(target);
    textRange = target.createTextRange();
    textRange.execCommand("RemoveFormat");
    textRange.execCommand("Copy");
};


/*
**********************************************************************************
*  methods to run on DOM ready for every page
*  page specific JS methods are instantiated on individual pages
**********************************************************************************
*/
$(function () {

    /*$("#signIn").live('click', function (e) {
        e.preventDefault();
    });
    */
    //Likes count    
    var likeObjects = new Array();
    if ($('.Likes').length > 0) {
        $('.Likes').each(function () {
            likeObjects.push($(this).attr('name'));
        });
        likeCount(likeObjects);
    };
    $.mustache = function (template, view, partials) {
        return Mustache.to_html(template, view, partials);
    };
    Badging = new GF.Badging
   
});


/* MUSTACHE.JS */
/*
mustache.js — Logic-less templates in JavaScript

See http://mustache.github.com/ for more info.
*/

var Mustache = function () {
    var Renderer = function () { };

    Renderer.prototype = {
        otag: "{{",
        ctag: "}}",
        pragmas: {},
        buffer: [],
        pragmas_implemented: {
            "IMPLICIT-ITERATOR": true
        },
        context: {},

        render: function (template, context, partials, in_recursion) {
            // reset buffer & set context
            if (!in_recursion) {
                this.context = context;
                this.buffer = []; // TODO: make this non-lazy
            }

            // fail fast
            if (!this.includes("", template)) {
                if (in_recursion) {
                    return template;
                } else {
                    this.send(template);
                    return;
                }
            }

            template = this.render_pragmas(template);
            var html = this.render_section(template, context, partials);
            if (in_recursion) {
                return this.render_tags(html, context, partials, in_recursion);
            }

            this.render_tags(html, context, partials, in_recursion);
        },

        /*
        Sends parsed lines
        */
        send: function (line) {
            if (line !== "") {
                this.buffer.push(line);
            }
        },

        /*
        Looks for %PRAGMAS
        */
        render_pragmas: function (template) {
            // no pragmas
            if (!this.includes("%", template)) {
                return template;
            }

            var that = this;
            var regex = new RegExp(this.otag + "%([\\w-]+) ?([\\w]+=[\\w]+)?" +
            this.ctag, "g");
            return template.replace(regex, function (match, pragma, options) {
                if (!that.pragmas_implemented[pragma]) {
                    throw ({ message:
            "This implementation of mustache doesn't understand the '" +
            pragma + "' pragma"
                    });
                }
                that.pragmas[pragma] = {};
                if (options) {
                    var opts = options.split("=");
                    that.pragmas[pragma][opts[0]] = opts[1];
                }
                return "";
                // ignore unknown pragmas silently
            });
        },

        /*
        Tries to find a partial in the curent scope and render it
        */
        render_partial: function (name, context, partials) {
            name = this.trim(name);
            if (!partials || partials[name] === undefined) {
                throw ({ message: "unknown_partial '" + name + "'" });
            }
            if (typeof (context[name]) != "object") {
                return this.render(partials[name], context, partials, true);
            }
            return this.render(partials[name], context[name], partials, true);
        },

        /*
        Renders inverted (^) and normal (#) sections
        */
        render_section: function (template, context, partials) {
            if (!this.includes("#", template) && !this.includes("^", template)) {
                return template;
            }

            var that = this;
            // CSW - Added "+?" so it finds the tighest bound, not the widest
            var regex = new RegExp(this.otag + "(\\^|\\#)\\s*(.+)\\s*" + this.ctag +
              "\n*([\\s\\S]+?)" + this.otag + "\\/\\s*\\2\\s*" + this.ctag +
              "\\s*", "mg");

            // for each {{#foo}}{{/foo}} section do...
            return template.replace(regex, function (match, type, name, content) {
                var value = that.find(name, context);
                if (type == "^") { // inverted section
                    if (!value || that.is_array(value) && value.length === 0) {
                        // false or empty list, render it
                        return that.render(content, context, partials, true);
                    } else {
                        return "";
                    }
                } else if (type == "#") { // normal section
                    if (that.is_array(value)) { // Enumerable, Let's loop!
                        return that.map(value, function (row) {
                            return that.render(content, that.create_context(row),
                partials, true);
                        }).join("");
                    } else if (that.is_object(value)) { // Object, Use it as subcontext!
                        return that.render(content, that.create_context(value),
              partials, true);
                    } else if (typeof value === "function") {
                        // higher order section
                        return value.call(context, content, function (text) {
                            return that.render(text, context, partials, true);
                        });
                    } else if (value) { // boolean section
                        return that.render(content, context, partials, true);
                    } else {
                        return "";
                    }
                }
            });
        },

        /*
        Replace {{foo}} and friends with values from our view
        */
        render_tags: function (template, context, partials, in_recursion) {
            // tit for tat
            var that = this;

            var new_regex = function () {
                return new RegExp(that.otag + "(=|!|>|\\{|%)?([^\\/#\\^]+?)\\1?" +
          that.ctag + "+", "g");
            };

            var regex = new_regex();
            var tag_replace_callback = function (match, operator, name) {
                switch (operator) {
                    case "!": // ignore comments
                        return "";
                    case "=": // set new delimiters, rebuild the replace regexp
                        that.set_delimiters(name);
                        regex = new_regex();
                        return "";
                    case ">": // render partial
                        return that.render_partial(name, context, partials);
                    case "{": // the triple mustache is unescaped
                        return that.find(name, context);
                    default: // escape the value
                        return that.escape(that.find(name, context));
                }
            };
            var lines = template.split("\n");
            for (var i = 0; i < lines.length; i++) {
                lines[i] = lines[i].replace(regex, tag_replace_callback, this);
                if (!in_recursion) {
                    this.send(lines[i]);
                }
            }

            if (in_recursion) {
                return lines.join("\n");
            }
        },

        set_delimiters: function (delimiters) {
            var dels = delimiters.split(" ");
            this.otag = this.escape_regex(dels[0]);
            this.ctag = this.escape_regex(dels[1]);
        },

        escape_regex: function (text) {
            // thank you Simon Willison
            if (!arguments.callee.sRE) {
                var specials = [
          '/', '.', '*', '+', '?', '|',
          '(', ')', '[', ']', '{', '}', '\\'
        ];
                arguments.callee.sRE = new RegExp(
          '(\\' + specials.join('|\\') + ')', 'g'
        );
            }
            return text.replace(arguments.callee.sRE, '\\$1');
        },

        /*
        find `name` in current `context`. That is find me a value
        from the view object
        */
        find: function (name, context) {
            name = this.trim(name);

            // Checks whether a value is thruthy or false or 0
            function is_kinda_truthy(bool) {
                return bool === false || bool === 0 || bool;
            }

            var value;
            if (is_kinda_truthy(context[name])) {
                value = context[name];
            } else if (is_kinda_truthy(this.context[name])) {
                value = this.context[name];
            }

            if (typeof value === "function") {
                return value.apply(context);
            }
            if (value !== undefined) {
                return value;
            }
            // silently ignore unkown variables
            return "";
        },

        // Utility methods

        /* includes tag */
        includes: function (needle, haystack) {
            return haystack.indexOf(this.otag + needle) != -1;
        },

        /*
        Does away with nasty characters
        */
        escape: function (s) {
            s = String(s === null ? "" : s);
            return s.replace(/&(?!\w+;)|["'<>\\]/g, function (s) {
                switch (s) {
                    case "&": return "&amp;";
                    case "\\": return "\\\\";
                    case '"': return '&quot;';
                    case "'": return '&#39;';
                    case "<": return "&lt;";
                    case ">": return "&gt;";
                    default: return s;
                }
            });
        },

        // by @langalex, support for arrays of strings
        create_context: function (_context) {
            if (this.is_object(_context)) {
                return _context;
            } else {
                var iterator = ".";
                if (this.pragmas["IMPLICIT-ITERATOR"]) {
                    iterator = this.pragmas["IMPLICIT-ITERATOR"].iterator;
                }
                var ctx = {};
                ctx[iterator] = _context;
                return ctx;
            }
        },

        is_object: function (a) {
            return a && typeof a == "object";
        },

        is_array: function (a) {
            return Object.prototype.toString.call(a) === '[object Array]';
        },

        /*
        Gets rid of leading and trailing whitespace
        */
        trim: function (s) {
            return s.replace(/^\s*|\s*$/g, "");
        },

        /*
        Why, why, why? Because IE. Cry, cry cry.
        */
        map: function (array, fn) {
            if (typeof array.map == "function") {
                return array.map(fn);
            } else {
                var r = [];
                var l = array.length;
                for (var i = 0; i < l; i++) {
                    r.push(fn(array[i]));
                }
                return r;
            }
        }
    };

    return ({
        name: "mustache.js",
        version: "0.3.1-dev",

        /*
        Turns a template and view into HTML
        */
        to_html: function (template, view, partials, send_fun) {
            var renderer = new Renderer();
            if (send_fun) {
                renderer.send = send_fun;
            }
            renderer.render(template, view, partials);
            if (!send_fun) {
                return renderer.buffer.join("\n");
            }
        }
    });
} ();

// Media Mind Click Tag Function - WORKING //
function ebConversionTracker(conv) {
    var ebConversionImg = new Image();
    var ebConversionURL = "HTTP://bs.serving-sys.com/BurstingPipe/ActivityServer.bs?";
    var ebRandClick = Math.random() + '';
    ebRandClick = ebRandClick * 1000000;
    ebConversionURL += "cn=as&ActivityID=" + conv + "&ns=1&rnd=" + ebRandClick;
    ebConversionImg.src = ebConversionURL;
};

