﻿var sCurrentPage;
// Development Facebook API Key
var sConnectAPIKey = "a01cf08bf67dfb1cca7219d8b5b81c1e";
// Production Facebook API Key
//var sConnectAPIKey = "d24473aa53f3e37313758cf47a43e2ac";
//var init;
//var conf;

//$(document).ready(function () {
//    init = $(document).data('gigya.Init');
//    conf = init.conf;
//});

var sCurrentUserNickname = null;

function ShowJoinModal() {
    jQuery('#menubox .join-button').trigger('click');
}

function ShowSignInModal() {
    jQuery('#menubox .signin-button').trigger('click');
}

function PopulateFacebookComments(_sXID, bLongCopy) {
    //jQuery('#commentsFBML').html('<iframe id="frameComments" frameborder="0" src="/Comments.aspx?sXID=' + _sXID + '&nWidth=575&nNumPosts=4" scrolling="no"></iframe>');
    LoadCommentsFBML(_sXID);
    jQuery.post("/API/Slurpee/GetNumComments.ashx", { sXID: _sXID }, function (xml) { PopulateFacebookCommentsHTML(xml, bLongCopy); }, "xml");
}

function LoadCommentsFBML(_sXID) {
    jQuery.get("/API/Slurpee/PopulateFacebookComments.ashx", { sXID: _sXID, nWidth: 575, nNumPosts: 4 }, function (sHTML) { PopulateFacebookCommentsFBML(sHTML); }, "html");
}

function PopulateFacebookCommentsFBML(sHTML) {
    jQuery('#commentsFBML').html(sHTML);
}

function PopulateFacebookCommentsHTML(xml, bLongCopy) {
    jQuery(xml).find('comment').each(function () {
        if (bLongCopy) {
            jQuery('#facebookCommentsCount').html('<a href="javascript:void(0);">' + parseInt(jQuery(this).attr('number')) + ' comment(s). <i>Add yours.</i></a>');
            jQuery('#facebookCommentsCountBand').html(parseInt(jQuery(this).attr('number')) + ' comment(s). <i>Add yours.</i>');
        }
        else {
            jQuery('#facebookCommentsCount').html('<a href="javascript:void(0);">' + parseInt(jQuery(this).attr('number')) + ' comment(s)</a>');
            jQuery('#facebookCommentsCountBand').html(parseInt(jQuery(this).attr('number')) + ' comment(s)');
        }
    });
}

// Disable the enter key on forms when needed.
function DisableEnterKey(e) {
    var key;
    if (window.event) key = window.event.keyCode; //IE
    else key = e.which; //firefox     

    return (key != 13);
}

function InitGlobal() {
    // Turn on the background image
    //jQuery('body').css('background', '#0096e2 url("/Images/backgroundDirt.jpg")');
    jQuery('body').css('background', '#0096e2');

    // Turn the current page nav on
    TogglePageNav(sCurrentPage, 'on');

    // Set the rollovers for the nav images
    jQuery('#navigation img').hover(function () {
        TogglePageNav(this.id, 'on');
    }, function () {
        TogglePageNav(this.id, 'off');
    });
}

function TogglePageNav(sPage, sState) {
    // Never turn the current page nav off
    if ((sPage != sCurrentPage) || (sState == "on")) {
        jQuery('#' + sPage).attr('src', '/Images/Navigation/' + sPage + '_' + sState + '.png');
    }
}

function LoadBackgroundFlash() {
    if (FlashDetect.installed) {
        var flashvars = {};
        var params = { bgcolor: "#0096e2", scale: "noscale", salign: "t", wmode: "transparent" };
        var attributes = { id: "flash" };
        swfobject.embedSWF("/Media/footer.swf", "backgroundFlash", "100%", "223", "9.0.0", "", flashvars, params, attributes);
    }
    else {
        jQuery('#backgroundFlash').html('<a href="http://www.adobe.com/go/EN_US-H-GET-FLASH" target="_blank"><img src="/Images/get_adobe_flash_player.png" alt="Get Adobe Flash Player" /></a>');
    }
}

