$('document').ready(function () {

    //Navigation
    if ($("#nav li").length > 0) {
        $("#nav li").hoverIntent(function (event) {
            $(this).find('.flyout').dequeue().stop(true, true).slideDown('fast');

        }, function () {
            $(this).find('.flyout').dequeue().stop(true, true).slideUp('fast');
        });

        $('.flybot').mouseenter(function () {
            $(this).parent().stop(true, true).slideUp('fast');
        });
    }

    //Portfolio Rotator
    if ($("#slider").length > 0) {
        $('#slider').jshowoff({ speed: 6000, changeSpeed: 1500, links: true, controls: false });
    }

    /************************
    * Facebook JS SDK Init
    *************************/
    window.fbAsyncInit = function () {
        FB.init({ 
                  appId: '221079181260823', 
                  status: true, 
                  cookie: true,
                  xfbml: true,
                  oauth: 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: true,
        width: 640,
        height: 500,
        open: function (event, ui) {
            $("#sonetdiv").html(overlayData);
        }
    }).bind('clickoutside', function (e) {
        if ($(this).dialog('isOpen')) {
            $(this).dialog('close');
        }
    });

    //Terms popup
    $('#shterms').click(function () {
        showterms();
    });

    //SHARE BUTTONS
    $('#shfb').click(function () {
        fbstatus();
    });

    $('#shtw').click(function () {
        twstatus();
    });

});


var __ajaxurl = '/ajax/disentropy/__sonetshare_disentropy.aspx'
var overlayData = null;

function fbstatus() {
    FB.getLoginStatus(function(response) {
            log(response);
      if(response.authResponse){
          getfbinfo(response.authResponse);
      }else{
          fblogin();
      }
    }, true);
}

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.userID, fbname: fbname, fblink: fblink, fbemail: fbemail },
            success: function (data) {

                overlayData = getIframe(data.url);
                $("#sonetdiv").dialog({ height: 500, title: 'Facebook Share Preview' });
                $('#sonetdiv').dialog("open")
                // jq('#sonetdiv').data('overlay').load();
            },
            async: false
        });

    });
}

function fblogin() {
    FB.login(function (response) {
        if (response.status == 'connected') {
            getfbinfo(response);
        } else {
            // user is not logged in
        }
    }, { scope: '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) {
        if (data.status == 'redirect') {
            window.location.href = data.url;
        }
        if (data.status == 'authed') {
            overlayData = getIframe(data.url);
            $("#sonetdiv").dialog({ height: 500, title: 'Twitter Share' });
            $('#sonetdiv').dialog("open")
            //   $('#sonetdiv').data('overlay').load();
        }
    });
}

function sendfb() {
    var fblink = "http://www.disentropy.com/?dtrk=520";
    var fbdescription = "Learn how disEntropy can help your business build a better website, implement new software to support your business processes, and advance your Internet marketing efforts. Plus, share our website with someone else and get a chance to win a professionally designed website for your own business.";
    var fbname = "Visit the disEntropy Website";
    var fbpicture = "http://www.disentropy.com/images/disentropy/fblogo.png";
    var fbcaption = ""

    hideShareButton();
    //FB.api('/me/feed', 'post', { message: shdata.fb_message }, function (response) {
    FB.api('/me/feed', 'post', { message: shdata.fb_message, link: fblink, description: fbdescription, name: fbname, picture: fbpicture, caption: fbcaption }, function (response) {
            log(response);
        if (!response || response.error) {
            alert('Facebook seems to be experiencing problems. Please try again later.');
            window.parent.closeOverlay();
        } else {
            $.post(__ajaxurl, { action: 'sendfb', msg: shdata.fb_message, type: shdata.type, lid: shdata.lid, uid: shdata.uid }, function (data) {
                if (data.status == "ok") {
                    //NEW CONFIRMATION MESSAGE HACK
                    confirmation = getIframe('/deconfirm-sonet');
                    window.parent.$("#sonetdiv").html(confirmation);
                    //window.parent.closeOverlay();
                }
            });
        }
    });
}

function sendtw() {
    hideShareButton();
    $.post(__ajaxurl, { action: 'sendtweet', msg: shdata.tw_message, type: shdata.type, lid: shdata.lid, uid: shdata.uid }, function (data) {
        if (data.status == 'ok') {
            //NEW CONFIRMATION MESSAGE HACK
            confirmation = getIframe('/deconfirm-sonet');
            window.parent.$("#sonetdiv").html(confirmation);
            //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 showterms() {
    var termslink = '/terms-and-conditions';
    overlayData = getIframe(termslink);
    $("#sonetdiv").html('');
    $("#sonetdiv").dialog({ height: 500, title: 'Terms & Conditions' });
    $('#sonetdiv').dialog("open")
}

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 hideShareButton() {
    $('.sharebtn').html('Please wait while your message is shared...');
}

function getIframe(url) {
    return '<iframe src="' + url + '" width="610" height="420px" frameborder="no" border="0" marginwidth="0" marginheight="0" allowTransparency="true"></iframe>';
}

function getTallIframe(url) {
    return '<iframe src="' + url + '" width="610" height="510px" frameborder="no" border="0" marginwidth="0" marginheight="0" allowTransparency="true"></iframe>';
}

/*function setMenuHover(MenuItemID) {
    $('#mi_' + MenuItemID).hoverIntent(function (event) {
        $('#mic_' + MenuItemID).dequeue().stop(true, true).slideDown('fast');
    },function () {
        $('#mic_' + MenuItemID).dequeue().stop(true, true).slideUp('fast');
    });
    $('#mic_' + MenuItemID).mouseenter(function () {
    $(this).parent().stop(true, true).slideUp('fast');
    });
}*/

/*******************
 * Error proof logger
 *******************/
function log(msg){
    if(typeof(console) != 'undefined'){
        console.log(msg);
    }
}

