﻿//When document finish loading
$(document).ready(function() {
    $.ajaxSetup({
      error : function(xml) { 
          if(xml.status==403)
              redirectLogin();
          else if(xml.status==500)
              alert("Oops - Unexpected Page Error Encounted. Sorry, Morange user! I have reported this error, hopefully Morange team will fix it soon.");
      }
    });

    //-------------------------------------Top Menu---------------------------------------
    var isFirst = true;
	var currentTab;
    $('#topmenu li').each(function() {
        $(this).mouseover(function() {
          $(this).css('background-color', '#666');
        });
        $(this).mouseout(function() {
          $(this).css('background-color', 'transparent');
        }); 
        
        if(isFirst) {this.className = 'selected';isFirst = false;}
        $(this).click(function(e) {
            if (!e) var e = window.event;
              e.cancelBubble = true;
            if (e.stopPropagation) e.stopPropagation();
      
            this.className = 'selected';  
            if (currentTab==this) {
                $(currentTab).find('.dropdown-menu-wrapper').toggle();
            }
            else {
                $(this).siblings().attr('class', '');
                if(currentTab)$(currentTab).find('.dropdown-menu-wrapper').hide();
                currentTab = this;
                $(currentTab).find('.dropdown-menu-wrapper').toggle();     
                
                $(this).find('div.dropdown-menu li').mouseover(function() {
                  $(this).css('background-color', '#666');
                });
                $(this).find('div.dropdown-menu li').mouseout(function() {
                  $(this).css('background-color', '#1A1A1A');
                });       
            }
        });
    });
    //Make Drop down menu disappear when click on document body
    $(document.body).click(function() {
      $('#topmenu > li').attr('class', '').find('.dropdown-menu-wrapper').hide();
      if($("#divFeedback")[0] && $.trim($("#divFeedback").val()) == '')
        $("#divFeedback").val($('#fMsg').html()).bind('click', ClearFeedback);
    });
    //---------------------------------------------------------------------------------
          
    $('#taQuickSaying').keyup(function() {
        if(_userID==2569846 | _userID == 2569851 | _userID== 2569838 | _userID==2569826)
            charCounter(this, $id('spQuickCounter'), 300);
        else
            charCounter(this, $id('spQuickCounter'), 160);
    });

    $($("#admin-msg-td span")[0]).click(function(){
        if(_userID==0 && $("#admin-msg-td span")[0])
            redirectLogin();

        if($('#admin-msg-div').css('display') != 'none') 
        {
            $("#admin-msg-div").slideUp(function(){
                $("#admin-msg-bar").show();
            });
            
            $("#admin-msg-img").attr('src', '/images/arrow/right_grey.png');
        }
        else
        {
            $("#admin-msg-bar").hide();
            $("#admin-msg-div").slideDown();
            $("#admin-msg-img").attr('src', '/images/arrow/down_grey.png');
            $("#divFeedback").focus();
        }
    });
		      
    function ClearFeedback(e) {
      if (!e) var e = window.event;
        e.cancelBubble = true;
      if (e.stopPropagation) e.stopPropagation();
      
      $('#fMsg').html($("#divFeedback").val());
		  $("#divFeedback").val('').unbind('click', ClearFeedback);
	  }
	  $("#divFeedback").click(ClearFeedback);

	  $("#btnFeedback").click(function(){
		  var d = $("#divFeedback");
		  var msg = d.val();
		  d.val("Submitting...");
		  $.post("/controllers/feedback.ashx",{
              msg:msg
	        },function(xml){
			  d.val(xml);
	      });
	  });

    BindMenuBox();

    //--------------------------------------------------------------------------------------
    $('#linkqSaying').click(function() {
        $('#divQuickSaying').toggle();
        if($('#divQuickSaying').css('display') == 'none') 
          $(this).siblings('img').attr('src', '/images/arrow-right.gif'); 
        else
        {
            $(this).siblings('img').attr('src', '/images/arrow-down.gif');
            $('#taQuickSaying').focus();
        }
          
        $('#taQuickSaying').val('');
    });
    
    $('#btnPostQuickSaying').click(function() { 
        var msg = $('#taQuickSaying').val();
        var isReplied = 0;
        var replyMsgId = 0;
        var photo = '';
        $.ajax({
            type: 'POST',
            url:  '/controllers/sayingCtrl.ashx',
            data: 'action=create&msg=' + encodeURIComponent(msg) + '&isReplied='+ isReplied +'&replyMsgId=' + replyMsgId +
                  '&fromSource=0&photo=' + photo + '&t=' + timestamp(),
            success: function(data) { 
              $('#taQuickSaying').val('');
              $('#divSuccessPostMsg').show().fadeOut(6000);
              $('#taQuickSaying').keyup();
            }
        });
    });
    
    function click_side_btn(btn, name)
    {
        if($('#' + name + '_div').html().length>0) {
          $('#' + name + '_div').toggle();
          if($('#' + name + '_div').css('display') == 'none')
            $(btn).siblings('img').attr('src', '/images/arrow-right.gif');
          else
            $(btn).siblings('img').attr('src', '/images/arrow-down.gif');
        }
        else {
          $('#' + name + '_div').html("<p>&nbsp;</p>");
          $(btn).siblings('img').attr('src', '/images/arrow-down.gif');
          return true;
        }
        return false;
    }

    $('#notifications_btn').click(function() {        
        if(click_side_btn(this, "notifications")) {
          notifications_fetch(0);
          $("#notifications_count").html("");
        }
    });

    $('#requests_btn').click(function() {
        if(click_side_btn(this, "requests")) {
          requests_fetch(0);
        }
    });

    $('#linkqUpload').click(function() {
        if(click_side_btn(this, "side-photo-up")) {
            $('#side-photo-up_div').html('<br /><iframe src="/rpc/photos/create.aspx" width="160px" height="140px" id="side-photo-up-frame" name="side-photo-up-frame" scrolling="no" frameborder="0"></iframe>');
        }
    });
});

