﻿$('document').ready(function () {
    /************************
    * Facebook JS SDK Init
    *************************/
    window.fbAsyncInit = function () {
        FB.init({ appId: '193887373979029', status: true, cookie: true,
            xfbml: true
        });
    };
    (function () {
        var e = document.createElement('script'); e.async = true;
        e.src = document.location.protocol +
      '//connect.facebook.net/en_US/all.js';
        document.getElementById('fb-root').appendChild(e);
    } ());

    $("#sonetdiv").dialog({
        autoOpen: false,
        modal: false,
        width: 640,
        height: 460,
        open: function (event, ui) {
            $("#sonetdiv").html(overlayData);
        }
    }).bind('clickoutside', function (e) {
        if ($(this).dialog('isOpen')) {
            $(this).dialog('close');
        }
    });

    //SHARE BUTTONS
    $('#shfb').click(function () {
        fbstatus();
    });

    $('#shtw').click(function () {
        twstatus();
    });

    $('#shct').click(function () {
        location.href = 'http://commonthreads.org/Pages/Donate';
    });

});

var __ajaxurl = '/ajax/monkfruit/__sonetshare_mf.aspx'
var overlayData = null;

function fbstatus() {
    if (typeof (listItemId) == 'undefined') {
        //        return false;
    }
    if (FB == 'undefined') {
        return false;
    }
    FB.getLoginStatus(function (response) {
        if (response.session) {
            // logged in and connected user, someone you know
            /*
            $.get(__ajaxurl, { action: 'fblike', listItemId: listItemId, rewritePath: rewritePath, fbuid: response.session.uid }, function (data) {
            overlayData = getIframe(data.url);
            $("#sonetdiv").dialog({ height: 460 });
            $('#sonetdiv').dialog("open")
            // $('#sonetdiv').data('overlay').load();
            });
            */
            getfbinfo(response);
        } else {
            // no user session available, someone you dont know
            fblogin();
        }
    });
}

function getfbinfo(response) {
    FB.api('/me', function (response2) {
        fbname = response2.name;
        fblink = response2.link;
        fbemail = response2.email;

        $.ajax({
            url: __ajaxurl,
            data: { action: 'fblike', listItemId: listItemId, rewritePath: rewritePath, fbuid: response.session.uid, fbname: fbname, fblink: fblink, fbemail: fbemail },
            success: function (data) {

                overlayData = getIframe(data.url);
                $("#sonetdiv").dialog({ height: 460 });
                $('#sonetdiv').dialog("open")
                // jq('#sonetdiv').data('overlay').load();
            },
            async: false
        });

    });
}

function fblogin() {
    FB.login(function (response) {
        if (response.session) {
            if (response.perms) {
                // user is logged in and granted some permissions.
                // perms is a comma separated list of granted permissions
                getfbinfo(response);
                /*
                $.get(__ajaxurl, { action: 'fblike', listItemId: listItemId, rewritePath: rewritePath, fbuid: response.session.uid }, function (data) {
                    overlayData = getIframe(data.url);
                    $("#sonetdiv").dialog({ height: 460 });
                    $('#sonetdiv').dialog("open")
                    // $('#sonetdiv').data('overlay').load();
                });
                */
            } else {
                // user is logged in, but did not grant any permissions
            }
        } else {
            // user is not logged in
        }
    }, { perms: 'publish_stream,email' });
}

function twstatus() {
    if (typeof (listItemId) == 'undefined') {
        //        return false;
    }
    var cookies = ReadCookie('de_hrhctw').split('&');
    if (cookies.length > 1) {
        var t = cookies[0].replace('t=', '');
        var ts = cookies[1].replace('ts=', '');
    }
    $.get(__ajaxurl, { action: 'tweet', listItemId: listItemId, rewritePath: rewritePath, t: t, ts: ts }, function (data) {
        //console.log(data.status);
        if (data.status == 'redirect') {
            window.location.href = data.url;
        }
        if (data.status == 'authed') {
            overlayData = getIframe(data.url);
            $("#sonetdiv").dialog({ height: 460 });
            $('#sonetdiv').dialog("open")
            //   $('#sonetdiv').data('overlay').load();
        }
    });
}

function sendfb() {
    hideShareButton();
    //FB.api('/me/feed', 'post', { message: shdata.fb_message }, function (response) {
    FB.api('/me/feed', 'post', { message: shdata.fb_message, link: "http://www.monkfruit.org/?dtrk=352", description: "Monk fruit is packed with healthy antioxidants and vitamins, but what makes this fruit really special is its natural, great-tasting sweetness. Monk fruit contains unique natural antioxidants called mogrosides, which have a delicious sweet taste, but are calorie-free. Natural, calorie-free sweetness from fruit - what could be better than that?", name: "Mother Nature's answer to calorie-free sweetness!", picture: "http://www.thecabledealguy.com/images/cabledealguy/CableDealGuy4.jpg", caption: "Help support nutrition education for kids!" }, function (response) {
        if (!response || response.error) {
            alert('Facebook seems to be experiencing problems. Please try again later.');
            window.parent.closeOverlay();
        } else {
            $.get(__ajaxurl, { action: 'sendfb', msg: shdata.fb_message, type: shdata.type, lid: shdata.lid, uid: shdata.uid }, function (data) {
                if (data.status == "ok") {
                    window.parent.closeOverlay();
                }
            });
        }
    });

}

function sendtw() {
    hideShareButton();
    $.get(__ajaxurl, { action: 'sendtweet', msg: shdata.tw_message, type: shdata.type, lid: shdata.lid, uid: shdata.uid }, function (data) {
        if (data.status == 'ok') {
            window.parent.closeOverlay();
        } else {
            alert('Twitter seems to be experiencing problems. Please try again later.');
            window.parent.closeOverlay();
        }
    });
}

function closeOverlay() {
    $('.ui-dialog-titlebar-close').click();
}

function closeOverlayAndThen(action) {
    $('.ui-dialog-titlebar-close').click();
    if (action == 'tw') {
        twstatus();
    }
    if (action == 'fb') {
        fbstatus();
    }
}

function ReadCookie(cookieName) {
    var theCookie = "" + document.cookie;
    var ind = theCookie.indexOf(cookieName);
    if (ind == -1 || cookieName == "") return "";
    var ind1 = theCookie.indexOf(';', ind);
    if (ind1 == -1) ind1 = theCookie.length;
    return unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
}

function getIframe(url) {
    return '<iframe src="' + url + '" width="610" height="400px" frameborder="no" border="0" marginwidth="0" marginheight="0" allowTransparency="true"></iframe>';
}

function getTallIframe(url) {
    return '<iframe src="' + url + '" width="610" height="590px" frameborder="no" border="0" marginwidth="0" marginheight="0" allowTransparency="true"></iframe>';
}

function hideShareButton() {
    $('.sharebtn').html('Please wait while your message is shared...');
}
