$(document).ready(function() {
    $("#blorg form").submit(function() {
        var value = $('#update')[0].value,
        twit = $('#publish_twitter').attr('checked') ? 1 : 0;
        $.post('/__transact/update.php', {update: value, publish_twitter: twit}, function(data) {
            if(data) {
                //$('<div class="section">' + data + '</div>').prependTo('#broadcast>div');
                $('<div class="section">' + data + '</div>').prependTo(window.broadcastPanel);
            }
        });
        $('#update')[0].value = "";
        $('#no-updates-ever').hide();
        return false;
    });
    $("#blorg h2 a").click(function() {
        var that = this;
        if(this.innerHTML == 'Use Real Name') {
            $("#blorg h2 span").load("/__transact/use_name_handle.php?name=1", function(data) {
                if(data) {
                    that.innerHTML = 'Use Handle';
                }
            });
        }
        else {
            $("#blorg h2 span").load("/__transact/use_name_handle.php?name=0", function(data) {
                if(data) {
                    that.innerHTML = 'Use Real Name';
                }
            });
        }
        return false;
    });
    (function() {
        if($("#user-title a").length > 0) {
            var defaultUserTitle = $("#user-title span").html(),
            defaultUserTitleAction = true;

            $("#user-title a").click(function() {
                if(this.innerHTML == "Save") {
                    var value = $("#user-title span input")[0].value, that = this;
                    $("#user-title span").load("/__transact/change_user_title.php?title=" + escape(value), function(data) {
                        if(data) {
                            that.innerHTML = "Edit User Title";
                            defaultUserTitle = data;
                        }
                    });
                }
                else {
                    var html = $("#user-title span").html();
                    $("#user-title span").html('<input type="text" value="'+html+'">');
                    this.innerHTML = "Save";
                }
                return false;
            });
            $("#user-title").click(function() {
                defaultUserTitleAction = false;
            });
            $(document.body).click(function() {
                if($("#user-title span input").length > 0 && defaultUserTitleAction) {
                    $("#user-title span").html(defaultUserTitle);
                    $("#user-title a").html("Edit User Title");
                }
                defaultUserTitleAction = true;
            });
        }
    })();
    $(".dialog,.dialog-degrades").dialog({
        autoOpen: false,
        width: 400,
        buttons: {
            "Ok": function() { 
                $(this).dialog("close"); 
            }
        }
    });
    $(".open-dialog,.open-dialog-degrades").click(function() {
        var id = this.href.split("#")[1];
        $("#" + id).dialog("open");
        return false;
    });
    $(".open-dialog,.open-dialog-degrades").wTooltip({
        style: false,
        content: 'pop-up',
        id: 'wtooltip',
        offsetX: -12,
        offsetY: 20
    });
    if($("#splitter").length > 0) {//causing too much recursion
        $.getScript("/js/splitter-1.5.js", function() {
            $("#splitter").splitter({
                type: "h",
                initA: true
            });
        });
    }
    $(".expandable dl:not(.open) dt").toggle(function() {
        $(this).parent('dl').addClass("open");
    }, function() {
        $(this).parent('dl').removeClass("open");
    });
    $(".expandable dl.open dt").toggle(function() {
        $(this).parent('dl').removeClass("open");
    }, function() {
        $(this).parent('dl').addClass("open");
    });
    $("#edit-outline a").click(function() {
        $("#main-text").hide();
        $("#edit-outline").hide();
        $("#save-outline,#cancel-save-outline").css("display", "inline");
        $("#outline .mceEditor").css("display", "block");
        return false;
    });
    $("#save-outline").click(function() {
        $("#outline form").submit();
        return false;
    });
    if($('#story_edit').length > 0) {
        var unload_by_save_event = false;
        window.onunload = function(e) {
            if(!unload_by_save_event && $('#section_real_ids').length > 0) {
                $.ajax({
                    url: '/__transact/uncheck-sections.php?s=' + $('#section_real_ids').attr('value'),
                    async: false
                });
            }
        }
        $('#story_edit').submit(function() {
            unload_by_save_event = true;
        });
        (function(){
            var scriptOpened = false, response = true;
            $("#edit-page a.edit").click(function(){
                var editlink = this, requested_sections = '', first = true;
                $('#script .story-section').each(function() {
                    var comma = (first) ? '' : ',', split = this.id.split('_');
                    requested_sections += comma + split[1];
                    first = false;
                });
                $.post('/__transact/check-out-sections.php', {
                    requested_sections: requested_sections,
                    story_id: window.story_id
                }, function(data) {
                    if(data) {
                        scriptOpened = true;
                        var dataset = data.split(']:::['), html = '';
                        for(var i = 1; i < dataset.length; i++) {
                            html += dataset[i];
                        }
                        if($(".mceEditor").length > 0) {
                            $('#script .inner').hide();
                            $(".mceEditor").css("display", "block");
                            //alert('yes1');
                            $(editlink).hide();
                            $("#edit-page a.save,#edit-page a.cancel").show();
                            if($('input#section_real_ids').length > 0) {
                                $('input#section_real_ids').attr('value', dataset[0]);
                            }
                            else {
                                $('<input type="hidden" id="section_real_ids" name="section_real_ids" value="' + dataset[0] + '" />').appendTo('#story_edit');
                            }
                            $('#mce_0').tinymce().execCommand('mceSetContent',false,html);
                        }
                        else {
                            var iId = setInterval(function() {//loop until the editor exists
                                if($(".mceEditor").length > 0) {
                                    $('#script .inner').hide();
                                    $(".mceEditor").css("display", "block");
                                    $(editlink).hide();
                                    $("#edit-page a.save,#edit-page a.cancel").show();
                                    if($('input#section_real_ids').length > 0) {
                                        $('input#section_real_ids').attr('value', dataset[0]);
                                    }
                                    else {
                                        $('<input type="hidden" id="section_real_ids" name="section_real_ids" value="' + dataset[0] + '" />').appendTo('#story_edit');
                                    }
                                    $('#mce_0').tinymce().execCommand('mceSetContent',false,html);
                                    clearInterval(iId);
                                }
                            },1);
                        }
                    }
                    else {
                        alert('There are no sections available here for editing.  Someone else has checked them out and is working on them.  Please try again later.')
                    }
                });
                return false;
            });
            $("#edit-page a.save").click(function() {
                $("#story_edit").submit();
                return false;
            });
            $('#edit-page a.cancel').click(function() {
                unload_by_save_event = true;//no need to waste an AJAX call, since this click does what we need anyway
                return true;
            });
            function ping() {
                if(scriptOpened && response) {
                    response = false;
                    $.post('/__transact/ping-checkout.php', {section_list: $('input[name=section_real_ids]').attr('value'), story_id: story_id},function(data) {
                        if(data) {
                            response = true;
                        }
                    });
                }
            }
            $(document).mousemove(function() {//this isn't working inside the IFRAME though (TODO)
                ping();
            });
            $(document).keyup(function() {//also not working inside the IFRAME (TODO)
                ping();
            });
        })();
    }
    $(".highlight").click(function() {
        this.select();
    })
    $("a.popopen").click(function() {
        var size = this.rel.split(','),
        scrollbars = ($(this).hasClass('scrollbars')) ? ',scrollbars=1' : '',
        popup = window.open(this.href, this.name, "width=" + size[0] + ",height=" + size[1] + scrollbars),
        width = $(window).width(),
        height = $(window).height(),
        xPos = ((Math.floor(width / 2) - Math.floor(size[0] / 2)) < 0) ? 0 : Math.floor(width / 2) - Math.floor(size[0] / 2),
        yPos = ((Math.floor(height / 2) - Math.floor(size[1] / 2)) < 0) ? 0 : Math.floor(height / 2) - Math.floor(size[1] / 2);
        popup.moveTo(xPos,yPos);
        return false;
    });
    $("textarea").focus(function() {
        $(this).css("border", "1px solid #bc5d2b");
    });
    $("textarea").blur(function() {
        $(this).css("border", "1px solid #636669");
    });
});