var addFriend = function(friendName, thisObj) {
    $.ajax({
        type: 'POST',
        url:  '/controllers/friendCtrl.ashx',
        data: 'action=add&username=' + encodeURIComponent(friendName),
        success: function(xml) { 
           ProcessRPCResult(xml);
           s = eval("(" + xml + ")");
           if(s.status.charAt(1) == '0')
               location.href = '/friends/main.aspx?list=Following';
           else
               location.href = '/friends/main.aspx?list=Buddy';
        }
    });
};

var delFriend = function(friendName, thisObj) {
    $.ajax({
        type: 'POST',
        url:  '/controllers/friendCtrl.ashx',
        data: 'action=delete&username=' + encodeURIComponent(friendName),
        success: function(xml) { 
           ProcessRPCResult(xml);
           location.href = '/friends/main.aspx?list=Following';
        }
    });
};

var blockFriend = function(friendName, thisObj) {
    location.href = '/friends/confirm-block.aspx?username='+ friendName;
};

var unblockFriend = function(friendName, thisObj) {
    $.ajax({
        type: 'POST',
        url:  '/controllers/friendCtrl.ashx',
        data: 'action=unblock&username=' + encodeURIComponent(friendName) + '&t=' + timestamp(),
        success: function(xml) { 
           ProcessRPCResult(xml);
           location.href = '/friends/main.aspx?list=Blocked';
        }
    });
};

//This function is ues to retrieve a list of friends from server
var getBlockFriendList = function() {
    $.ajax({
        type: 'POST',
        url:  '/rpc/friends/list.aspx',
        data: 'action=getBlockedList&pageIndex=1&t=' + timestamp(),
        success: function(xml) {
            ProcessRPCResult(xml);
            $('#frn_divBlockedFriends').html(xml);
        }
    });
};