function LoadBackgroundFlashFullScreen() {
    var nContentHeight = jQuery('#containerGlobal').height();
    // Subtract the height of the bottom margin below the straw
    var nContentMinusMarginHeight = nContentHeight - parseInt(jQuery('#strawBottom').css('margin-bottom').split('p')[0]);
    var flashvars = { nBrowserHeight: "" + nContentMinusMarginHeight + "" };
    var params = { bgcolor: "#0096e2", scale: "noscale", salign: "t", wmode: "transparent" };
    var attributes = { id: "flash" };
    swfobject.embedSWF("/Media/footer.swf", "backgroundFlash", "100%", "" + nContentHeight + "", "10.0.0", "", flashvars, params, attributes);
}

function ShareFacebook(caption, name, href, hrefImage, description) {
    // path to the image that shows up on the left of the post when displayed on the wall or news feed
    var src = hrefImage;
    
    // src must be absolute url not relative; image size 160 x 160 is good
    var attachment = { 'name': name, 'href': href, 'caption': caption, 'description': unescape(description), 'media': [{ 'type': 'image', 'src': src, 'href': href}] };

    // limit one link in this collection
    var link_text = 'Check this out';
    var link_href = href;
    var links = [{ "text": link_text, "href": link_href}];

    // FB default is What's on your mind?
    var comment_header_text = 'What\' on your mind?';

    // Before calling the Facebook share, Google track this page share
    pageTracker._trackPageview('/FacebookShare/' + sCurrentPage + '/');
    
    // all the work here
    FB.Connect.streamPublish('', attachment, links, null, comment_header_text, function (post_id, exception) { }, false, null);
}

function SignOutFacebook() {
    FB.Bootstrap.requireFeatures(["Connect"], function () {
        FB.init('' + sConnectAPIKey + '', '/xd_receiver.htm', { 'reloadIfSessionStateChanged': true });
        FB.Connect.logout(function () {
            document.location = "/Default.aspx";
        });
    });
}

function Redirect(sURL) {
    document.location = sURL;
}

function PopulateFacebookFeed(_nNumPosts) {
    jQuery.post("/API/Slurpee/GetFacebookPosts.aspx", { nNumPosts: _nNumPosts }, function (xml) { PopulateFacebookFeedHTML(xml); }, "xml");
}

function PopulateFacebookFeedHTML(xml) {
    var sHTML = '';

    jQuery(xml).find('post').each(function () {
        sHTML += '<div class="facebook"><a href="http://www.facebook.com/profile.php?id=' + jQuery(this).attr('uid') + '" target="_blank"><img src="' + jQuery(this).attr('pic') + '" width="45" height="45" align="left" /></a><a href="http://www.facebook.com/profile.php?id=' + jQuery(this).attr('uid') + '" target="_blank">' + jQuery(this).attr('nameFirst') + ' ' + jQuery(this).attr('nameLast') + '</a><div>' + URLDecode(jQuery(this).attr('message')) + '</div><div class="postDate">' + jQuery(this).attr('hoursAgo') + ' hours ago</div></div>';
    });
    jQuery('#feedFacebook').html(sHTML);
}

function PopulateTwitterFeed(_nNumPosts, _nNumChars, _bBOTB) {
    jQuery.post("/API/Slurpee/GetTwitterPosts.ashx", { nNumPosts: _nNumPosts, nNumChars: _nNumChars, bBOTB: _bBOTB }, function (xml) { PopulateTwitterFeedHTML(xml); }, "xml");
}

function PopulateTwitterFeedHTML(xml) {
    var sHTML = '';

    jQuery(xml).find('post').each(function () {
        sHTML += '<div class="postTwitter"><span class="postUser">Slurpee: </span>' + URLDecode(jQuery(this).attr('message')) + '<div class="postDate">' + jQuery(this).attr('daysAgo') + ' days ago</div></div>';
    });
    jQuery('#feedTwitter').html(sHTML);
}

