// onload function
$(document).ready(function() {
    // refresh the count of characters
    addCounterField('retweetStatusRemaining','retweetStatus',108,'retweet-button');
    addCounterField('replyStatusRemaining','replyStatus',108,'reply-button');

    // adding a callback when pressing ESC in video description textarea
    $('#description').keydown(function(event) {
        if (event.keyCode == 27) { onClickCancelVideoDescriptionChange(); }

    });
    
    var showTab = getParameterFromUrl('showTab');
    if (showTab) { onClickTab(showTab,showTab+'-btn'); }
});

/*window.setDescriptionEventForAuthor = function() {
    if($('#description-display') && isAuthor()) {
        $('#description-display').mouseover(showEditableDescription);
    }
};*/

//When the user clicks on "Reply with screencast"
window.onClickReplyScreencast = function() {
    window.location = g_homeUrl+'/?reply_video_bid='+$('#replyVideoBid').val();
};

window.onClickRecord = function() {
    window.location = g_homeUrl;
};

window.onClickCopyUrl = function () {
    showNotificationBar('success','Link copied to the clipboard.');
    return $('#copyLinkUrl').val();
};

window.onClickCopyEmbed = function () {
    showNotificationBar('success','Embed code copied to the clipboard.');
    return $('#copyEmbedCode').val();
};

window.onClickEditDescription = function() {
    showEditableDescription();
    showDescriptionButtons();
};

window.onClickSaveVideoDescription = function() {
    //this.withFacebookInit(function() {
    //    FB.Connect.showPermissionDialog("publish_stream", function(x){
        
    screenjelly.saveVideo($('#video-bid').val(), $('#description').val(), $('#video-published').val(),
        // Success
        function(data) {
            $('#video-description').val($('#description').val()).html();
            $('#description-display').text($('#description').val()).html();
            hideDescriptionButtons();
            hideEditableDescription();
            showNotificationBar('success','The description of your video has been saved.');
        },
        // Error
        function(code, error) {
        }, true);
};

window.onClickCancelVideoDescriptionChange = function() {
    $('#description').blur();
    $('#description').val($('#video-description').val());
    hideDescriptionButtons();
    hideEditableDescription();
};

window.showDescriptionButtons = function() {
    //$('#description').text($('#description-display').text()).html();
    $('#description-buttons').show();
};

window.hideDescriptionButtons = function() {
    $('#description-buttons').hide();
};

window.showEditableDescription = function() {
    $('#description-display').hide();
    $('#description').show();
};

window.hideEditableDescription = function() {
    $('#description').hide();
    $('#description-display').show();
};

//When the user clicks on the icon to change the video status"
window.onClickChangePublishedStatus = function(videoBid, element) {
    openLoginIfNeeded('sign-in', function (success,data) {
        if (success) {
            var published = $(element).children('.public-img').is(':visible');

            // call status service
            ajaxCall({
                type: 'GET',
                url: g_updatePublishedStatusUrl,
                cache: false,
                data: {
                    videoBid: videoBid,
                    published: !published
                },
                onSuccess: function(data){
                    if ($(element).children('.private-img').is(':visible')) {
                        $(element).children('.private-img').hide();
                        $(element).children('.public-img').show();
                    } else {
                        $(element).children('.private-img').show();
                        $(element).children('.public-img').hide();
                    }
                },
                onError: function (code, error) {

                }
             });
        }
    });
};

//When the user clicks on "follow me on twitter"
window.onClickFollowMe = function(userBid) {
    openTwitterLoginIfNeeded(function (success,data) {
        if (success) {
            // call follow me service
            ajaxCall({
                type: 'GET',
                url: g_followUserUrl,
                cache: false,
                data: {
                    userBid: userBid
                },
                onSuccess: function(msg){

                },
                onError: function (code, error) {

                }
             });
        }
    });
};