function BindMenuBox(){
    if (!$('#divExpandFMenu').length)
    {
        return false;
    }

    var count = 0;
    $('#divFriendMenu ul.menu li').each(function() {
        if(count === 0) { //View Friend's friends
          $(this).children().click(function() {
              var friendUName = $('#divFriendMenu').prev().attr('title');
              location.href = '/'+friendUName + '/friends/'; 
          });
        }else if(count === 1) { //View Friend's photos
          $(this).children().click(function() {
              var friendUName = $('#divFriendMenu').prev().attr('title');
              location.href = '/' + friendUName+'/photos/';
          });
        }
        else if(count === 2) { //View Friend's sayings
          $(this).children().click(function() {
              var friendUName = $('#divFriendMenu').prev().attr('title');
              location.href = '/' + friendUName +'/sayings/';
          });
        }        
        else if(count === 3) { //Send message
          $(this).children().click(function() {
              var friendUName = $('#divFriendMenu').prev().attr('title');
              location.href = '/msgs/compose.aspx?UserName='+ friendUName;
          });
        }
        else if(count === 4) { //Add as Friend
          $(this).children().click(function() {
              var friendUName = $('#divFriendMenu').prev().attr('title');
              addFriend(friendUName, null);
          });
        }
        else if(count === 5) { //Add as Friend
          $(this).children().click(function() {
              var friendUName = $('#divFriendMenu').prev().attr('title');
              delFriend(friendUName, null);
          });
        }
        else if(count === 6) { //Block a friend
          $(this).children().click(function() {
              $('#divFriendMenu').prev().attr('status', 'Blocked');
              var friendUName = $('#divFriendMenu').prev().attr('title');
              blockFriend(friendUName, null);
          });
        }
         else if(count === 7) { //Unblock a friend
          $(this).children().click(function() {
              $('#divFriendMenu').prev().attr('status', 'UnBlocked');
              var friendUName = $('#divFriendMenu').prev().attr('title');
              unblockFriend(friendUName, null);
          });
        }
        count++;
    });

    $('#divExpandFMenu').click(function(e) {
        if (!e) var e = window.event;
	        e.cancelBubble = true;
	      if (e.stopPropagation) e.stopPropagation();

        $('#divFriendMenuBox').show();
        $('#divFriendMenu').insertAfter($(this).parents('div.user-info-box')).toggle();
        if($('#divFriendMenu').css('display') == 'none') {
            $(this).parent().removeClass('active'); 
        }
        else {
            $(this).parent().addClass('active');
        }
        
        var status = $(this).parents('div.user-info-box').attr('status');
        if(!status)
        {
              $('#divFriendMenu ul:eq(1) > li:eq(1)').hide();
              $('#divFriendMenu ul:eq(1) > li:eq(2)').hide();
              $('#divFriendMenu ul:eq(1) > li:eq(3)').hide();
              $('#divFriendMenu ul:eq(1) > li:eq(4)').hide();
        }
        else
        {
            if(status.charAt(2) != '0') {
              $('#divFriendMenu ul:eq(1) > li:eq(3)').hide();
              $('#divFriendMenu ul:eq(1) > li:eq(4)').show();
            }else {
              $('#divFriendMenu ul:eq(1) > li:eq(3)').show();
              $('#divFriendMenu ul:eq(1) > li:eq(4)').hide();
            }
            
            if(status.charAt(0) == '0') {
              $('#divFriendMenu ul:eq(1) > li:eq(1)').show();
              $('#divFriendMenu ul:eq(1) > li:eq(2)').hide();
            }
            else{
              $('#divFriendMenu ul:eq(1) > li:eq(1)').hide();
              $('#divFriendMenu ul:eq(1) > li:eq(2)').show();
            }
        }
    });

    $('#divExpandFMenu')[0].onmouseover = function() {
        $('#divFriendMenuBox').show();
    };
}
var hashPrefix = "#_";
var newPageCount = 0;
var pageHistory = [];
var currentHash = location.hash;

function ajah(url, divname, param, callback){
    show_loading_msg(divname);
    $.post(url,param,function(xml){
        if(!ProcessRPCResult(xml))
            $("#" + divname).html(xml).css({height:"auto"});
        if(callback)callback();
    });
}


function show_loading_msg(divname){    
    h = $("#" + divname).height();
    $("#" + divname).html('<center><img src="/images/ajaxing.gif" /> ' + "Loading...</center>").css({height:h+"px"});
}

//this function is use to rate saying
var rating = function(url, itemId, itemType, rate, spanObj, msg) {
    var tmp;
    var p=spanObj.parent();
    tmp = p.html();
    var count = parseInt(spanObj.html()) +1;

    p.html('<img src="/images/ajaxing.gif" />');
    $.post(url ,{
        action:'rating',
        itemId:itemId,
        rate:1,
        itemType: itemType
    },
    function(xml) {
        ProcessRPCResult(xml);
        if(xml == 1) {
            p.html(tmp);
            jQuery.facebox('<h2>'+msg+'</h2>');
        }else
        {
            p.html('<span>' + count + '</span> <img src="/images/rated.png" />');
        }
    });
}