function GetCurrentDateTime() {
    var dCurrent = new Date();

    jQuery.ajax({
        type: "POST",
        url: "/API/Slurpee/GetCurrentDateTime.ashx",
        dataType: "xml",
        success: function (xml) {
            jQuery(xml).find('datetime').each(function () {
                dCurrent = jQuery(this).text();
            });
        }
    });

    return dCurrent;
}

function trace(s) {
    //window.console.log(s);
}

//Gigya Global Functions
//Gigya Functions
function setGigyaShareInfo(shareUserMessage, shareTitle, shareLinkBack, shareDescription, shareImagePath, shareImageClickUrl, shareActionLink) {
    //Gigya Share
    // Constructing a UserAction Object   
    var act = new gigya.services.socialize.UserAction();

    // Setting the User Message  
    act.setUserMessage(shareUserMessage);

    // Setting the Title  
    act.setTitle(shareTitle);

    act.setLinkBack(shareLinkBack);

    // Setting the Description  
    act.setDescription(shareDescription);

    // Adding a Media Item (image)  
    var image = {
        type: 'image',
        src: shareImagePath,
        href: shareImageClickUrl
    }
    act.addMediaItem(image);

    // Adding an Action Link  
    act.addActionLink("Read More", shareActionLink);

    return act;
}

function setGigyaShareBar(containerID, shareUserMessage, shareTitle, shareLinkBack, shareDescription, shareImagePath, shareImageClickUrl, shareActionLink, contextId, finalUrl) {
    var ua = setGigyaShareInfo(shareUserMessage, shareTitle, shareLinkBack, shareDescription, shareImagePath, shareImageClickUrl, shareActionLink);

    var params = {
        userAction: ua,
        shareButtons:
        [
			{
			    // General Share Button  
			    provider: 'share',
			    tooltip: 'Share'
			},
            {
                provider: 'facebook-like',
                tooltip: 'Like on Facebook',
                action: 'like'
            },
			{
			    provider: 'google-plusone',
			    tooltip: 'Share on Google',
			    iconOnly: 'true'
			}
        ],
        containerID: 'gigyaShare',
        cid: contextId,
        operationMode: 'multiSelect',
        onLoad: function () {
            //trace('share hit 3');
            //var fid = flavorCommentId.substring(flavorCommentId.length - 2);
            var furl = finalUrl;
            trace('share hit 2');
            //trace('Response: ' + response);
            var p = { 'URL': furl, 'callback': function (response) {
                trace('ErrorCode: ' + response.errorCode);
                if (response.errorCode == 0) {
                    var n = response.shareCounts.facebook;
                    //var ss = 'div.#gigyaShare-reaction2_plusOne';
                    var ss = 'div.#gigyaShare-reaction2';
                    if (n > 1000) {
                        trace('margin > 1000');
                    } else if (n > 100) {
                        trace('margin > 100');
                    } else if (n > 10) {
                        trace('margin > 10');
                    } else {
                        trace('margin adjusted');
                        $(ss).css('margin-left', '-16px');
                    }
                }
            }
            };
            gigya.services.socialize.getProviderShareCounts(conf, p);
        }
    };

    gigya.services.socialize.showShareBarUI(conf, params);
}

function commentsPrintResponse(response) {
    if (response.errorCode == 0) {
        if (null != response.comments && response.comments.length > 0) {
            var totalCount = response.commentCount + ' Comment(s).  <strong>Speak Up</strong>.';

            $('#gigyaComments .reviewText a').html(totalCount);
            _totalCommentsCount = totalCount;
        }
        else {
            var totalCount = '0 Comment(s).  <strong>Speak Up</strong>.';
            $('#gigyaComments .reviewText a').html(totalCount);
        }
    } else {
        //console.log('Error :' + response.errorMessage);
    }
};

function showGigyaCommentsModule(streamId, categoryId, containerId) {
    var params = {
        categoryID: categoryId,
        streamID: streamId,
        containerID: containerId,
        cid: streamId
    }
    gigya.services.socialize.showCommentsUI(conf, params);
}

