// master.js
// MEEDEOR
// by Hunter Bridges


// Globals
    // Core
    var curSubnav = '';
    var disableKeyListeners = false;
    var timeSeekMode = false;
    var over_sidebar = false;
    var notifs_open = false;
    var overflow_y = '';
    var mousewheel_bound = false;

    // Notifications
    var numberCurrent = 0;
    var hovering_notifbadge = false;

    // Avatar Uploader
    var origWidth = 0;
    var origHeight = 0;
    var minWidth = 0;
    var minHeight = 0;
    var isUploading = false;
    var isSaving = false;
    var avatarToolActive = false;

    // View Entry
    var newCommentHover = false;
    var postDetails = "";

    //live search
    var current_livesearch_query;
    var new_livesearch_query;
    var browsing_results;
    var current_result;

    // facebook
    var fb_perms;

// Functions
    // Mouse Scrolling
    function getScrollLeft()
    {
            if( typeof( window.pageYOffset ) == 'number' ) {
                //Netscape compliant
                var scrollLeft = window.pageXOffset;
            } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
                //DOM compliant
                var scrollLeft = document.body.scrollLeft;
            } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
                //IE6 standards compliant mode
                var scrollLeft = document.documentElement.scrollLeft;
            }

            return scrollLeft;
    }
    function setScrollLeft(i)
    {
            $('html, body').animate({
                    scrollLeft: i
            },1);
    }
    function mouseWheel(e,delta)
    {
            if (!e) var e = window.event;
            var scroll = 0;
            var speed = 4;

            if ($.browser.safari)
             {
                 scroll = delta * speed;
             } else if ($.browser.mozilla) {
                 scroll = delta * 15 * speed;
             } else {
                 scroll = delta * 30 * speed;
             }
             
             scroll = scroll * -1;
            if (!over_sidebar)
            {
                window.scrollBy(scroll,0);
                /*
                if (scroll>=0 ){
                    wheelFilter(216);
                } else {
                  wheelFilter(-216) ;
                }*/
            }
    }
    function bottoms_out()
    {
        $('.infoArea, #usercardContentsHolder, #usercardContents').each(function () {
           if ($(window).height() > 608)
           {
               $(this).height($(window).height() - 486);
               if ($(this).hasClass('infoArea'))
                   {
                       $(this).height(($(window).height() - 486)/3);
                   }

               if ($(this).attr('id') == 'usercardContents')
                   $(this).height($(window).height() - 510);

               if ($(this).attr('id') == 'usercardContentsHolder')
                   $("#feedUsercard").height(432 + $(this).height() - 10);
           }
           else
               $(this).height(50);
        });
    }
    function pagescroll_off()
    {

       document.body.scroll = "no";
       document.body.style.overflowY = overflow_y;
       $('.vertical_page').height($(window).height()-54).css('overflow','hidden');
    }
    function pagescroll_on()
    {
        document.body.scroll = "yes";
        document.body.style.overflowY = overflow_y;
        $('.vertical_page').css('height','auto').css('overflow','visible');
    }
    // Misc
    function sizeHtml()
    {
            $("html").css('height',0).css('width',0);
            $("html").css('height',$(document).height()).css('width',$(document).width());
    }
    function hideNotifications()
    {
        notifs_open = false;
        $("#notif_bar").stop();
        $("#notif_bar").hide();

        if (!browsing_results)
            $("#feedstring_holder").show();
        
        $("#notif_bar").height(0);
        $("a#notifications_badge").removeClass('tabbed');
        document.body.scroll = "yes";
        document.body.style.overflowX = 'auto';
        document.body.style.overflowY = overflow_y;
        $('.vertical_page').css('height','auto').css('overflow','visible');
    }

    // URL Functions
    function url_encode (clearString) {
      var output = '';
      var x = 0;
      clearString = clearString.toString();
      var regex = /(^[a-zA-Z0-9_.]*)/;
      while (x < clearString.length) {
        var match = regex.exec(clearString.substr(x));
        if (match != null && match.length > 1 && match[1] != '') {
            output += match[1];
          x += match[1].length;
        } else {
          if (clearString[x] == ' ')
            output += '+';
          else if (clearString[x] == '\'' || clearString[x] == '.' || clearString[x] == '+'  || clearString[x] == '?'  || clearString[x] == '#'  || clearString[x] == '!'  || clearString[x] == '%')
            output += '';
          else {
            var charCode = clearString.charCodeAt(x);
            var hexVal = charCode.toString(16);
            output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
          }
          x++;
        }
      }
      return output;
    }

    function url_decode (encodedString) {
      var output = encodedString;
      var binVal, thisString;
      var myregexp = /(%[^%]{2})/;
      while ((match = myregexp.exec(output)) != null
                 && match.length > 1
                 && match[1] != '') {
        binVal = parseInt(match[1].substr(1),16);
        thisString = String.fromCharCode(binVal);
        output = output.replace(match[1], thisString);
      }
      return output;
    }
    String.prototype.trim = function () {
        return this.replace(/^\s*/, "").replace(/\s*$/, "");
    }

    // Notifications
    function buildNotifFeed()
    {
            var widthOfPosts = 162;
            var numberDisplayed = Math.floor($("#notif_bar").outerWidth()/widthOfPosts);
            //$('#notif_container').html('<p class="no_new">Loading...</p>');
            $.post("/notifications/html_feed",{length:numberDisplayed}, function(data){
                    if ($('#notif_container ul').html() != data)
                    {
                            $('#notif_container ul').html(data);
                            $('#notif_container').css('margin-left',0);
                            $("#notif_container a.tab.left").hide();
                            $("#notif_container a.tab.right").hide();

                            var widthOfPosts = 162;
                            var numberDisplayed = Math.floor($("#notif_bar").outerWidth()/widthOfPosts);

                            if ($("#notif_container ul li.notification").size() >= numberDisplayed)
                                $("#notif_container a.tab.right").show();
                    }
            });
    }
    function resetCurrentNotifs()
    {
        numberCurrent = 0;

        $('#notifications_badge').addClass("gray");
        $('#notifications_badge').html("00");
    }
    function checkNotifications()
    {
        var numberNew = 0;
        $.get("/notifications/count_new", function(data){
                numberNew = data * 1;
                $('#notifications_badge').html(data);

                if (numberNew == 0)
                {
                    $('#notifications_badge').addClass("gray");
                } else {
                    $('#notifications_badge').removeClass("gray");
                }
                
                animate_notifbadge();

                if (numberNew > numberCurrent)
                {
                        numberCurrent = numberNew;
                        buildNotifFeed(0);
                }
        });
        if ($(".newposts_button").size() && $(".prevPage").size() == 0)
        {
            var sinceId;

            if ($(".feedEntry:first").size())
                sinceId = $(".feedEntry:first").attr("id").replace('e_','');
            else
                sinceId = 0;

            $.post("/ajax_utils/count_feed_since",{feed:window.location.href, sinceId: sinceId}, function(data){
                    $('.newposts_button').html(data);
                    reveal_newposts();
            });
        }
    }
    function animate_notifbadge()
    {
        if (!$('#notifications_badge').hasClass('gray') && !hovering_notifbadge)
        {
            $('#notifications_badge').stop().animate({opacity:0},2500,'easeInOutQuart',function() {
                $('#notifications_badge').animate({opacity:1},2500,'easeInOutQuart');
            });
        }
    }

    // Analytics
    function loadAnalytics()
    {
            var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
            jQuery.getScript(gaJsHost + "google-analytics.com/ga.js", function(){
            _gat._getTracker("UA-4703198-5")._trackPageview();
            });
    }

    // Avatar Uploader
    function reset_uploader()
    {
        $("a#avatar_upload_link").html('Change Picture <div id="the_actual_uploader"></div>');
        $("#avatar_tool").html('');
        $("a#avatar_cancel").hide();
        $("#avatar_loading_graphic").hide();
        $("#avatar_upload_link").unbind('click',save_avatar);
        $("#avatar_upload_link").css('background-color','');
        $(".avatar_instructions").hide();
        $(".optional").show();
        isSaving = false;
        avatarToolActive = false;
        make_uploader();
    }
    function make_uploader()
    {
        if ($("#avatar_tool").size())
        {
            $.post("/ajax_utils/avatar_url", null, function (data) {
                    $("#avatar_tool").html('<div id="status_indicator"></div>');
                    $("#avatar_tool").append('<img src="'+data+'" style="display:none" onload="$(this).fadeIn(250)" id="avatar_preview" />');
                    init_upload();
            });
        }
    }
    function init_upload()
    {
            $.getScript("/js/AC_RunActiveContent.js",function() {
            $.getScript("/js/jQuery.uploader.js", function() {

                jQuery.uploader.backendScript = '/ajax_utils/upload_avatar';

                var oUpload = $("#the_actual_uploader").uploader ({
                    'swfURL'        : '/js/jQuery.uploader.swf',
                    'multiple'      : 'false'
                });

                jQuery.extend(oUpload.events, {
                    /**
                                     * SWF ready handler, used to bind the events the way YOU want.
                                     */
                                    uploaderReady: function() {
                                            //alert("ready");
                                                    this.setFilters([
                                                                                            {description: 'Image files (*.jpg,*.png)', extensions: '*.jpg;*.jpeg;*.png'}
                                                                                    ]);
                                                    this.setMaxFileSize(10485760);
                                                    this.setMaxQueueCount(1);
                                            },

                                    /**
                                     * File added handler
                                     */
                                    fileAdded: function(args) {
                                            this.upload(args.fileData.id, jQuery.uploader.backendScript);
                                            },

                                    queueStarted: function(args) {
                                    $("#avatar_preview").fadeOut(200);
                                            $("#avatar_upload_link").fadeTo(200,0.5);
                                            $("#status_indicator").html("");
                                            $("#status_indicator").width(0);
                                            isUploading = true;
                                            avatarToolActive = true;
                                            $("#avatar_loading_graphic").show();
                                            $('#usercardContentsHolder').css('visibility','visible');
            
                                    },

                                    fileUploadProgress: function(args) {
                                            $("#status_indicator").html(args.fileProgress.progress+"%");
                                            $("#status_indicator").stop();
                                            $("#status_indicator").animate({width:(args.fileProgress.progress/100) * (432 - 18)},100);
                                    },
                                    rollOver: function (args) {
                                            //$("#avatar_upload_link").show();
                                    },
                                    rollOut: function (args) {
                                            //$("#avatar_upload_link").hide();
                                    },

                                    /**
                                     * Triggered when a file is uploaded (or has an error)
                                     */

                                    /**
                                     * Triggered when a file is uploaded (or has an error)
                                     */
                                    fileUploadError: function(args) {
                                                    //
                                                    // You need to remove the file from the queue or else you can't upload any more!
                                                    this.remove(args.fileData.id);
                                                    $("#status_indicator").html("Upload error.");
                                                    $("#avatar_upload_link").fadeTo(200,1);
                                                    isUploading = false;
                                                    $("#avatar_loading_graphic").hide();

                                            },

                                    /**
                                     * Server data returned
                                     */
                                    fileUploadServerData: function(args) {
                                            if(args.serverData!="0") {
                                                isUploading = false;
                                                make_image_tool(args.serverData);
                                            }
                                            }
                            });
            });
        });
    }
    function make_image_tool(url)
    {
            $("#avatar_tool").append('<div id="viewport" style="display:none;"></div>');
            $("#avatar_tool #viewport").html('<img src="http://tmp.mdor.co/'+url+'" style="display:none;" />');
            $("#status_indicator").html("This may take a moment...");

            $("#avatar_tool #viewport img").load(function () {
                    $("#avatar_tool *:not(#viewport, #viewport *)").remove();
                    $("#avatar_tool #viewport").show();
                    init_image();
                    init_slider(url);
                    save_data();
            })
    }
    function init_image()
    {
            $("#avatar_tool #viewport img").draggable({stop: function () {
                    save_data();
            }});

            origWidth = $("#avatar_tool #viewport img").width();
            origHeight = $("#avatar_tool #viewport img").height();

            if (origWidth > origHeight)
            {
                    minHeight = 432;
                    minWidth = (minHeight / origHeight) * origWidth;
            } else {
                    minWidth = 432;
                    minHeight = (minWidth / origWidth) * origHeight;
            }

            $("#avatar_tool #viewport img").height(minHeight);
            $("#avatar_tool #viewport img").width(minWidth);
            $("#avatar_tool #viewport img").css("top",0 - (minHeight - $("#avatar_tool #viewport").height() - 18)/2);
            $("#avatar_tool #viewport img").css("left",0 - (minWidth - $("#avatar_tool #viewport").width())/2);
            $("#avatar_tool #viewport img").fadeIn(250);
            $("#avatar_tool").append('<div id="slider_container"></div>');
            contain_drag();

            $("#avatar_upload_link").bind('click',save_avatar);
            $("a#avatar_cancel").show();
    }
    function save_avatar(e)
    {
        if (!isSaving)
        {
            isSaving = true;
            $("#avatar_loading_graphic").show();

            $(this).fadeTo(200,0.5);
            $(this).html("Saving...");
            $(this).css('background-color','#999');
            $("#avatar_tool #viewport img").draggable("destroy");
            $("#avatar_tool #viewport img").css("cursor","auto");
            $("#avatar_tool #slider").remove();
            $("#avatar_tool #viewport").height(432);
            $(".avatar_instructions").fadeOut(250);
            $("a#avatar_cancel").hide();

            $.post('/ajax_utils/save_avatar',
                     {pic_height: $('input#pic_height').val(),
                      pic_width: $('input#pic_width').val(),
                      pic_top: $('input#pic_top').val(),
                      pic_left: $('input#pic_left').val(),
                      pic_tmpname: $('input#pic_tmpname').val(),
                      new_avatar: 'true'},
                      function (data) {
                        $("#avatar_upload_link").fadeTo(200,1);
                        hide_instruction_step(1);
                        isSaving = false;
                        $("#avatar_loading_graphic").hide();
                        $("#avatar_upload_link").unbind('click',save_avatar);
                        $("#avatar_upload_link").css('background-color','');
                        avatarToolActive = false;
                        reset_uploader();
                      });
        }
    }
    function init_slider(url)
    {
            $("#avatar_tool #slider_container").append('<div id="slider"></div>');
            $("#avatar_tool").append('<div id="save_crop"></div>');

            $("#save_crop").html('<input type="hidden" id="pic_height" name="pic_height" />');
            $("#save_crop").append('<input type="hidden" id="pic_width" name="pic_width" />');
            $("#save_crop").append('<input type="hidden" id="pic_top" name="pic_top" />');
            $("#save_crop").append('<input type="hidden" id="pic_left" name="pic_left" />');
            $("#save_crop").append('<input type="hidden" id="pic_tmpname" name="pic_tmpname" value="'+url+'" />');
            $("#save_crop").append('<input type="hidden" name="new_avatar" value="true" />');

            $("#avatar_tool #slider").slider({handle: '#slider-handle',
                                     min: 100,
                                     max: 400,
                                                     slide: function(e,ui) {
                                                            zoom_and_adjust(ui);
                                                     }
            });

            $("#avatar_loading_graphic").hide();
            $(".avatar_instructions").fadeIn(250);
            $(".optional").hide();
            
            $("#avatar_upload_link").fadeTo(200,1);
            $("#avatar_upload_link").html("Save Picture");
    }
    function save_data()
    {
            var coef = 432/432;

            $("#save_crop #pic_height").val($("#avatar_tool #viewport img").height() * coef);
            $("#save_crop #pic_width").val($("#avatar_tool #viewport img").width() * coef);
            $("#save_crop #pic_top").val($("#avatar_tool #viewport img").position().top * coef);
            $("#save_crop #pic_left").val($("#avatar_tool #viewport img").position().left * coef);
    }
    function zoom_and_adjust(ui)
    {
            var oldHeight = $("#avatar_tool #viewport img").height();
            var oldWidth = $("#avatar_tool #viewport img").width();

            $("#avatar_tool #viewport img").height(ui.value/100 * minHeight);
            $("#avatar_tool #viewport img").width(ui.value/100 * minWidth);

            $("#avatar_tool #viewport img").css("top",$("#avatar_tool #viewport img").position().top - ($("#avatar_tool #viewport img").height() - oldHeight)/2);
            $("#avatar_tool #viewport img").css("left",$("#avatar_tool #viewport img").position().left - ($("#avatar_tool #viewport img").width() - oldWidth)/2);

            if ($("#avatar_tool #viewport img").position().top > 0)
                    $("#avatar_tool #viewport img").css("top",0);
            else if ($("#avatar_tool #viewport img").position().top < 0 - ($("#avatar_tool #viewport img").height() - $("#avatar_tool #viewport").height() + 18))
                    $("#avatar_tool #viewport img").css("top",0 - ($("#avatar_tool #viewport img").height() - $("#avatar_tool #viewport").height() + 18));

            if ($("#avatar_tool #viewport img").position().left > 0)
                    $("#avatar_tool #viewport img").css("left",0);
            else if ($("#avatar_tool #viewport img").position().left < 0 - ($("#avatar_tool #viewport img").width() - $("#avatar_tool #viewport").width()))
                    $("#avatar_tool #viewport img").css("left",0 - ($("#avatar_tool #viewport img").width() - $("#avatar_tool #viewport").width()));

            save_data();

            contain_drag();
    }
    function contain_drag()
    {
            var offset = $("#avatar_tool #viewport").offset();
            var x1 = offset.left - $("#avatar_tool #viewport img").width() + $("#avatar_tool #viewport").width();
            var x2 = offset.left;
            var y1 = offset.top - $("#avatar_tool #viewport img").height() + $("#avatar_tool #viewport").height() + 18;
            var y2 = offset.top;

            $("#avatar_tool #viewport img").draggable('option','containment',[x1, y1, x2, y2]);
    }
    // Media Feed
    function set_feed_width()
    {
        var feedWidth = 0;
        $("#feedHolder").children().each(function() {
            if ($(this).css('display') !== 'none')
            {
                feedWidth += $(this).outerWidth(true);
            }
        });
        //var feedWidth = ($('.feedEntry').size() * 432 + $('.navTab').size() * 108 + $('#feedUsercard').size() * 450 + $('.instruction_step').size() * 450) - $('#feedHolder').outerWidth();
        //$('#feedHolder').width(feedWidth);
        if (feedWidth >= $(window).width())
            $("html, body").width(feedWidth);
        else
            $("html, body").width($(window).width());

        //$('#feedHolder').css('margin','0');
    }
    function reveal_newposts()
    {
        if ($(".newposts_button").html() != "" && $(".newposts_button").html() != "00" && $(".newposts_button").width() == 0)
        {
            var buttonLeft = 0;
            $("#feedHolder").children().slice(0,$("a.newposts_button").index()).each(function () {
                buttonLeft += $(this).innerWidth(false);
            });
            

            $("#feedHolder").children().slice($("a.newposts_button").index()+1,$("#feedHolder").children().size()).each(function () {
                $(this).animate({left:$(this).css('left').replace('px','')*1+36});
            });

            setTimeout(function(){
                $("a.newposts_button").css('left',buttonLeft);
                $("a.newposts_button").css('padding-right','3px');

                if ($('#feedUsercard').size())
                    $("a.newposts_button").css('border-right','18px solid #e6e6e6');

                $("a.newposts_button").animate({width:33},200,function() {
                    set_feed_width();
                    hide_instruction_step(2);
                });
            },100);

        }
    }
    // View Entry
    function largeMonitorFix()
    {
            var targetWidth;
            var targetMargin;

            targetWidth = 72 + 1124;
            targetMargin = 562 + 36;
            $("div.ghost").each(function () {

               $(this).width($(this).find('img').width());
            });
            $("#activePost, #activePost a#bigPicture").width($("div#activePost").find('img').width());
            $("#feedstring_holder").css('min-width',$("div#activePost").find('img').width());
            $("#feedstring_holder").css('margin-left',$("#feedstring_holder").width()/2 * -1);
            
            if ($("#activePost div.photoPost a img").size())
            {
                if ($("#activePost div.photoPost a img").outerWidth() >= 422)
                {
                    targetWidth += $("#activePost div.photoPost a img").outerWidth();
                    targetMargin += $("#activePost div.photoPost a img").outerWidth()/2;
                } else {
                    $("#activePost, #activePost div.photoPost, #activePost div.photoPost a").width(422);
                    $("#activePost div.photoPost a img").css('margin','auto');
                    targetWidth += 422;
                    targetMargin += 211;
                }
            }
            else
            { 
                targetWidth += 562;
                targetMargin += 562/2;
            }

            if ($("div.ghost.left div.ghostHider").size())
            {
                targetWidth += $("div.ghost.left div.ghostHider").outerWidth();
                targetMargin += $("div.ghost.left div.ghostHider").outerWidth();
            }
            else
            {
                targetWidth += 562;
                targetMargin += 562;
            }

            if ($("div.ghost.right div.ghostHider").size())
                targetWidth += $("div.ghost.right div.ghostHider").outerWidth();
            else
                targetWidth += 562;

           // if ($("#viewEntryWrapper").outerWidth() > targetWidth)
           // {
           //         $("#viewEntry").css("width","100%");
           // } else {
                    $("#viewEntry").css("width",targetWidth + "px");
           // }

            $("#viewEntry").css("margin-left","-"+targetMargin+"px");
    }
    function scrollTo(top)
    {
            if(location.hash == '')
            {
                    $('html,body').scrollTop(top);
            }
    }

    // Live Search
    function hideSearch()
    {
        if ($("#search_field").width() != 50) $("#search_field").animate({width:50},150,"easeOutQuart",function(){
            if ($(this).val() == "")
                $(this).val("Search").css('text-align','center');
        });

        browsing_results = false;
        current_result = 0;

        $("#search_delta").hide();
        $("#search_results").hide();

        if (!notifs_open)
            $("#feedstring_holder").show();
        
        $("#search_results ul li.result a").removeClass("current");
        pagescroll_on();
    }
    function queue_livesearch(search_query)
    {
        if (new_livesearch_query == search_query)
        {
            $("#search_field").addClass('loading');
            current_livesearch_query = $.post('/ajax_utils/livesearch',{query: search_query}, function (data) {
               if (data != "" && data != "0")
               {
                   $("#search_results").html(data);
                   $("#search_field").removeClass('loading');
                   $('#search_results').height($(window).height()-54);
                   pagescroll_off();
               } else if (data == "0")
               {
                   $("#search_results").html("");
                   $("#search_field").removeClass('loading');
                   $('#search_results').height(0);
                   pagescroll_on();
               }
           });

           new_livesearch_query = false;
        }
    }
    // New user tips
    function hide_instruction_step(tip_id)
    {
        if ($("#instruction_step"+tip_id).size() && $("#instruction_step"+tip_id).css('display') != 'none')
        {
            var shift_current = false;
            if ($("#instruction_step"+tip_id).hasClass("current"))
            {
                shift_current = true;
            }

            $("#instruction_step"+tip_id).fadeOut(200,function (){
                if (tip_id == 1 && $("#instruction_step2").size())
                {
                    $("#instruction_step2").animate({left: $("#instruction_step2").css("left").replace('px', '')-450},200);

                    if (shift_current)
                        $("#instruction_step2").addClass('current');
                }

                if (tip_id <= 2 && $("#instruction_step3").size())
                {
                    $("#instruction_step3").animate({left: $("#instruction_step3").css("left").replace('px', '')-450},200);

                    if (shift_current && tip_id == 2)
                        $("#instruction_step3").addClass('current');
                }

                setTimeout('set_feed_width()',200);
            });

            $.post('/ajax_utils/complete_intro_step',{step:tip_id});
        }
    }

    // facebook
    function save_session()
    {
            var session = FB.Facebook.apiClient.get_session();
            
            $.post('/ajax_utils/fb_savesession',{fb_sessid: session.session_key, fb_uid: session.uid}, function(data) {
                    refresh_fbc_widget();
            });
    }
    function check_fb_perms()
    {
            var permsString = '';
            FB_RequireFeatures(["CanvasUtil","Api","Connect","XFBML"], function(){
                FB.Connect.showPermissionDialog("offline_access,publish_stream", function(perms) {
               if (!perms) {
                 permsString = 'You do not have automatic publishing enabled.';
               } else {
                     permsString = 'You have automatic publishing enabled.';
               }

               save_session();
            });});
    }
    function fb_unlink()
    {
            $.post('/ajax_utils/fb_unlink',null, function(data) {
                    refresh_fbc_widget();
            });
    }
    function loadFBConnect()
    {
            refresh_fbc_widget();
            $("span#fbsync_toggle a").live("click", function () {
                    $.get('/ajax_utils/fbsync_toggle',null,function(data) {
                            $("span#fbsync_toggle").html(data);
                    });
            });
    }
    function init_fb()
    {
        $.getScript("/js/fb_api_0.4.js", function () {
                FB_RequireFeatures(["CanvasUtil","Api","Connect","XFBML"], function(){
                        FB.init("81f72f6b91965a9bf548ddbe5c8faf2c","/xd_receiver.htm");
                        //FB.Connect.ifUserConnected(check_fb_perms);
                });
        });
    }
    function callPublish(msg, attachment, action_link) {
      FB.ensureInit(function () {
        FB.Connect.streamPublish('', attachment, action_link);
      });
    }
    function publish_entry_from_view()
    {
            callPublish('',
                                    {
                                            'name':$('#postmeta_title').val(),
                                            'href':$('#postmeta_url').val(),
                                            'description':$('#postmeta_desc').val(),
                                            'media':[{
                                                    'type':'image',
                                                    'src':$('#current_photo').attr('src'),
                                                    'href':$('#postmeta_url').val()
                                            }]
                                    },
                                    null);

            return false;
    }
    function refresh_fbc_widget()
    {
        $.get('/ajax_utils/fbc_display', null, function (data) {
            $("#fbconnect_area").html(data);
            if (typeof FB == 'undefined')
            {
                init_fb();
            } else {
                FB_RequireFeatures(["CanvasUtil","Api","Connect","XFBML"], function() {
                    FB.XFBML.Host.parseDomTree();
                });
            }
        });
    }
    // Twitter
    var tw_signout_bound = false;

    function load_twitter()
    {
        refresh_tw_widget();
        $("span#twsync_toggle a").live("click", function () {
                $.get('/ajax_utils/twsync_toggle',null,function(data) {
                        $("span#twsync_toggle").html(data);
                });
        });
    }
    function tw_unlink()
    {
        $.post('/ajax_utils/tw_unlink',null, function(data) {
              refresh_tw_widget();
        });
    }
    function refresh_tw_widget()
    {
        $.get('/ajax_utils/tw_display', null, function (data) {
            $("#twitteranywhere_area").html(data);
        });
    }

    // sidebar
    function hide_sidebar()
    {
        $("#sidebar").stop();
        $("#sidebar").hide();
        $("#sidebar").css('width','0px');
        over_sidebar = false;
        document.body.scroll = "yes";
        document.body.style.overflowX = 'auto';
        document.body.style.overflowY = overflow_y;
        $('.vertical_page').css('height','auto').css('overflow','visible');
    }