window.onClickShare = function(service) {
    if (service == 'delicious') {
        window.open('http://delicious.com/save?v=5&amp;noui&amp;jump=close&amp;url='+encodeURIComponent(document.location)+'&amp;title='+encodeURIComponent(document.title), 'delicious','toolbar=no,width=550,height=550');

    } else if (service == 'digg') {
        window.open('http://digg.com/submit?url='+encodeURIComponent(document.location)+'&title='+encodeURIComponent(document.title)+'&media=news&topic=tech_news','Digg','scrollbars=yes,toolbar=no,width=975,height=550');

    } else if (service == 'stumbleupon') {
        window.open('http://www.stumbleupon.com/submit?url='+encodeURIComponent(document.location)+'&title='+encodeURIComponent(document.title), 'stumpleupon','scrollbars=yes,toolbar=no,width=950,height=550');

    } else if (service == 'google') {
        window.open('http://www.google.com/bookmarks/mark?op=add&bkmk='+encodeURIComponent(document.location)+'&title='+encodeURIComponent(document.title), 'GoogleBookmarks','scrollbars=yes,toolbar=no,width=800,height=550');

    } else if (service == 'friendfeed') {
        window.open('http://friendfeed.com/?url='+encodeURIComponent(document.location)+'&title='+encodeURIComponent(document.title), 'FriendFeed','scrollbars=yes,toolbar=no,width=800,height=550');

    } else if (service == 'myspace') {
        window.open('http://www.myspace.com/Modules/PostTo/Pages/?u='+encodeURIComponent(document.location)+'&t='+encodeURIComponent(document.title)+'&c=', 'MySpace','scrollbars=yes,toolbar=no,width=800,height=550');

    } else if (service == 'facebook') {
        window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(location.href)+'&t='+encodeURIComponent(document.title),'sharer','toolbar=0,status=0,width=626,height=436');
    }

    if ($.cookie('last_recorded_video_bid') == $('#videoBid').val()) {
        sendEvent('SHARE_VIDEO',$('#videoBid').val(), service, 'JustAfterCapture=true');
    } else {
        sendEvent('SHARE_VIDEO',$('#videoBid').val(), service, 'JustAfterCapture=false');
    }
};

//When the user clicks on "i like it"
window.onClickLikeIt = function() {
    openLoginIfNeeded('sign-in', function (success,data) {
        if (success) {
            // call contact service
            ajaxCall({
                type: 'GET',
                url: g_likeVideoUrl,
                cache: false,
                showSuccess: false,
                data: {
                    videoBid: $('#videoBid').val()
                },
                onSuccess: function(data){
                    showNotificationBar('success','Thanks for liking this video.');
                },
                onError: function (code, error) {
                }
             });
        }
    });
};

//When the user clicks on "Reply"
window.onClickReplyStatus = function() {
    $('#replyStatusError').html('');

    // make sure the text is not too long
    if($('#replyStatus').val().length > 108) { return false; }

    openTwitterLoginIfNeeded(function (success,data) {
        if (success) {
            blockButton($('#reply-button'), 'Please wait..');

            // call contact service
            ajaxCall({
                type: 'GET',
                url: g_replyVideoUrl,
                cache: false,
                data: {
                    status: $('#replyStatus').val(),
                    videoBid: $('#replyVideoBid').val()
                },
                onSuccess: function(data){
                    unblockButton($('#reply-button'));
                },
                onError: function (code, error) {
                    unblockButton($('#reply-button'));
                }
             });
        }
    });
};

