//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, Shabik user! I have reported this error, hopefully Shabik 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() {
        charCounter(this, $id('spQuickCounter'), 160);
    });

    $($("#admin-msg-td span")[0]).click(function(){
        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("Thank You for your feedback");
	      });
	  });

    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) { 
              if(!ProcessRPCResult(data))
				{
				  $('#taQuickSaying').val('');
				  $('#divSuccessPostMsg').show().fadeOut(6000);
				  $('#taQuickSaying').keyup();
			  }
              
            }
        });
    });
    $('#linkqUpload').click(function() {
        if($('#side-photo-up-div').html().length>0) {
          $('#side-photo-up-div').toggle();
          if($('#side-photo-up-div').css('display') == 'none')
            $(this).siblings('img').attr('src', '/images/arrow-right.gif');
          else
            $(this).siblings('img').attr('src', '/images/arrow-down.gif');
        }
        else {
          $('#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>');
          $(this).siblings('img').attr('src', '/images/arrow-down.gif');
        }
    });
});

var addFriend = function(friendName, thisObj) {
    $.ajax({
        type: 'POST',
        url:  '/controllers/friendCtrl.ashx',
        data: 'action=add&user_id=' + 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&user_id=' + 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?user_id='+ friendName;
};

var unblockFriend = function(friendName, thisObj) {
    $.ajax({
        type: 'POST',
        url:  '/controllers/friendCtrl.ashx',
        data: 'action=unblock&user_id=' + 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 user_id = $('#divFriendMenu').prev().attr('user_id');
              location.href = '/friends/user.aspx?user_id=' + user_id; 
          });
        }else if(count === 1) { //View Friend's photos
          $(this).children().click(function() {
              var user_id = $('#divFriendMenu').prev().attr('user_id');
              location.href = '/photos/listalbum.aspx?user_id=' + user_id; 
          });
        }
        else if(count === 2) { //View Friend's sayings
          $(this).children().click(function() {
              var user_id = $('#divFriendMenu').prev().attr('user_id');
              location.href = '/sayings/user.aspx?user_id=' + user_id; 
          });
        }        
        else if(count === 3) { //Send message
          $(this).children().click(function() {
              var user_id = $('#divFriendMenu').prev().attr('user_id');
              location.href = '/msgs/compose.aspx?user_id='+ user_id;
          });
        }
        else if(count === 4) { //Add as Friend
          $(this).children().click(function() {
              var user_id = $('#divFriendMenu').prev().attr('user_id');
              addFriend(user_id, null);
          });
        }
        else if(count === 5) { //Add as Friend
          $(this).children().click(function() {
              var user_id = $('#divFriendMenu').prev().attr('user_id');
              delFriend(user_id, null);
          });
        }
        else if(count === 6) { //Block a friend
          $(this).children().click(function() {
              $('#divFriendMenu').prev().attr('status', 'Blocked');
              var user_id = $('#divFriendMenu').prev().attr('user_id');
              blockFriend(user_id, null);
          });
        }
         else if(count === 7) { //Unblock a friend
          $(this).children().click(function() {
              $('#divFriendMenu').prev().attr('status', 'UnBlocked');
              var user_id = $('#divFriendMenu').prev().attr('user_id');
              unblockFriend(user_id, 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();
    };
}

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. Shabik have recorded it, and hopefully resolved it soon. Sorry for the error, please try again.")
        return true;
    }
    else if(xml=="103")
	{
        alert("النص الذي أدخلته يحتوي على كلام غير لائق، الرجاء تعديله بكلام  لائق");
		return true;
	}

    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 hint_hide(hint, a)
{
     $.post("/rpc/hint.ashx" ,{
        action:"Hide",
        hint:hint
     },
        function(xml) {
            ProcessRPCResult(xml);
            if(xml=="0")
            {
                $(a).parent().fadeOut(1000);
            }
    });
}

function notification_list_fetch(page)
{
    ajah('/rpc/notifications/list.aspx', "notification-div", {page:page}, function(){
        bind_home_delete_events("#notification-list > div");
    });
}

function notification_markall()
{
    $.post("/rpc/events/delete.ashx" ,{
        action:"delete_all"
    },
    function(xml) {
        $("#notification-div").fadeOut(500);
    });
}

function events_delete(event_id, a)
{
    ddd(event_id);
    $(a).unbind('click', events_delete);
    $.post("/rpc/events/delete.ashx" ,{
        id:event_id
    },
    function(xml) {
        i = parseInt($("#notification-count").text().replace("(", "").replace("(", ""));
        if(i==1){
            $("#notification-div").fadeOut(500);
        }
        else{
            $("#notification-count").text("(" + (i-1) + ")");
            $(a).parent().remove();
            if(!$("#notification-list .notification-item").length>0)
            {
                notification_list_fetch($("#notification-div").attr('title'));
            }
        }
    });
}

function bind_home_delete_events(selectExp)
{
 	$(selectExp).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){
         jQuery.facebox('<iframe src="/rpc/poke/create.aspx?username=' + 
                username
            + '" width="300px" height="80px" frameborder="0"></iframe>');
        },
        repoke:function(username, event_id, node){
            poke.create(username);
            events_delete(event_id, node.parentNode.previousSibling);
        }
    }
}();