// Core events
    $(document).ready(function () {

        // sidebar

        if ($('.vertical_page').size() > 0)
        {
           overflow_y = 'scroll';
        } else {
           overflow_y = 'auto';
        }

        document.body.style.overflowY = overflow_y;

        $("#sidebar").css('width','0px');
        $("#logo").mouseenter(function (e) {
            $("#sidebar").show();
            $("#sidebar").animate({
                width:162
            },250,'easeOutQuart');

           over_sidebar = true;
           hideNotifications();
           
           
           if (browsing_results || $("#search_field").width() > 54)
               $("#feedstring_holder").hide();

           document.body.scroll = "no";
           document.body.style.overflowX = 'hidden';
           document.body.style.overflowY = overflow_y;
           $('.vertical_page').height($(window).height()-54).css('overflow','hidden');
        });
        $(document).mouseleave(function (e) {
           if (over_sidebar)
           {
            hide_sidebar();
           }
        });
        
        $("#sidebar").mouseleave(function (e) {
           if (over_sidebar)
           {
            hide_sidebar();
           }
        });

        $("#sidebar a").click(function (e) {
            document.body.style.overflowY = 'scroll';
            $('.vertical_page').css('height','auto').css('overflow','visible');
        });
        $(document).scroll(function (e) {
            if ($(document).scrollTop() == 0)
            {
                $("#meedeor_home").show();
                $("#logo_inactive").hide();
            } else {
                $("#meedeor_home").hide();
                $("#logo_inactive").show();
                hideNotifications();
            }

            if (over_sidebar)
                scroll(0,0);
        });

	// Link auto meta
	$("a.nameMe").each(function (i, element) {
		var address = $(element).attr("href");
		$.post("/ajax_utils/url_meta",{address: address, output: 'title'}, function (data) {
			$(element).html(data);
		});
	});

        // Search
        $("#search_field").focus(function (e) {
            if ($(this).width() != 194) $(this).animate({width:194},0,"easeOutQuart");
            $("#search_field").css("text-align","left");
            
            if (!browsing_results)
            {
                $("#search_delta").fadeIn(150);
                $("#search_results").show();

                hideNotifications();
                $("#feedstring_holder").fadeOut(100);

                if ($("#search_results").html() != '')
                {
                    pagescroll_off();
                }
            } else {
               current_result = 0;
               browsing_results = false;
               $("#enterkey_directions").show();
               $("#enterkey_directions").animate({height:'18px',minHeight:'18px'},100);
               $("#search_results ul li.result a").removeClass("current");
            }
        });

        $("#search_field").blur(function (e) {
            //$(this).animate({width:50},150,"easeOutQuart");
            
            //if (!browsing_results)
            //{
               // $("#search_delta").hide();
               // $("#search_results").hide();
            //}
        });

        $("#search_results ul li a").live('keyup', function (e) {
           if (e.keyCode == 40)
           {
               if (browsing_results)
               {
                   if ($("#search_results ul li.result:gt("+current_result+")").size())
                   {
                       current_result++;
                       $("#search_results ul li.result a").removeClass("current");
                       $("#search_results ul li.result:eq("+current_result+") a").addClass("current").focus();
                   }
               }
           } else if (e.keyCode == 38) {
               if (browsing_results)
               {
                   if ($("#search_results ul li.result:lt("+current_result+")").size())
                   {
                       current_result--;
                       $("#search_results ul li.result a").removeClass("current");
                       $("#search_results ul li.result:eq("+current_result+") a").addClass("current").focus();
                   } else {
                       $("#search_field").focus().select();
                   }
               }
           }
        });

        $("#search_field").keyup(function (e) {
           if (e.keyCode == 40)
           {
               if ($("#search_results ul li.result").size())
               {
                   if (!browsing_results && !current_livesearch_query)
                   {
                       browsing_results = true;
                       current_result = 0;
                       $("#enterkey_directions").animate({height:'0px',minHeight:'0px'},100,function () {
                           $("#enterkey_directions").hide();
                       });

                       $("#search_results ul li.result:first a").addClass("current").focus();
                   }
               }
           } else if (e.keyCode == 13)
           {
               window.location.href = "/search/"+url_encode($(this).val());
           } else if (!(e.keyCode <= 40 && e.keyCode >= 36)) {
               var search_query = $(this).val().trim();

               if (current_livesearch_query)
               {
                   current_livesearch_query.abort();
                   current_livesearch_query = false;
               }

               new_livesearch_query = url_encode(search_query);
               setTimeout("queue_livesearch('"+url_encode(search_query)+"')",100);
           }
        });
        
        $(document).ajaxSuccess(function (e, xhl, settings) {
           if (xhl = current_livesearch_query)
           {
               current_livesearch_query = false;
           }
        });

	// Notifs
        $("a#notifications_badge").click(function () {
            $("#notif_bar").stop();

           if (notifs_open)
           {
                hideNotifications();
           } else {
               $("body").animate({scrollTop: 0}, 0);
               $("#notif_bar").show();

               document.body.scroll = "no";
               document.body.style.overflowX = 'hidden';
               document.body.style.overflowY = overflow_y;
               $('.vertical_page').height($(window).height()-54).css('overflow','hidden');

               $("a#notifications_badge").addClass('tabbed');
               $("#notif_bar").animate({height:$(window).height()-54},500,'easeOutQuart');
               notifs_open = true;
               
               $.get("/notifications/read",function (data) {
                    resetCurrentNotifs();
		});
           }
        });

        $(document).click(function (e) {
            if (!$(e.target).is("#notif_bar, #notifications_badge, #notif_bar *"))
            {
                hideNotifications();
            }

            if (!$(e.target).is("#search_field") && !$(e.target).is("#search_results *") && !$(e.target).is("#search_results"))
            {
                hideSearch();
            } else {
                pagescroll_off();
            }

            if (!$(e.target).is("#sidebar, #sidebar *"))
            {
                hide_sidebar();
            }

            if (notifs_open)
            {
                $("#feedstring_holder").fadeOut(100);
            }
        });
        $(window).resize(function (e) {
            if (notifs_open)
                $("#notif_bar").height($(window).height()-54);

            if (notifs_open || over_sidebar)
                $(".vertical_page").height($(window).height()-54);
        });
        
        // notifications
        $("#notif_container ul li:not(.right)").live("mouseenter", function (e) {
            $(this).addClass("hover");
        });
        $("#notif_container ul li:not(.right)").live("mouseleave", function (e) {
            $(this).removeClass("hover");
        });
	$("#notif_container").everyTime(5000,function(i) {
		checkNotifications();
	});
        $("#notifications_badge").mouseenter(function () {
            hovering_notifbadge = true;
            $(this).stop().animate({opacity:1},250);
        });
        $("#notifications_badge").mouseleave(function () {
            hovering_notifbadge = false;
        });
        $("#notifications_badge").everyTime(5000,function(i) {
            animate_notifbadge();
	});
        
	checkNotifications();
	buildNotifFeed();
        $("#notif_container a.tab").live("click",function () {
            var widthOfPosts = 162;
            var numberDisplayed = Math.floor($("#notif_bar").outerWidth()/widthOfPosts);
            var marginLeft = ($("#notif_container").css("margin-left").replace('px', '')) * 1;
             var toScroll = 0;

            if ($(this).hasClass("left"))
            {
                toScroll = marginLeft + (numberDisplayed - 1) * widthOfPosts;

                if (toScroll > 0)
                    toScroll = 0;
                 
                if (toScroll == 0)
                    $(this).hide();
                // left
            } else {
                // right
                toScroll = marginLeft - (numberDisplayed - 1) * widthOfPosts + (marginLeft==0?18:0);

                $("#notif_container a.tab.left").show();
                $("#notif_container a.tab.right").hide();

                //var numOnScreen = Math.floor((toScroll * -1) / widthOfPosts) % numberDisplayed;
                var leftNotifIndex = Math.floor((toScroll * -1) / widthOfPosts) + 1;
                var rightNotifIndex = Math.floor((toScroll * -1) / widthOfPosts) + numberDisplayed;
                var trueRight = $("#notif_container ul li.notification:last").index();
                //alert(numOnScreen);
                
                //if (numOnScreen == 0) numOnScreen = numberDisplayed;

                $("#notif_container").animate({marginLeft:toScroll}, 350, "easeOutQuart", function () {
                });

                if ($("#notif_container ul li.notification:eq("+rightNotifIndex+")").size() == 0)
                {
                    $.post("/notifications/html_feed",{left:$("#notif_container ul li.notification:eq("+trueRight+")").attr("id"),length:rightNotifIndex-trueRight}, function(data){
                        $('#notif_container ul').append(data);

                        //if (numOnScreen == 0) numOnScreen = numberDisplayed;
                        //if (numOnScreen == numberDisplayed)
                            $("#notif_container a.tab.right").show();
                    });
                } else {
                    $("#notif_container a.tab.right").show();
                }
            }

            $("#notif_container").animate({marginLeft:toScroll}, 350, "easeOutQuart", function () {});
        });

	// Text input auto clear
        $("#search_field").val("Search");
	$("input").each(function (i, element){
		$(element).data('defaultText',$(element).val());
	});
	$("input:text").focus(function () {
		if($(this).hasClass('noclear'))
		{
		}
		else
		{
		if ($(this).val() == $(this).data('defaultText'))
			$(this).val('');
		}
	});
        if ($.browser.safari)
        {
            $(".activity_bubble, #activity_switch").css('line-height','16px').css('margin-top','1px');
        }

        if ($("#feedstring_holder").size())
        {
            $("#feedstring_holder a").each(function (index, e) {
                $(this).css('z-index',$("#feedstring_holder a").size()-index);
            });
        }
	if ($('#feedHolder').size())
        {
            make_uploader();
            // Media feed is present
            $('.entryCaptionHolder, #usercardContentsHolder').hide();
            $('.postDetails').hide();
            $('#archiveLinks').hide();
            $('#topbar').addClass('fixed');

            //set_feed_width();

            // pix fix
            if ($.browser.mozilla)
                    $("div.feedEntry div.infoArea div.postDetails img").css("margin-top","2px");

            var currentPage = $('#currentPage').val();

            $('.feedEntry').mouseenter(function (e) {
                $('.postName').hide();
                $(this).children('.infoArea').children('.postDetails').show();
                $(this).find('.entryCaptionHolder').show();
            });

            $('.feedEntry').mouseleave(function (e) {
                $('.postName').show();
                $(this).children('.infoArea').children('.postDetails').hide();
                $(this).find('.entryCaptionHolder').hide();
            });

            // wheel
            if ($.browser.safari) {
                    sizeHtml();
                    $(window).resize(sizeHtml);
            }
            $(document).bind('mousewheel',mouseWheel);
            mousewheel_bound = true;

            $('#archiveOpener').click(function (e) {
                    $(this).hide();
                    $("#archiveLinks").show();
                    //mouseScrollCallback(e);
            });
            bottoms_out();
            $(document).scroll(function () {
               $('#topbar').css('top','-'+$(document).scrollTop()+'px');

               if ($(document).height() > $(window).height() && mousewheel_bound)
               {
                   $(document).unbind('mousewheel', mouseWheel);
                   mousewheel_bound = false;
               } else if ($(document).height() <= $(window).height() && !mousewheel_bound) {
                   $(document).bind('mousewheel', mouseWheel);
                   mousewheel_bound = true;
               }
            });

            $(window).resize(function () {
               if ($(document).height() > $(window).height() && mousewheel_bound)
               {
                   $(document).unbind('mousewheel', mouseWheel);
                   mousewheel_bound = false;
               } else if ($(document).height() <= $(window).height() && !mousewheel_bound) {
                   $(document).bind('mousewheel', mouseWheel);
                   mousewheel_bound = true;
               }

               bottoms_out();
            });
            if ($('#usercardArea').size())
            {
                $('#feedUsercard, #change_pic_helper').mouseover(function (e) {
                    $('#usercardContentsHolder').show();
                    $('#usercardContentsHolder').css('visibility','visible');
                });

                $('#feedUsercard, #change_pic_helper').mouseout(function (e) {
                    if (!avatarToolActive)
                        $('#usercardContentsHolder').css('visibility','hidden');
                });

                $('a.subscribe_to').click(function (e) {
                        $('#subscriptionsArea').html('Subscribing...');
                        $.post('/users/subscribe',{id: $(this).attr('id')}, function (data) {
                                $('#subscriptionsArea').html(data);
                        });
                });
                $('a.unsubscribe_from').click(function (e) {
                        $('#subscriptionsArea').html('Unsubscribing...');
                        $.post('/users/unsubscribe',{id: $(this).attr('id')}, function (data) {
                                $('#subscriptionsArea').html(data);
                        });
                });
                $("#admin_override").click(function (e) {
                        var flickr_id = prompt("Enter a new Flickr photo ID for this place:","");

                        if (flickr_id)
                        {
                                $.post('/ajax_utils/override_placecard',{
                                        geo: $(this).attr("title"), flickr_id: flickr_id
                                }, function (data) {
                                        //alert(data);
                                        location.reload(true);
                                });
                        }
                });
                if ($.browser.safari)
                    $("div#feedUsercard div#usercardContents div#subscriptionsArea a div").css('line-height','14px');

                $(".avatar_instructions").hide();
                $("#avatar_cancel").click(function () {
                   reset_uploader();
                });
            }


            $(".instruction_step a.hider").click(function (e) {
               hide_instruction_step($(this).parent(".instruction_step").attr("id").replace('instruction_step',''));
            });
            $(".instruction_step").mouseenter(function(e) {
               $(this).addClass('hover');
            });
            $(".instruction_step").mouseleave(function(e) {
               $(this).removeClass('hover');
            });

            if ($.browser.safari)
            {
                $('div#feedUsercard div#usercardContents div#subscriptionsArea a div').css('line-height','16px');
            }
	}

        if ($("#search_results_page").size())
        {
            //$(".search_col:last").find(".search_col_pad").css('margin-right','18px');
            $('a.subscribe_to').live('click',function (e) {
                    var container = $(this).parents('.subscription_area').html('<span class="small">Subscribing...</span>');
                    $.post('/users/subscribe',{id: $(this).attr('rel')}, function (data) {
                            container.html('<span class="small">'+data+'</span>');
                    });
            });
            //$('.subscription_area').hide();

            $('li#load_more_people a').live('click',function(){
                if (!$(this).hasClass('loading'))
                {
                    $(this).addClass('loading');

                    $.post(window.location.href,
                            {which:'people',ajax_mode:'true',skip:$(this).attr('rel'),page_size:$("#page_size").val()},
                            function (data) {
                                $('li#load_more_people').remove();
                                $('ul#people_results_list').append(data);
                                //$('.subscription_area').hide();
                                if ($.browser.safari)
                                {
                                    $("#search_results_page li .subscription_area a div").css('line-height','17px');
                                }
                            });
                }
            });

            if ($.browser.safari)
            {
                $("#search_results_page li .subscription_area a div").css('line-height','17px');
            }

            $('li#load_more_places a').live('click',function(){
                if (!$(this).hasClass('loading'))
                {
                   $(this).addClass('loading');
                   $.post(window.location.href,
                        {which:'places',ajax_mode:'true',skip:$(this).attr('rel'),page_size:$("#page_size").val()},
                        function (data) {
                            $('li#load_more_places').remove();
                            $('ul#places_results_list').append(data);
                        });
                }
            });
        }
        // Arrow Keys
	$(document).keydown(function (e) {
		if (!disableKeyListeners)
		{

			/*if ($.browser.msie || $.browser.mozilla || $.browser.opera)
			 	var scrollLeft = document.documentElement.scrollLeft;
			else if ($.broswer.safari)
				var scrollLeft = document.body.scrollLeft;*/

			var scrollLeft = getScrollLeft();

			if (e.keyCode == 37)
			{

				if ($('#feedHolder').size())
				{
                                    set_feed_width();
					if (scrollLeft > 486)
						setScrollLeft(scrollLeft - 432);
					else if (scrollLeft <= 486 && scrollLeft > 0)
						setScrollLeft(0);
					else {
						if ($(".prevPage").size()) document.location = $(".prevPage").attr('href');
					}
				} else {
					if ($(".prevPage").size()) document.location = $(".prevPage").attr('href');
				}
			}
			else if (e.keyCode == 39)
			{
				if ($('#feedHolder').size())
				{
                                    set_feed_width();
                                    var adjSL = (scrollLeft + $("#topbar").width());
					if (adjSL < $('#feedHolder').width() - 432)
                                            {
						setScrollLeft(scrollLeft + 432);
                                            }
					else if (adjSL >= $('#feedHolder').width() - 432 && adjSL < $('#feedHolder').width()) {
						setScrollLeft($('#feedHolder').width());
					} else {
						if ($(".nextPage").size()) window.location = $(".nextPage").attr('href');
					}
				} else {
					if ($(".nextPage").size()) window.location = $(".nextPage").attr('href');
				}
			}
		}
	});

	$("input, textarea").focus(function () {
		disableKeyListeners = true;
	});

	$("input, textarea").blur(function () {
		disableKeyListeners = false;
	});
        
        // twitter widget
        if ($("#twitteranywhere_area").size())
        {
            load_twitter();
        }
        // fb widget
        if ($("#fbconnect_area").size())
        {
            loadFBConnect();
        }

        
        
        // Account Settings
        if ($("#account_settings").size())
        {
            
            $('#big_cancel').click(function () {
                 window.location.href = window.location.href;
            });
            $('#big_save').click(function () {
                 $('#account_settings input[type=submit]').click();
            });

            $('#password').keypress(function () {
                    $("#password_again").removeAttr("disabled");
                    $('#password_again').removeClass('disabled');
            });

            $("#the_controls").hide();
            $("#account_page input, #account_page textarea").change(function () {
               $("#the_controls").show();
            });
            $("#account_page input, #account_page textarea").keyup(function () {
               $("#the_controls").show();
            });

        }

        // View Entry
        if ($("#viewEntry").size())
        {
            $("#timeAndControls").hide();
            
            $("a.extractedLink").each(function (i, element) {
                    var address = $(element).attr("href");

                    $.post("/ajax_utils/url_meta",{address: address}, function (data) {
                            $(element).children("#swappable").html(data);
                    });
            });
            $(window).resize(function () {
                    largeMonitorFix();
            });
            $("#activity_switch").click(function () {
               $("html,body").animate({scrollTop:$(document).height()},250);
               $("html,body").scrollLeft(0);
            });
            $("#activity_switch, #loc_icon").mouseenter(function () {
                $(".caption, #statsBox #postUserName").stop();
                $(".caption, #statsBox #postUserName").fadeTo(100,0.3);
            });

            $("#activity_switch, #loc_icon").mouseleave(function () {
                $(".caption, #statsBox #postUserName").stop();
                $(".caption, #statsBox #postUserName").fadeTo(100,1);
            });

            $("#postInformation").hide();
            $(".commentDetails").hide();
            $("a.submit").click(function (e) {
               $(this).parents("form").submit();
            });
            $(".comment").mouseenter(function(e) {
                $(this).find(".commentDetails").show();
            });
            $(".comment").mouseleave(function(e) {
                $(this).find(".commentDetails").hide();
            });
            $(".box").mouseenter(function (e) {
                    if (!newCommentHover)
                    $(this).children("#postInformation").show();
                    $(this).children("#postUserName").children("#timeAndControls").show();
            });
            $(".box").mouseleave(function (e) {
                    $(this).children("#postInformation").hide();
                    $(this).children("#postUserName").children("#timeAndControls").hide();
                    $("a.delete_button").parents("span").children("span.confirm").hide();
                    $("a.delete_button").show();
            });
            $(".edit_post").click(function (e) {
                    $("#editField").show().width($("#activePost").innerWidth());
                    if ($("#statsBox").innerHeight()-30 > 46)
                    {
                        $("#editField textarea").height($("#statsBox").innerHeight()-30);
                    }
                    $("#editField").children("form").children("textarea").width($("#activePost").innerWidth()-130).focus();
                    $("#editField").children("form").children("a.submit").show();
            });

            $("#newComment").click(function (e) {
                    $("#postCommentField").children("form").children("textarea").val("");
                    $("#postCommentField").width($("#activePost").innerWidth()).show();
                    $("#postCommentField").children("form").children("textarea").width($("#activePost").innerWidth()-130).focus();
            });
            $("#newCommentInstructions").hide();
            $("#newComment").mouseenter(function (e) {
                    newCommentHover = true;
                    $("#newCommentInstructions").show();
            });
            $("#newComment").mouseleave(function (e) {
                    newCommentHover = false;
                    $("#newCommentInstructions").hide();
            });
            $(".cancelButton").click(function (e) {
                    $(this).parents("div:first").hide();
            });

            $("textarea").keydown(function (){$(this).change()});
            $("textarea").keyup(function (){$(this).change()});
            $("#postCommentField textarea").change(function () {
                    if ($(this).val().length > 0)
                    {
                            $(this).parents("form").children("a.submit").show();
                    } else {
                            $(this).parents("form").children("a.submit").hide();
                    }
            });

            $("span.confirm").hide();
            $("a.no").click(function() {
                    $("span.confirm").hide();
                    $("a.delete_button").show();
            });
            $("a.delete_button").click(function () {
                    $(this).hide();
                    $(this).parents("span:first").children("span.confirm").show();
            });

            scrollTo(36);
            if ($.browser.mozilla)
                    largeMonitorFix();

            if ($("#activePost div.photoPost").size())
            {
                    $("#activePost div.photoPost a:first img").load(function () {
                            largeMonitorFix();
                    });
            } else
                    largeMonitorFix();

            $("#postCommentField a.submit").hide();
        }
        
        // Analytics
	loadAnalytics();

    });