$(document).ready(function() {
    var bodyDefault = true;
    $('#profile-pic-span').hover(function(){
        $('#upload-profile-pic-button').show();
    }, function() {
        $('#upload-profile-pic-button').hide();
    });
    $('#upload-profile-pic-button').click(function() {
        $('#upload-profile-pic').show();
        return false;
    });
    $('#upload-profile-pic form').submit(function() {
        $('#upload-profile-pic').hide();
    });
    $('#upload-profile-pic').click(function() {
        bodyDefault = false;
    });
    $(document.body).click(function() {
        if(bodyDefault) {
            $('#upload-profile-pic').hide();
        }
        bodyDefault = true;
    });
});

$(document).ready(function() {
    $('#my-stories-list.personal .synopsis a.edit').click(function(){
        var id = $(this).attr('href'), story_id = id.split('_')[2];
        $(id + ' .synopsis').hide();
        if($(id + ' .update').length == 0) {
            $('<dd class="update"><p><textarea rows="20" style="width:100%;"></textarea></p><p><input class="save" type="button" value="Save"></p></dd>').appendTo($(id + ' dl'));
            $(id + ' .update .save').click(function() {
                var synopsis = $(id + ' .update textarea').val();
                $.post('/__transact/update-synopsis.php', {
                    story_id: story_id,
                    synopsis: synopsis,
                    try_manage: 'try1'
                }, function(data) {
                    if(data) {
                        $(id + ' .synopsis-content').html(data);
                    }
                    $(id + ' .update').hide();
                    $(id + ' .synopsis').show();
                });
            });
        }
        $(id + ' .update textarea').val($(id + ' .synopsis-content').html().replace(/<br \/>/g, '').replace(/<br>/g, ''));
        $(id + ' .update').show();
        return false;
    });
});