function updateGigyaTotalComments(streamId, categoryId) {
    var params = {
        categoryID: categoryId,
        streamID: streamId,
        callback: commentsPrintResponse, 
        cid: streamId
    };

    gigya.services.comments.getComments(conf, params);
}

function formatItemNameForGigya(itemName, itemId) {
    var itemNameFormatted = itemName.replace(/%c2%ae/g, ''); //remove copyright
    itemNameFormatted = itemName.replace(/%3csup%3e%c2%ae%3c%2fsup%3e/g, ''); //remove register
    itemNameFormatted = itemNameFormatted.replace(/%e2%80%99/g, '').substring(0, 25); //remove apostrophe                       
    itemNameFormatted = itemNameFormatted.split('+').join('_'); //replace + with underscores
    itemNameFormatted = itemNameFormatted.replace(/ /g, '_');
    //itemNameFormatted = itemNameFormatted.replace(/[^a-zA-Z 0-9]+/g, '');
    itemNameFormatted = itemNameFormatted + '_' + itemId;

    return itemNameFormatted;
}

function showShareOnNewRegistration() {

    // Constructing a UserAction Object  
    var act = new gigya.services.socialize.UserAction();

    // Setting the title and description   
    // (will be presented in the preview on the Share UI)  
    act.setTitle("Sign up to be a Slurpee superstar");
    act.setDescription("I just signed up for a 7-Eleven membership with access to the wonderful world of Slurpee Nation rewards.  Register now on their Facebook tab and then maybe later we can do the secret handshake.");

    // Setting a link back to the publishing source  
    act.setLinkBack("https://www.facebook.com/Slurpee");

    // Adding Action Link  
    act.addActionLink("Register on Facebook",
                "https://www.facebook.com/Slurpee");

    // Adding an image (will be presented in the preview on the Share UI)  
    var image = {
        src: '/Images/7-11-logo.jpg',
        href: 'http://www.slurpee.com',
        type: 'image'
    }
    act.addMediaItem(image);

    // Parameters for the showShareUI method, including the UserAction object  
    var params =
            {
                userAction: act  // The UserAction object enfolding the newsfeed data.  
                // Gigya finishes the publishing process.  

                // Enable the "More" button and screen:  
                , showMoreButton: true
                // Customize the list of destinations in the "More" screen:  
                //, moreEnabledProviders: "digg, friendfeed, googlebookmarks, myaol, livebookmarks, technorati, yahoobookmarks, linkedin"
                //  Remove yahoo and linkedin destinations from the main Share screen (Note - we added these destinations to the "More" screen):  
                //, disabledProviders: "yahoo, linkedin"
                , useHTML: true  // Use the HTML implementation of the Plugin (rather then Flash implementation)  

            };

    // Show the "Share" dialog  
    gigya.services.socialize.showShareUI(conf, params);

    var shareParams = {
        userAction: act,
        scope: 'both'
    };

    // Publish the User Action  
    gigya.services.socialize.publishUserAction(conf, shareParams);
}

function setReactionsFeedMessage(itemName, reactionName) {
    return 'I just rated ' + itemName + ' as ' + reactionName + ' on Slurpee.com.  Get the delicious details here.';
}

function getUserInfoResponse(response) {
    if (response.errorCode == 0) {
        var user = response['user'];
        sCurrentUserNickname = user['nickname'];
        //alert(sCurrentUserNickname);
    }
    else {
        trace('Error: ' + response.errorMessage);
    }
}

function setUserAction(userMessage, title, linkBack, description, image, actionLink) {
    var userAction = new gigya.services.socialize.UserAction();

    if (userMessage != '') {
        userAction.setUserMessage(userMessage);
    }
    userAction.setTitle(title);
    userAction.setLinkBack(linkBack);
    userAction.setDescription(description);
    if (image != '') {
        userAction.addMediaItem(image);
    }
    userAction.addActionLink("Read More", actionLink);

    return userAction;
}