function bind_delete_events(selectExp)
{
	$(selectExp).hover(
        function(){
            $view($(this).find(".d")[0]);
        },
        function(){
            $noview($(this).find(".d")[0]);
        }
    );
}

function redirectLogin() {
  location.href = "/login.aspx?LoginRequired=True&ReturnUrl=" + $currenturl();
}

function ProcessRPCResult(xml)
{
    if(xml=="2")
    {
        redirectLogin();
        return true;
    }
    else if(xml=="101")
    {
        alert("A unexpected error occurred. Morange have recorded it, and hopefully resolved it soon. Sorry for the error, please try again.")
        return true;
    }
    else if(xml=="103")
        alert("The content you published contains illegal or uncivil language");

    return false;
}

function BindUserBox(divName)
{
    if($('#divFriendMenuBox').length == 0)
    {
      $('#MemuDiv')[0].innerHTML = MemuDiv;
      BindMenuBox();
    }

    if(divName)
    {
        path = "#" + divName + " div.user-info-box div.user-info img";
    }
    else
        path = "div.user-info-box div.user-info img";

   $(path).each(function() {
        this.onmouseover = function() {
            if(this.title != '' && ($('#divFriendMenu').css('display') == 'none' || this.title != _title)
            && $('#divFriendMenu').css('display') == 'none') {
                _title = this.title;
                
                $('#divFriendMenuBox').insertAfter($(this).parent().parent());
                $('#divFriendMenuBox div.friend-menu-inner-box').removeClass('active'); 
                
                $('#divFriendMenuBox').show();
                $('#divFriendMenu').hide();
                
                $('#divFriendMenuBox')[0].onmouseout = function() {
                    if($('#divFriendMenu').css('display') == 'none')
                        $(this).hide();
                };
            }
        };
   });

   $(document.body).click(function() {
        $('#divFriendMenu').hide();
        $('#divFriendMenuBox').hide();
   }); 
}

function showAvatar48(img, obj)
{
    newHTML = '<div style="padding: 5px; background-color: #FFF; border: 1px solid #888;">'
    newHTML = newHTML + '<div align="center" style="padding: 2px 2px 2px 2px;">';
    newHTML = newHTML + '<img src="' + img + '" border="0"/></div>';
    newHTML = newHTML + '</div>';
    var trailimageid = document.getElementById("trailimageid");
    if(trailimageid == null)
    {
        $("body").append('<div id="trailimageid"></div>');
        trailimageid = document.getElementById("trailimageid");
        trailimageid.style.position = "absolute";
    }
    trailimageid.style.display = "inline";
    trailimageid.style.left = (getLeft(obj) + 10) + "px";
    trailimageid.style.top = (getTop(obj) + 20) + "px";
    trailimageid.innerHTML = newHTML;
}

function hideAvatar48(img, obj)
{
    var trailimageid = document.getElementById("trailimageid");
    if(trailimageid != null)
    {
        trailimageid.style.display = "none"
        trailimageid.innerHTML = "";    
    }
}

function hint_hide(hint, a)
{
     $.post("/rpc/hint.ashx" ,{
        action:"Hide",
        hint:hint
     },
        function(xml) {
            ProcessRPCResult(xml);
            if(xml=="0")
            {
                $(a).parent().fadeOut(1000);
            }
    });
}

function notifications_fetch(start)
{
    ajah('/rpc/notifications/list.aspx', "notifications_div", {start:start}, function(){
        $("#notifications_div .unread").css("background-color","yellow").animate({ 
            backgroundColor: "#FFF"
        }, 3000 );
    });
}

function requests_fetch(start)
{
    ajah('/rpc/requests/list.aspx', "requests_div", {start:start}, function(){
        bind_home_delete_requests("#requests_div .request-item");
    });
}