// When the user clicks on "Send"
window.onClickShareVideoByEmail = function() {
    openLoginIfNeeded('sign-in', function(success, data) {
        if (success) {
            $('#shareEmailFrom-error').html('');
            $('#shareEmailTo-error').html('');
            $('#shareEmailNote-error').html('');
            var published = ($('#video-published').val() == 1);
            blockButton($('#send-email-button'), '<p>&nbsp;</p><p>Please wait..</p>');

            screenjelly.emailVideo($('#shareEmailVideoBid').val(), $('#shareEmailFrom').val(), $('#shareEmailTo').val(), 
                                $('#shareEmailNote').val(), published,
                                function(data){
                                    unblockButton($('#send-email-button'));
                                },
                                function (code, error) {
                                    unblockButton($('#send-email-button'));
                                });
            // call contact service
            /*ajaxCall({
                type: 'GET',
                url: g_emailVideoUrl,
                cache: false,
                data: {
                    'from': $('#shareEmailFrom').val(),
                    'to': $('#shareEmailTo').val(),
                    'video_bid': $('#shareEmailVideoBid').val(),
                    'note': $('#shareEmailNote').val()
                },
                onSuccess: function(data){
                    unblockButton($('#send-email-button'));
                },
                onError: function (code, error) {
                    unblockButton($('#send-email-button'));
                }
             });
             */
        } else {
            unblockButton($('#send-email-button'));
        }
    });
};

window.onClickReportAbuse = function() {
    updateCaptcha('reportAbuseCaptchaImg','reportAbuseCaptchaVerif');

    showPopup('report-abuse-popup');
};

window.onCancelReportAbuse = function() {
    hidePopup('report-abuse-popup');
};

window.onSendReportAbuse = function() {
    $('#reportAbuseCaptchaCodeError').html('');
    $('#reportAbuseCommentError').html('');

    blockButton($('#send-report-abuse'), '<p>&nbsp;</p><p>Please wait..</p>');

    // call contact service
    ajaxCall({
        type: 'GET',
        url: g_reportAbuseUrl,
        cache: false,
        data: {
            videoBid: $('#reportAbuseVideoBid').val(),
            comment: $('#reportAbuseComment').val(),
            catpchaCode: $('#reportAbuseCaptchaCode').val(),
            catpchaVerif: $('#reportAbuseCaptchaVerif').val()
        },
        onSuccess: function(data){
            hidePopup('report-abuse-popup');

            unblockButton($('#send-report-abuse'));
        },
        onError: function (code, error) {
            unblockButton($('#send-report-abuse'));
        }
     });
};

window.onClickRetweet = function() {
    $('#retweetStatus-error').html('');

    // make sure the text is not too long
    if($('#retweetStatus').val().length > 108) { return false; }

    openTwitterLoginIfNeeded(function (success,data) {
        if (success) {
            var published = ($('#video-published').val() == 1);
            blockButton($('#retweet-button'), '<p>&nbsp;</p><p>Please</p><p>wait..</p>');
            screenjelly.tweetVideo($('#retweetVideoBid').val(), $('#retweetStatus').val(), null, null, 
                function(data){
                    unblockButton($('#retweet-button'));
                },
                function (code, error) {
                    unblockButton($('#retweet-button'));
                },
                true);
        }
    });
};

window.onClickPostToFacebook = function() {
    openFacebookLoginIfNeeded(function (success,data) {
        if (success) {
            var published = ($('#video-published').val() == 1);
            blockButton($('#facebook-button'), '<p>&nbsp;</p><p>Please</p><p>wait..</p>');
            
            FB.Connect.showPermissionDialog("publish_stream", function(x){
                screenjelly.facebookPostVideo($('#video-bid').val(), $('#facebook-status-text').val(), null, null,
                    function(data){
                        //showNotificationBar('success', 'Your recording has been posted to your Facebook stream!');
                        unblockButton($('#facebook-button'));
                    },
                    function (code, error) {
                        unblockButton($('#facebook-button'));
                    },
                    true);   
                });
        }
    });
};

//When the user clicks on "Delete"
window.onClickDeleteVideo = function() {
    // show the confirmation popup
    showPopup('confirm-delete-popup');
};

window.onClickConfirmDeleteVideo = function() {
    openLoginIfNeeded('sign-in', function (success,data) {
        if (success) {
            var videoBid = $('#video-bid').val();

            // call delete service
            ajaxCall({
                type: 'GET',
                url: g_deleteVideoUrl,
                cache: false,
                data: {
                    videoBid: videoBid
                },
                onSuccess: function(msg){
                    // go to the user page
                    window.location = $('#user-page').val();
                },
                onError: function (code, error) {

                }
             });
        }
    });
};