function request_delete(id, a)
{
    $.post("/controllers/requestCtrl.ashx" ,{
        action:"ignore",
        id:id
    },
    function(xml) {
        i = parseInt($("#requests_count").text().replace("(", "").replace("(", ""));
        $(a).parent().remove();
        if(i==1){
            $("#requests_count").text("");
            $("#requests_div").find(".static-paging").remove();
        }
        else{
            $("#requests_count").text("(" + (i-1) + ")");
            requests_start = $("#requests_start").val();
            if(i>requests_start)
            {
                $.post("/rpc/requests/list.aspx",{start:requests_start - 1, count:1},
                  function(xml) {
                    $("#requests_div").find(".static-paging").before(xml);
                    bind_home_delete_requests("#requests_div .request-item");
                });
            }
            if((i-1)==requests_start)
            {
                $("#requests_div").find(".static-paging img[src='/images/next.gif']").parent().css("visibility","hidden");
            }
        }
    });
}

function bind_home_delete_requests(selectExp)
{
 	$(selectExp).parent().hover(
        function(){
            $(this).find(".x").show();
        },
        function(){
            $(this).find(".x").hide();
        }
    );
}

function pre(b)
{
	t=b.value.substring(b.value.lastIndexOf(".")+1);
    t=t.toLowerCase();
	if(t!="jpg"&&t!="gif"&&t!="png")
	{
		alert("Please only upload jpg/png/gif format image");
		b.value="";
	}
    else
    {
        i = parseInt(b.id.substring(4)) + 1;
        if((!$$("file" + i)) && i<6)
        {
            $(b).parent().append('<br><input name="file' + i + '" type="file" id="file' + i + '" onchange="pre(this);" size="' + b.size + '" />');
            if(window!=window.parent)
            {
              window.parent.document.getElementById("side-photo-up-frame").height = document.body.scrollHeight + 10;
            }
        }
    }
}

//==============charcount=================//
var charcount =  function(){
    return {
        setup: function (id, max_length){
            var exceeded = false;
            $("#" + id).keyup(function(){
                if(this.value.length > max_length)
                {
                    $(this).addClass("input-warning");
                    $("#" + id + "Hint").show();
                    exceeded = true;
                }
                else
                {
                    if(exceeded)
                    {
                        $(this).removeClass("input-warning");
                        $("#" + id + "Hint").hide();
                        exceeded = false;
                    }
                }
            });
        }
    }
}();

//==============charcount=================//
var abuse_report =  function(){
    return {
        report_photo: function (){
            jQuery.facebox('<iframe src="/rpc/reports/create.aspx?id=' + 
                urlList[photos_current_photoindex][0]
            + '" width="380px" height="180px" id="report-frame" scrolling="no" frameborder="0"></iframe>');
        }
    }
}();

//==============tagline=================//
var old_tagline;
var old_tagline_cmd;
function edit_tagline(cmd, b){
    if(cmd != b.innerHTML)
    {
        old_tagline = $("#tagline").text();
        old_tagline_cmd = b.innerHTML;
        b.innerHTML = cmd;
        $("#tagline").html("<textarea id='personalMsg' name='personalMsg' style='width:80px'>" + old_tagline + "</textarea>");
        $("#cancel_edit_tagline").show();
        $("#personalMsg").focus();
    }
    else
    {
        $.post("/controllers/profile.ashx",{personalMsg:$("#personalMsg").val()},
            function(xml) {
                $("#edit_tagline").html(old_tagline_cmd);
                $("#tagline").html($("#personalMsg").val());
                $("#cancel_edit_tagline").hide();
        });    
    }    
};

function cancel_edit_tagline(){
    $("#edit_tagline").html(old_tagline_cmd);
    $("#tagline").html(old_tagline);
    $("#cancel_edit_tagline").hide();
};


//==============poke=================//
var poke = function(){
    return {
        create:function(username, pid){
         jQuery.facebox('<iframe src="/rpc/poke/create.aspx?username=' + 
                username
            + '&pid=' + pid + '" width="400px" height="140px" frameborder="0"></iframe>');
        },
        repoke:function(username, event_id, node, pid){
            poke.create(username, pid);
        }
    }
}();

function ShowNews(i)
{
    i = i - 1;
    $("#admin-news-div").find('p').hide();
    $($("#admin-news-div").find('p')[i]).fadeIn();
}

//============= box ================//
function showbox(url, width, height)
{
    if(!width)width = 400;
    if(!height)height = 400;
    jQuery.facebox('<iframe src="' +  url
            + '" width="' + width + 'px" height="' + height + 'px" frameborder="0"></iframe>');
}