
var sendMessageForm = '<div id="${divid}" class="replyBox ui-widget ui-widget-content " style="display:none">'
                       +'<form name="${formid}" id="${formid}" method="post" action="inbox.html">'
                        +'<input type="hidden" value="${action}" name="action" />'
                           +'<input type="hidden" value="${receiver_id}" name="receiver_id" />'
                           +'<input type="hidden" value="${did}" name="did" />'
                           +'<input type="hidden" value="2" name="ajax" />'
                           +'<input type="hidden" value="2" name="showhtml" />'
                           +'<p class="left smallBlock">'
                           +'${send_to_field}'
                           +'</p>'
                           +'<p class="left smallBlock">'
                           +'<label>Subject: </label>'
                           +'<input size="32" class="text ui-state-default ui-corner-all" type="text" value="" name="message_subject" placeholder="Enter a Subject" />'
                           +'</p>'
                           +'<p class="left smallBlock">'
                           +'<label>Message: </label>'
                           +'<textarea cols="60" rows="8" class="ui-state-default ui-corner-all" name="message_text" placeholder="Enter a Message"></textarea>'
                           +'</p>'
                           +'<p class="left smallBlock" >'
                           +'<input type="submit" class="jqButton" value="Send" name="btnSend" />&nbsp;&nbsp;'
                           +'<input type="button" class="jqButton" value="Cancel" name="btnCancel" />'
                           +'</p>'
                        +'</form></div>';
						
function genRandomId(){
   var minValue = 1000000;
   var maxValue = 9999999;
   var random_id = '';
   do{
       random_id = $.randomBetween(minValue, maxValue);
       return random_id;
   }
   while( $("[id*='"+random_id+"']").length == 0 );
}

// INBOX
function deleteMessage(obj){
    var id = $(obj).attr('id').replace(/del-message-/, "");

    var url = String($(obj).attr('href').split("?",1));
    var myparams = getparams($(obj).attr('href'));
    
    var paramsStr = '';
    $(myparams).each(function(i){
        paramsStr += myparams[i]+',';
    });
    
    var params = $.evalJSON('{'+paramsStr+'}');
    var parentBox = $(obj).parent().parent();
    
    //debuglog(params);
    /*
    var send = {};
    send.ajax = "2";
    send.showhtml = "2";
    send.action = "delete_message";

    if(obj.attr('rel')=='this'){
        send.onebyone = 1;
    }
    else{
        send.onebyone = 0;
    }
    send.mid = $('input#mid').val();
    if($("input#this_mid"+id).length!=0){
        send.this_mid = $("input#this_mid"+id).val();
    }

    var encoded = $.toJSON(send);
    var params = $.evalJSON(encoded);
    */
    //debuglog(paramsStr);
    $.get( url, params, function(res){
        var data = $.evalJSON(res);
        var is_err = false;
        var system_message = '';
        if( data.msg=='true' ){
            system_message = 'Message deleted';
			
            if(params.onebyone==1){
                $(obj).parent().fadeOut(1000, function(){
                    $(this).remove();     
                    parentBox.find('.replyMessage:odd').removeClass('news_content_hover');
                    parentBox.find('.replyMessage:even').addClass('news_content_hover');
                });
            }
            else{
                $(obj).parents(".MessageBox").prev('h3').fadeOut(1000, function(){$(this).remove();});
                $(obj).parents(".MessageBox").fadeOut(1000, function(){$(this).remove();});
            }
        }
        else{
			is_err = true;
            system_message = "Message wasn't deleted";
        }

		show_stack_bottomleft(is_err,system_message);
    });
    
}

function showReplies(obj){
    var $icon = $(obj).find('span.ui-icon');
    var patt = /\d/g;
        
    var id = $(obj).parent().find("input[name='um_id']").val();
        
        if( $icon.hasClass('ui-icon-triangle-1-e') ){
            $(obj).addClass('ui-state-active');
            
            $icon.removeClass('ui-icon-triangle-1-e')
            $icon.addClass('ui-icon-triangle-1-s');
            $(obj).parent().parent().parent().children('.replyMessage').children().css('opacity',0);
            $(obj).parent().parent().parent().children('.replyMessage').fadeIn(300, function(){
                $(this).children().animate({
                    opacity:1
                },400);
            });
            $(obj).parent().parent().parent().children('.replyMessage:even').addClass('news_content_hover');
            $(obj).parent().parent().parent().children('.replyMessage:odd').removeClass('news_content_hover');
            $icon.parent().attr('original-title','Hide replies');
            $(obj).attr('id','hide-replies-'+id);  
        }
        else{
            $(obj).removeClass('ui-state-active');

            $icon.removeClass('ui-icon-triangle-1-s')
            $icon.addClass('ui-icon-triangle-1-e');
            $(obj).parent().parent().parent().children('.replyMessage').children().animate({opacity:0},400,function(){
                $(this).parent().fadeOut(300);
            });
            //$(obj).parent().parent().parent().children('.replyMessage').slideUp(300);
            $icon.parent().attr('original-title','Show replies');
            $(obj).attr('id','show-replies-'+id); 
        }
}

function readMessage(obj){
    var $mailicon = $(obj).find('span.ui-icon');
    var id = $(obj).attr('id').replace(/read-message-/, "");
    //debuglog(id);
    var $headericon = $(obj).parent().parent().parent().prev('h3').find("span[id^='ui-accordion-read-icon-"+id+"']");
    //debuglog($headericon.attr('class'));
    
    var send = {};
    send.ajax = "2";
    send.showhtml = "2";
    send.action = "read";
    send.mid = id;
    var encoded = $.toJSON(send);
    var params = $.evalJSON(encoded);
    $.get('inbox.html', params, function(returned_data){
        //debuglog(returned_data);
        $mailicon.removeClass('ui-icon-mail-closed');
        $mailicon.addClass('ui-icon-mail-open');
        $mailicon.parent().addClass('ui-state-active');
        $headericon.removeClass('ui-icon-mail-closed');
        $headericon.addClass('ui-icon-mail-open');
        $headericon.parent().addClass('ui-state-active');
        $mailicon.parent().attr('id','read-icon-'+send.mid);

        $mailicon.parent().attr('original-title','message is read');
        $(".inboxWidget span:not(.ui-icon)").data('checkInbox').recheck();
    });
}

function replyToMessage(obj){

   if(  $.cookie($(obj).attr('id')+'-contactFormId')==null || $.cookie($(obj).attr('id')+'-contactFormId')=='' ){
       var temp_contactid = genRandomId();
       $.cookie($(obj).attr('id')+'-contactFormId', temp_contactid,{path: '/', expires: 1});
   }

   var contactFormId = $.cookie($(obj).attr('id')+'-contactFormId');
   var divid = 'replyBox-'+contactFormId+'-'+$(obj).attr('id');
   var formid ='replyForm-'+contactFormId+'-'+$(obj).attr('id');

   if( !obj.hasClass('ui-state-active') ){
       
       var did = obj.parent().find("input[name='did']").val();
       var parent_id = obj.parent().find("input[name='um_id']").val();
       var $replyBox = $('<div id="'+divid+'" class="replyBox ui-widget ui-widget-content " style="display:none"></div>');
       var $replyForm = $('<form name="'+formid+'" id="'+formid+'" method="post" action="inbox.html"></form> ')
       //var to = obj.parent().parent().parent().find('h6 p.message-footer a').html().split(" - ");
       
       $replyForm.append(  '<input type="hidden" value="reply-to-message" name="action" />'
                           +'<input type="hidden" value="0" name="reply_to_uid" />'
                           
                           +'<input type="hidden" value="'+did+'" name="did" />'
                           +'<input type="hidden" value="'+parent_id+'" name="parent_id" />'
                           +'<input type="hidden" value="0" name="is_parent" />'
                           +'<input type="hidden" value="2" name="ajax" />'
                           +'<input type="hidden" value="2" name="showhtml" />'
                           +'<p class="smallFullBlock">'
                           +'<label>Reply to the last message:</label>'
                           +'</p>'
                           +'<p class="smallFullBlock">'
                           +'<label>Subject: </label>'
                           +'<input size="32" class="text ui-state-default ui-corner-all" type="text" value="" name="message_subject" placeholder="Enter a Subject" />'
                           +'</p>'
                           +'<p class="smallFullBlock">'
                           +'<label>Message: </label>'
                           +'<textarea cols="70" rows="8" class="ui-state-default ui-corner-all" name="message_text" placeholder="Enter a Message"></textarea>'
                           +'</p>'
                           +'<p class="smallFullBlock" >'
                           +'<input type="submit" class="jqButton" value="Send" name="btnSend" />&nbsp;&nbsp;'
                           +'<input type="button" class="jqButton" value="Cancel" name="btnCancel" />'
                           +'</p>'
        );
      
      $replyBox.append($replyForm);
      //$(obj).parent().parent().after($replyBox);
      var $afterEl;
      if( $(obj).parent().parent().parent().find(".replyMessage").length != 0 ){
          $afterEl = $(obj).parent().parent().parent().find(".replyMessage:last");
      }
      else{
          $afterEl = $(obj).parent().parent();
      
      }
      $afterEl.after($replyBox).parent().find('#'+divid).addClass('rounded-r4');
      var uidsArr = $('#'+divid).parent().find("input[name^='to_uid']");

      var reply_to_uid;
      $(uidsArr).each(function(i){
            if($(this).val() != $('#my_uid').val()){
                reply_to_uid = $(this).val();
            }
      });
      //debuglog(reply_to_uid);
      $('#'+formid).find("[name='reply_to_uid']").val(reply_to_uid);

      /*
      obj.parent().next().after($replyBox).parent().find('#'+divid).corner({
            tl: {radius: 4},
            tr: {radius: 4},
            bl: {radius: 4},
            br: {radius: 4},
            antiAlias:true
      });
      */
     
      $('#'+divid).slideFadeToggle(300,'linear',function(){
          $(obj).addClass('ui-state-active');
      });

      $("#"+divid+" input[name='btnCancel']").live('click',function(e){
            $('#'+divid).slideFadeToggle(300,'linear',function(){
                $(this).remove();
                $(obj).removeClass('ui-state-active');
            });
      });

      $("#"+formid).validate({
         rules:{
            message_subject: {
                required:true,
                maxlength:50
            },
            message_text:{
                required:true,
                maxlength:300
            }
        },
        messages:{
            message_subject:{
                required:"Please enter the subject of your message",
                maxlength:"The subject should be less then 50 characters"
            },
            message_text:{
                required:"Please enter the text of your message",
                maxlength:"The text should be less then 300 characters"
            }
        },
        submitHandler: function(form) {
            $(form).ajaxSubmit(ajaxoptions);

        },
        onfocusout: false,
        onkeyup: false,
        onsubmit: true,
        success: "",
        errorClass: "invalid",
        errorElement: "em",
        errorPlacement: function(error, element) {
            var label = $("label[for='"+element.attr('name')+"']");
            label.append(error);
        },
        debug: false
      });
   }
   else{
       $('#'+divid).slideFadeToggle(300,'linear',function(){
                $(this).remove();
                $(obj).removeClass('ui-state-active');
       });
   }
}

function sendToUser(obj){
   var contactFormId, contactFormIdOld, temp_contactid;
   var totalHeight, startHeight, divHeight, divPadding = 30;

   if(  $.cookie($(obj).attr('id')+'-contactFormId')==null || $.cookie($(obj).attr('id')+'-contactFormId')=='' ){
       temp_contactid = genRandomId();
       $.cookie($(obj).attr('id')+'-contactFormId', temp_contactid,{path: '/', expires: 1});
       contactFormId = $.cookie($(obj).attr('id')+'-contactFormId');
   }else{
       contactFormIdOld = $.cookie($(obj).attr('id')+'-contactFormId');
       temp_contactid = genRandomId();
       $.cookie($(obj).attr('id')+'-contactFormId', temp_contactid,{path: '/', expires: 1});
       contactFormId = $.cookie($(obj).attr('id')+'-contactFormId');       
   }

   var divid = 'sendToUserBox-'+contactFormId+'-'+$(obj).attr('id');
   var formid = 'sendToUserForm-'+contactFormId+'-'+$(obj).attr('id');
   var divid_old = 'sendToUserBox-'+contactFormIdOld+'-'+$(obj).attr('id');
   //debuglog(divid);
   if( !$(obj).hasClass('ui-state-active') ){
       //$(obj).addClass('ui-state-active')
       if( $('#'+divid_old).length != 0 ){
            
            divHeight = $('#'+divid_old).height();
            totalHeight = $('#'+divid_old).parent().height();
            $('#'+divid_old).fadeOut(500,function(){
                    $('#'+divid_old).parent().find("[id^='sendSmallForm']").removeClass('ui-state-active');  
            })
            .delay(500)
            .parent()
            .animate({
                height:totalHeight - divHeight - divPadding
            }, 500, function(){
                $('#'+divid_old).remove(); 
            });
       }
       
	   //$( "[name='user_username']", $("#userRating")).val();  
	   
       var to_username = $( "[name='user_username']", $("#userRating")).val();
       var to_uid = $( "[name='user_id']", $("#userRating")).val();
		//debuglog($( "[name='user_username']", $("#userRating")).val());
		//debuglog($( "[name='user_id']", $("#userRating")).val());
       startHeight = $(obj).parent().parent().parent().height();
       
       var $replyBox = $('<div id="'+divid+'" class="replyBox ui-widget ui-widget-content" style="display:none"></div>');
       var $replyForm = $('<form name="'+formid+'" id="'+formid+'" method="post" action="inbox.html"></form> ')
       //debuglog(startHeight);
       $replyForm.append(  '<input type="hidden" value="send-to-followed" name="action" />'
                           +'<input type="hidden" value="'+to_uid+'" name="reply_to_uid" />'
                           +'<input type="hidden" value="0" name="did" />'
                           +'<input type="hidden" value="1" name="is_parent" />'
                           +'<input type="hidden" value="0" name="parent_id" />'
                           +'<input type="hidden" value="2" name="ajax" />'
                           +'<input type="hidden" value="2" name="showhtml" />'
                           +'<p class="smallBlock">'
                           +'<label>Send To: <strong>'+to_username+'</strong></label>'
                           +'</p>'
                           +'<p class="smallBlock">'
                           +'<label>Subject: </label>'
                           +'<input size="32" class="text ui-state-default ui-corner-all" type="text" value="" name="message_subject" placeholder="Enter a Subject"/>'
                           +'</p>'
                           +'<p class="smallBlock">'
                           +'<label>Message: </label>' 
                           +'<textarea cols="34" rows="8" class="ui-state-default ui-corner-all" name="message_text" placeholder="Enter a Message"></textarea>'
                           +'</p>'
                           +'<p class="smallBlock" >'
                           +'<input type="submit" class="jqButton" value="Send" name="btnSend" />&nbsp;&nbsp;'
                           +'<input type="button" class="jqButton" value="Cancel" name="btnCancel" />'
                           +'</p>'
						   +'<div clas="clear></div>'
      );
      
      $replyBox.append($replyForm);
      $replyBox.after('<div clas="clear></div>');
      $(obj).parents('table').after($replyBox).parent().find('#'+divid).addClass('rounded-r4');
      divHeight = $('#'+divid).height();
     
      /*
      obj.parent().parent().after($replyBox).parent().find('#'+divid).corner({
            tl: {radius: 4},
            tr: {radius: 4},
            bl: {radius: 4},
            br: {radius: 4},
            antiAlias:true
      });
        */
      //debuglog($('#'+divid).parent().attr('class'));
      
      $('#'+divid)
      .parent()
      .animate({
          height : startHeight + divHeight + divPadding
      }, 500, function(){
          $('#'+divid).hide().fadeIn(500);
		 debuglog(divid);
		 //debuglog($('#'+divid).parent().width());
		  $('#'+divid).width( $('#'+divid).parent().width() - 22 );
      });

      
      $("#"+divid+" input[name='btnCancel']").live('click',function(e){
            $(obj).toggleClass('ui-state-active');
            //$(obj).removeClass('ui-state-active');
            divHeight = $('#'+divid).height();
            totalHeight = $('#'+divid).parent().height();
            $('#'+divid).fadeOut(500,function(){
                    $(this).remove();
            })
            .delay(500).parent()
            .animate({
                height:totalHeight - divHeight - divPadding
            }, 500);
      });

      $("#"+formid).validate({
         rules:{
            message_subject: {
                required:true,
                maxlength:50
            },
            message_text:{
                required:true,
                maxlength:300
            }
        },
        messages:{
            message_subject:{
                required:"Please enter the subject of your message",
                maxlength:"The subject should be less then 50 characters"
            },
            message_text:{
                required:"Please enter the text of your message",
                maxlength:"The text should be less then 300 characters"
            }
        },
        submitHandler: function(form) {
            $(form).ajaxSubmit(ajaxoptions);

        },
        onfocusout: false,
        onkeyup: false,
        onsubmit: true,
        success: "",
        errorClass: "invalid",
        errorElement: "em",
        errorPlacement: function(error, element) {
            var label = $("label[for='"+element.attr('name')+"']");
            label.append(error);
        },
        debug: false
      });
      //debuglog($('#'+divid).parent().attr('class'));
   }
   else{
        //$(obj).removeClass('ui-state-active');
        divHeight = $('#'+divid_old).height();
        totalHeight = $('#'+divid_old).parent().height();
        $('#'+divid_old).fadeOut(500,function(){
                $(this).remove();
        })
        .delay(500).parent()
        .animate({
            height:totalHeight - divHeight - divPadding
        }, 500);  
   }
   $(obj).toggleClass('ui-state-active');
}
function sendToSubscriber(obj){
   var contactFormId, contactFormIdOld, temp_contactid;
   var totalHeight, startHeight, divHeight, divPadding = 30;

   if(  $.cookie($(obj).attr('id')+'-contactFormId')==null || $.cookie($(obj).attr('id')+'-contactFormId')=='' ){
       temp_contactid = genRandomId();
       $.cookie($(obj).attr('id')+'-contactFormId', temp_contactid,{path: '/', expires: 1});
       contactFormId = $.cookie($(obj).attr('id')+'-contactFormId');
   }else{
       contactFormIdOld = $.cookie($(obj).attr('id')+'-contactFormId');
       temp_contactid = genRandomId();
       $.cookie($(obj).attr('id')+'-contactFormId', temp_contactid,{path: '/', expires: 1});
       contactFormId = $.cookie($(obj).attr('id')+'-contactFormId');       
   }

   var divid = 'sendToFollowedBox-'+contactFormId+'-'+$(obj).attr('id');
   var formid = 'sendToFollowedForm-'+contactFormId+'-'+$(obj).attr('id');
   var divid_old = 'sendToFollowedBox-'+contactFormIdOld+'-'+$(obj).attr('id');
   //debuglog(divid);
   if( !$(obj).hasClass('ui-state-active') ){
       //$(obj).addClass('ui-state-active')
       if( $('#'+divid_old).length != 0 ){
            
            divHeight = $('#'+divid_old).height();
            totalHeight = $('#'+divid_old).parent().height();
            $('#'+divid_old).fadeOut(500,function(){
                    $('#'+divid_old).parent().find("[id^='message-to-subs']").removeClass('ui-state-active');  
            })
            .delay(500)
            .parent()
            .animate({
                height:totalHeight - divHeight - divPadding
            }, 500, function(){
                $('#'+divid_old).remove(); 
            });
       }
       
       var to_username = $(obj).parent().prev().find('a').html();
       var to_uid = $(obj).parent().parent().find('#to_uid').val();

       startHeight = $(obj).parent().parent().parent().height();
       
       var $replyBox = $('<div id="'+divid+'" class="replyBox ui-widget ui-widget-content" style="display:none"></div>');
       var $replyForm = $('<form name="'+formid+'" id="'+formid+'" method="post" action="inbox.html"></form> ')
       //debuglog(startHeight);
       $replyForm.append(  '<input type="hidden" value="send-to-followed" name="action" />'
                           +'<input type="hidden" value="'+to_uid+'" name="reply_to_uid" />'
                           +'<input type="hidden" value="0" name="did" />'
                           +'<input type="hidden" value="1" name="is_parent" />'
                           +'<input type="hidden" value="0" name="parent_id" />'
                           +'<input type="hidden" value="2" name="ajax" />'
                           +'<input type="hidden" value="2" name="showhtml" />'
                           +'<p class="smallFullBlock">'
                           +'<label>Reply To: <strong>'+to_username+'</strong></label>'
                           +'</p>'
                           +'<p class="smallFullBlock">'
                           +'<label>Subject: </label>'
                           +'<input size="32" class="text ui-state-default ui-corner-all" type="text" value="" name="message_subject" placeholder="Enter a Subject"/>'
                           +'</p>'
                           +'<p class="smallFullBlock">'
                           +'<label>Message: </label>'
                           +'<textarea cols="60" rows="8" class="ui-state-default ui-corner-all" name="message_text" placeholder="Enter a Message"></textarea>'
                           +'</p>'
                           +'<p class="smallFullBlock" >'
                           +'<input type="submit" class="jqButton" value="Send" name="btnSend" />&nbsp;&nbsp;'
                           +'<input type="button" class="jqButton" value="Cancel" name="btnCancel" />'
                           +'</p>'
      );
      
      $replyBox.append($replyForm);
      $(obj).parent().parent().after($replyBox).parent().find('#'+divid).addClass('rounded-r4');
      divHeight = $('#'+divid).height();

      /*
      obj.parent().parent().after($replyBox).parent().find('#'+divid).corner({
            tl: {radius: 4},
            tr: {radius: 4},
            bl: {radius: 4},
            br: {radius: 4},
            antiAlias:true
      });
        */
      //debuglog($('#'+divid).parent().attr('class'));
      
      $('#'+divid)
      .parent()
      .animate({
          height : startHeight + divHeight + divPadding
      }, 500, function(){
          $('#'+divid).hide().fadeIn(500);
      });

      
      $("#"+divid+" input[name='btnCancel']").live('click',function(e){
            $(obj).toggleClass('ui-state-active');
            //$(obj).removeClass('ui-state-active');
            divHeight = $('#'+divid).height();
            totalHeight = $('#'+divid).parent().height();
            $('#'+divid).fadeOut(500,function(){
                    $(this).remove();
            })
            .delay(500).parent()
            .animate({
                height:totalHeight - divHeight - divPadding
            }, 500);
      });

      $("#"+formid).validate({
         rules:{
            message_subject: {
                required:true,
                maxlength:50
            },
            message_text:{
                required:true,
                maxlength:300
            }
        },
        messages:{
            message_subject:{
                required:"Please enter the subject of your message",
                maxlength:"The subject should be less then 50 characters"
            },
            message_text:{
                required:"Please enter the text of your message",
                maxlength:"The text should be less then 300 characters"
            }
        },
        submitHandler: function(form) {
            $(form).ajaxSubmit(ajaxoptions);

        },
        onfocusout: false,
        onkeyup: false,
        onsubmit: true,
        success: "",
        errorClass: "invalid",
        errorElement: "em",
        errorPlacement: function(error, element) {
            var label = $("label[for='"+element.attr('name')+"']");
            label.append(error);
        },
        debug: false
      });
      //debuglog($('#'+divid).parent().attr('class'));
   }
   else{
        //$(obj).removeClass('ui-state-active');
        divHeight = $('#'+divid_old).height();
        totalHeight = $('#'+divid_old).parent().height();
        $('#'+divid_old).fadeOut(500,function(){
                $(this).remove();
        })
        .delay(500).parent()
        .animate({
            height:totalHeight - divHeight - divPadding
        }, 500);  
   }
   $(obj).toggleClass('ui-state-active');
}



function sendMessage(obj){
   if(  $.cookie($(obj).attr('id')+'-contactFormId')==null || $.cookie($(obj).attr('id')+'-contactFormId')=='' ){
       var temp_contactid = genRandomId();
       $.cookie($(obj).attr('id')+'-contactFormId', temp_contactid,{path: '/', expires: 1});
   }
   
   var contactFormId = $.cookie($(obj).attr('id')+'-contactFormId');
   var divid = 'sendNewMessageBox-'+contactFormId+'-'+$(obj).attr('id');
   var formid = 'sendNewMessageForm-'+contactFormId+'-'+$(obj).attr('id');
   var totalHeight, startHeight, divHeight, divPadding = 30;
   if( !$(obj).hasClass('ui-state-active') ){

       //var did = 0;
       var $replyBox = $('<div id="'+divid+'" class="replyBox ui-widget ui-widget-content" style="display:none"></div>');
       var $replyForm = $('<form name="'+formid+'" id="'+formid+'" method="post" action="inbox.html" class="replyForm"></form> ')
       $replyForm.append(  '<input type="hidden" value="send-new-message" name="action" />'
                           +'<input type="hidden" value="0" name="did" />'
                           +'<input type="hidden" value="1" name="is_parent" />'
                           +'<input type="hidden" value="0" name="parent_id" />'
                           +'<input type="hidden" value="2" name="ajax" />'
                           +'<input type="hidden" value="2" name="showhtml" />'
                           +'<p class="left mediumBlock">'
                           +'<label for="to_username">Send message to: </label><input type="text" size="32" name="to_username" id="to_username" placeholder="Enter a username" class="text left ui-corner-all ui-state-default" />'
                           +'<input type="text" size="2" value="0" id="'+formid+'-uid" name="reply_to_uid" readonly class="text left ui-corner-all ui-state-default" />'
                           +'</p>'
                           +'<p class="left mediumBlock">'
                           +'<label for="message_subject">Subject: </label>'
                           +'<input size="32" class="text ui-corner-all ui-state-default" type="text" value="" name="message_subject" placeholder="Enter a subject" />'
                           +'</p>'
                           +'<p class="left mediumBlock">'
                           +'<label for="message_text">Message: </label>'
                           +'<textarea cols="60" rows="8" class="ui-state-default ui-corner-all" name="message_text"></textarea>'
                           +'</p>'
                           +'<p class="left mediumBlock" >'
                           +'<input type="submit" class="jqButton" value="Send" name="btnSend" />&nbsp;&nbsp;'
                           +'<input type="button" class="jqButton" value="Cancel" name="btnCancel" />'
                           +'</p>'
        );
      $replyBox.append($replyForm);
      $(obj).parent().after($replyBox).parent().find('#'+divid).addClass('rounded-r4');

      startHeight = $(obj).parent().parent().height();
      divHeight = $('#'+divid).height();
      
      $('#'+divid)
      .parent()
      .animate({
          height : startHeight + divHeight + divPadding
      }, 300, function(){
          $('#'+divid).hide().fadeIn(300);
      });
		
		var btnCancel = $("#"+divid+" input[name='btnCancel']");
		if(btnCancel[0]){
			$("#"+divid+" input[name='btnCancel']").live('click',function(e){
		        $(obj).toggleClass('ui-state-active');
		        		
				divHeight = $('#'+divid).height();
		        totalHeight = $('#'+divid).parent().height();
		        $('#'+divid).fadeOut(300,function(){
		                $(this).remove();
		        })
		        .delay(300).parent()
		        .animate({
		            height:totalHeight - divHeight - divPadding
		        }, 300, function(){
		            $(this).removeAttr("style");
		        });
		  	});	
		}

      $( "#to_username" ).autocomplete({
            source: function(request, response) {
                $.ajax({
                  url: "/check.php",
                  data: request,
                  dataType: "json",
                  type: "POST",
                  success: function(data){
                      response(data);
                  }
                });
              },
              select: function(event, ui) {
                  $('#to_username', '#'+formid).val(ui.item.value);
                  $('#'+formid+'-uid').val(ui.item.id);
              }
      });
		

      $("#"+formid).validate({
         rules:{
            to_username:{
                required:true,
                remote:{
                        url: "/check.php",
                        type: "post",
                        data: {
                            target:'to_username',
                            validate: '1'
                        }
                    }
            },
            message_subject: {
                required:true,
                maxlength:50
            },
            message_text:{
                required:true,
                maxlength:300
            }
        },
        messages:{
             to_username:{
                required:"Please enter a username",
                remote: "This username doesn't exist. Please choose from the autocomplete list."
            },
            message_subject:{
                required:"Please enter the subject of your message",
                maxlength:"The subject should be less then 50 characters"
            },
            message_text:{
                required:"Please enter the text of your message",
                maxlength:"The text should be less then 300 characters"
            }
        },
        submitHandler: function(form) {
            //debuglog($(form).serializeArray());
            $(form).ajaxSubmit(ajaxoptions);
        },
        onfocusout: false,
        onkeyup: false,
        onsubmit: true,
        success: "",
        errorClass: "invalid",
        errorElement: "em",
        errorPlacement: function(error, element) {
            var label = $("label[for='"+element.attr('name')+"']");
            label.append(error);
        },
        debug: false
      });
   }
   else{

        divHeight = $('#'+divid).height();
        totalHeight = $('#'+divid).parent().height();
        $('#'+divid).fadeOut(300,function(){
                $(this).remove();
        })
        .delay(300).parent()
        .animate({
            height:totalHeight - divHeight - divPadding
        }, 300, function(){
            $(this).removeAttr("style");
        });
   }
   $(obj).toggleClass('ui-state-active');
}

function mPaging(obj){
        var filename = String(obj.attr('href').split("?",1));
        var myparams = getparams(obj.attr('href'));
        myparams.pop(myparams);
        var paramsStr = '';
        $(myparams).each(function(i){
            paramsStr += myparams[i]+',';
	});
    
	paramsStr += 'showhtml:2,ajax:2,action:"mpaging"';
	var params = $.evalJSON('{'+paramsStr+'}');
	
	$("#loaderAnim")
	.ajaxStart(function(){
		$("#loader",$(this)).remove();
		$(this).append('<div id="loader"></div>');
		$("#loader").position({
			of:$(this),
	        my: 'right top',
	        at: 'right top',
	        offset: '0 0'
		}).fadeIn(300);
	})
	.ajaxComplete(function(){
		$("#loader").fadeOut(300, function(){
			$("#loader").remove();
		});
	});
	
        $.get(filename,
                    params,
                    function(returned_data)
                    {
                        var htmlBox = '', repliesBox = '';
                        var data = $.evalJSON(returned_data);

                        $.each(data.messages, function(i,item){
                            //debuglog(item);
                            var is_did = 0;
                            $.each(item.discussion, function(j,reply){
                                is_did = 1;
                            });

                            htmlBox += '<h3>'
                                        +'<a href="#">'
                                            +'<strong>'+item.um_subject+'</strong>'
                                        +'</a>'
                                        +'<span class="ui-icon ui-accordion-read-icon '+((item.um_read==1)?'ui-icon-mail-open':'ui-icon-mail-closed')+'" id="ui-accordion-read-icon-'+item.um_id+'"></span>'
                                        +'<span class="ui-icon ui-accordion-direction-icon '+((item.um_to_uid==item.actual_uid)?'ui-icon-arrowthick-1-s':'ui-icon-arrowthick-1-n')+'" id="ui-accordion-direction-icon-'+item.um_id+'"></span>'
                                    +'</h3>';
                            htmlBox += '<div class="MessageBox">'
                                            +'<p>'+item.um_message+'</p>'
                                            +'<div class="clear"></div>'
                                            +'<h6>'
                                            +'<p style="margin-bottom:0; line-height:24px; height:26px;" class="message-footer">';
                                            if(item.um_from_uid==item.actual_uid){
                                                htmlBox += item.um_date+' / from <a title="check profile" href="/my-profile.html" >me</a>';
                                            }else{
                                                htmlBox += item.um_date+' / from <a title="check profile" href="/profile/'+stripText(item.sender)+'-'+item.um_from_uid+'.html" >'+item.sender+'</a>';
                                            }
                                    htmlBox +='</p>'
                                            +'<div class="clear"></div>'
                                            +'<p style="margin-bottom:0;" class="buttonsHolder">'
                                                +'<input type="hidden" name="to_uid" id="to_uid" value="'+item.um_from_uid+'" />'
                                                +'<input type="hidden" name="is_parent" id="is_parent"  value="1" />'
                                                +'<input type="hidden" name="um_id" id="um_id_'+item.um_id+'"  value="'+item.um_id+'" />'
                                                +'<input type="hidden" name="did" id="did" value="'+item.um_discussion_id+'" />';
                                                if(item.um_to_uid==item.actual_uid){
                                                    htmlBox +='<a original-title="'+((item.um_read==1)?'message is read':'mark as read')+'" class="ui-button  ui-button-special ui-state-default ui-corner-all '+((item.um_read==1)?' ui-state-active':'')+'" id="'+((item.um_read==1)?'read-icon':'read-message')+'-'+item.um_id+'" href="#">'
                                                                    +'<span class="ui-icon '+((item.um_read==1)?'ui-icon-mail-open':'ui-icon-mail-closed')+'"></span>'
                                                                +'</a>';
                                                }
                                                else{
                                                    htmlBox +='<a original-title="'+((item.um_read==1)?'message is read':'You cannot change status of this message')+'" class="ui-button  ui-button-special ui-state-default ui-corner-all '+((item.um_read==1)?' ui-state-active':'')+'" id="'+((item.um_read==1)?'read-icon':'read-message')+'-'+item.um_id+'" href="#">'
                                                                    +'<span class="ui-icon '+((item.um_read==1)?'ui-icon-mail-open':'ui-icon-mail-closed')+'"></span>'
                                                                +'</a>';
                                                }
												
                                                htmlBox +='<a href="/en/inbox.html?to_uid='+item.um_to_uid+'&action=reply-message&mid='+item.um_id+'&did='+item.um_id+'" class="reply-to-message ui-button  ui-button-special ui-state-default ui-corner-all" original-title="Reply" id="reply-message-'+item.um_id+'">'
                                                                +'<span class="ui-icon ui-icon-arrowreturnthick-1-e"></span>'
                                                            +'</a>';
                                                htmlBox +='<a href="/en/inbox.html?mid='+item.um_id+'&action=delete-message&did='+item.um_id+'&onebyone=0&role='+((item.actual_uid == item.um_from_uid)?'f':'t')+'" class="message_delete ui-button ui-button-special ui-state-default ui-corner-all" original-title="Delete this discussion" id="del-message-'+item.um_id+'">'
                                                                +'<span class="ui-icon ui-icon-trash"></span>'
                                                            +'</a>';
                                                
                                                htmlBox +=((is_did==1)?'<a original-title="Show replies" class="ui-button ui-button-special ui-state-default ui-corner-all " id="show-replies-'+item.um_id+'" href="/en/inbox.html?action=show-replies">'
                                                                +'<span class="ui-icon ui-icon-triangle-1-e"></span>'
                                                            +'</a>':'')
                                            +'</p>'
                                            +'</h6>';

                                            var tmp_mid = 0;
                                            $.each(item.discussion, function(j,reply){
                                                repliesBox += '<div style="display: none;" class="replyMessage ui-corner-all">'
                                                                +'<input type="hidden" value="'+reply.um_id+'" id="this_mid'+reply.um_id+'" name="this_mid">'
                                                                +'<h4>'
                                                                +'<span class="subject">'+reply.um_subject+'</span>';
                                                                if(reply.um_from_uid==reply.actual_uid){
                                                                    repliesBox +='<span class="left date">'+reply.um_date+' / from <a title="check Profile"  href="/en/my-profile.html" >me</a></span>';
                                                                }
                                                                else{
                                                                    repliesBox +='<span class="left date">'+reply.um_date+' / from <a title="check Profile"  href="/en/profile/'+stripText(reply.sender)+'-'+reply.um_from_uid+'.html" >'+reply.sender+'</a></span>';
                                                                }
                                                repliesBox += '</h4>';
                                                                if(reply.um_to_uid==reply.actual_uid){
                                                                      repliesBox += '<strong original-title="incoming message" class="right ui-button ui-button-special ui-state-default ui-corner-all"><span class="ui-icon ui-icon-arrowthick-1-s" id="ui-accordion-direction-reply-icon-'+reply.um_id+'"></span></strong>';
                                                                }
                                                                else{
                                                                      repliesBox += '<strong original-title="outgoing message" class="right ui-button ui-button-special ui-state-default ui-corner-all"><span class="ui-icon ui-icon-arrowthick-1-n" id="ui-accordion-direction-reply-icon-'+reply.um_id+'"></span></strong>';

                                                                }
                                                repliesBox +='<a href="/en/inbox.html?mid='+reply.um_id+'&action=delete-message&did='+item.um_id+'&onebyone=1&role='+((reply.actual_uid == reply.um_from_uid)?'f':'t')+'" class="message_delete right ui-button ui-button-special ui-state-default ui-corner-all" rel="this" original-title="Delete this message" id="del-message-'+reply.um_id+'">'
                                                                        +'<span class="ui-icon ui-icon-trash"></span>'
                                                                +'</a>'
                                                                if(reply.actual_uid == reply.um_from_uid){
                                                                    repliesBox +='<a original-title="'+((reply.um_read==1)?'message is read':'You cannot change status of this message')+'" class="ui-button ui-button-special right ui-state-default ui-corner-all '+((reply.um_read==1)?' ui-state-active':'')+'" id="sent-message-'+reply.um_id+'" href="#">'
                                                                                        +'<span class="ui-icon '+((reply.um_read==1)?'ui-icon-mail-open':'ui-icon-mail-closed')+'"></span>'
                                                                                +'</a>';

                                                                }else{
                                                                    repliesBox +='<a original-title="'+((reply.um_read==1)?'message is read':'mark as read')+'" class="ui-button ui-button-special right ui-state-default ui-corner-all '+((reply.um_read==1)?' ui-state-active':'')+'" id="'+((reply.um_read==1)?'read-icon':'read-message')+'-'+reply.um_id+'" href="#">'
                                                                                        +'<span class="ui-icon '+((reply.um_read==1)?'ui-icon-mail-open':'ui-icon-mail-closed')+'"></span>'
                                                                                +'</a>';
                                                                }

                                                repliesBox +=   '<p class="ui-corner-all">'+reply.um_message+'</p>'
                                                                +'</div>'
                                                tmp_mid = reply.um_id;
                                                //is_did = 1;
                                            });

                                            htmlBox += repliesBox
                                                        +'<div class="clear"></div>'
                                                        +'</div>';
                        });
                        
                        if(data.paging.pagingNumPages!=1){

                            var pagingBox = '';
                            var pagingAddBox = '';
                            var page = data.paging
                            if(page.pagingCurrentPage!=1){
                                pagingBox += '<a href="'+document.location.pathname+'?mpage=1&spage=1" class="page-btn-icon ui-corner-all ui-state-default"><span class="ui-icon ui-icon-seek-first"></span></a>'
                                             +'<a href="'+document.location.pathname+'?mpage='+(page.pagingCurrentPage-1)+'&spage=1" class="page-btn-icon ui-corner-all ui-state-default"><span class="ui-icon ui-icon-seek-prev"></span></a>'
                            }
                            if( (page.pagingNumPages-page.pagingCurrentPage) == 1  && page.pagingCurrentPage-1 != 0){
                               pagingAddBox += '<a href="'+document.location.pathname+'?mpage='+(page.pagingCurrentPage-1)+'&spage='+$.getUrlVar('spage')+'" class="page-btn-text ui-corner-all ui-state-default"><span>'+(page.pagingCurrentPage-1)+'</span></a>';
                            }
                            if( (page.pagingNumPages-page.pagingCurrentPage) == 0 ){
                               if(page.pagingCurrentPage-2 != 0 ){
                                    pagingAddBox += '<a href="'+document.location.pathname+'?mpage='+(page.pagingCurrentPage-2)+'&spage='+$.getUrlVar('spage')+'" class="page-btn-text ui-corner-all ui-state-default"><span>'+(page.pagingCurrentPage-2)+'</span></a>';
                               }
                               if(page.pagingCurrentPage-1 != 0 ){
                                    pagingAddBox += '<a href="'+document.location.pathname+'?mpage='+(page.pagingCurrentPage-1)+'&spage='+$.getUrlVar('spage')+'" class="page-btn-text ui-corner-all ui-state-default"><span>'+(page.pagingCurrentPage-1)+'</span></a>';
                               }
                            }
                            //debuglog(pagingAddBox);
                            pagingBox +=pagingAddBox;
                            for(var z=page.pagingCurrentPage; z<=page.pagingNumPages; z++){
                                //alert(page.pagingNumPages-page.pagingCurrentPage);

                                if( z < page.pagingCurrentPage+3   ){
                                    if( z == page.pagingCurrentPage ){
                                        pagingBox += '<span class="active-page ui-state-default ui-corner-all ui-state-active">'+z+'</span>';
                                    }
                                    else{
                                        pagingBox += '<a href="'+document.location.pathname+'?mpage='+z+'&spage='+$.getUrlVar('spage')+'" class="page-btn-text ui-corner-all ui-state-default"><span>'+z+'</span></a>';
                                    }
                                }
                            }
                            if((page.pagingCurrentPage+1)<=page.pagingNumPages){
                                pagingBox += '<a href="'+document.location.pathname+'?mpage='+(page.pagingCurrentPage+1)+'&spage='+$.getUrlVar('spage')+'" class="page-btn-icon ui-corner-all ui-state-default"><span class="ui-icon ui-icon-seek-next"></span></a>'
                                             +'<a href="'+document.location.pathname+'?mpage='+page.pagingNumPages+'&spage='+$.getUrlVar('spage')+'" class="page-btn-icon ui-corner-all ui-state-default"><span class="ui-icon ui-icon-seek-end"></span></a>'
                            }

                            //debuglog(pagingBox);
                            $("#Mpaging").empty().append(pagingBox);
                        }

                        $("#messagesAcc").accordion( "destroy" );
                        $("#messagesAcc").empty().append(htmlBox);
                        $('#messagesAcc').accordion({
                            active:false,
                            collapsible: true,
                            autoHeight: false
                        });
                    }
        );
}


// Followed
function unSubscribeFromProfile(obj){
    var patt=/\d+/;
    var uid = patt.exec( obj.attr('class'));
    var send = {};
    send.ajax = "2";
    send.showhtml = "2";
    send.action = "unsubscribe";
    send.uid = uid[0];
    
    var encoded = $.toJSON(send);
    var params = $.evalJSON(encoded);
    $.get( '/'+labels.lang+"/network.html", params, function(res){
        var data = $.evalJSON(res);
       	if( typeof data.err != 'undefined' && data.err.length !=0 ){
			if( $.isArray( data.err) ){
				$.each(data.err,function(i,obj){
					show_stack_bottomleft(true, data.err[i]);	
				});	
			}
			else{
				show_stack_bottomleft(true, data.err);
			}
			//show_stack_bottomleft(true, "test error");
	    }
		
	    if( typeof data.msg != 'undefined' && data.msg.length!=0 ){
			if( $.isArray( data.msg) ){
				$.each(data.msg,function(i,obj){
					show_stack_bottomleft(false, data.msg[i]);	
				});	
			}
			else{
				show_stack_bottomleft(false, data.msg);
			}	
			obj.find('span.ui-icon').removeClass('ui-icon-minus').addClass('ui-icon-plus');
			//show_stack_bottomleft(false, "test notice");
	    }
	   
    });
}
function unSubscribe(obj){
    var patt=/\d+/;
    var uid = patt.exec( obj.attr('class'));
    var send = {};
    send.ajax = "2";
    send.showhtml = "2";
    send.action = "unsubscribe";
    send.uid = uid[0];
    
    var encoded = $.toJSON(send);
    var params = $.evalJSON(encoded);
    $.get( '/'+labels.lang+"/network.html", params, function(res){
        var data = $.evalJSON(res);
       	if( typeof data.err != 'undefined' && data.err.length !=0 ){
		
			if( $.isArray( data.err) ){
				$.each(data.err,function(i,obj){
					show_stack_bottomleft(true, data.err[i]);	
				});	
			}
			else{
				show_stack_bottomleft(true, data.err);
			}
			//show_stack_bottomleft(true, "test error");
	    }
		
	    if( typeof data.msg != 'undefined' && data.msg.length!=0 ){
			if( $.isArray( data.msg) ){
				$.each(data.msg,function(i,obj){
					show_stack_bottomleft(false, data.msg[i]);	
				});	
			}
			else{
				show_stack_bottomleft(false, data.msg);
			}	
			obj.parent().parent().parent().fadeOut(300, function(){
				obj.parent().parent().parent().remove();
			});
			//show_stack_bottomleft(false, "test notice");
	    }
	   
    });
}
// Follow
function Subscribe(obj){
    var patt=/\d+/;
    var uid = patt.exec( obj.attr('class'));
    var send = {};
    send.ajax = "2";
    send.showhtml = "2";
    send.action = "subscribe";
    send.uid = uid[0];
    
    var encoded = $.toJSON(send);
    var params = $.evalJSON(encoded);
    $.get( '/'+labels.lang+"/network.html", params, function(res){
        var data = $.evalJSON(res);
        if( typeof data.err != 'undefined' && data.err.length !=0 ){
		
			if( $.isArray( data.err) ){
				$.each(data.err,function(i,obj){
					show_stack_bottomleft(true, data.err[i]);	
				});	
			}
			else{
				show_stack_bottomleft(true, data.err);
			}
			//show_stack_bottomleft(true, "test error");
	    }
		
	    if( typeof data.msg != 'undefined' && data.msg.length!=0 ){
			if( $.isArray( data.msg) ){
				$.each(data.msg,function(i,obj){
					show_stack_bottomleft(false, data.msg[i]);	
				});	
			}
			else{
				show_stack_bottomleft(false, data.msg);
			}	
			obj.find('span.ui-icon').removeClass('ui-icon-plus').addClass('ui-icon-minus');
			//show_stack_bottomleft(false, "test notice");
	    }
    });
}

function sPaging(obj){
    var filename = String(obj.attr('href').split("?",1));
    var myparams = getparams(obj.attr('href'));
    myparams.pop(myparams);
    var paramsStr = '';
    $(myparams).each(function(i){
        paramsStr += myparams[i]+',';
    });
    paramsStr += 'showhtml:2,ajax:2,action:"spaging"';
    var params = $.evalJSON('{'+paramsStr+'}');
	
	$("#loaderAnim")
	.ajaxStart(function(){
		$("#loader",$(this)).remove();
		$(this).append('<div id="loader"></div>');
		$("#loader").position({
			of:$(this),
	        my: 'right top',
	        at: 'right top',
	        offset: '0 0'
		}).fadeIn(300);
	})
	.ajaxComplete(function(){
		$("#loader").fadeOut(300, function(){
			$("#loader").remove();
		});
	});
	
    $.get(filename,
                params,
                function(returned_data)
                {
                    var htmlBox = '';
                    var data = $.evalJSON(returned_data);

                    $.each(data.subscribers, function(i,item){
                        //debuglog(item);
                        htmlBox +=
                            '<li>'
                                +'<a original-title="View '+item.user_username+'\'s Profile" class="user_avatar" href="/en/profile/'+stripText(item.user_username)+'-'+item.user_id+'.html" title="View profile" ><img src="/images/avatars/'+item.user_avatar+'" alt="no avatar" width="32" height="32" /></a>'
                                +'<div class="user_info">'
                                    +'<p><a href="/en/profile/'+stripText(item.user_username)+'-'+item.user_id+'.html" title="View profile" >'+item.user_username+'</a></p>'
                                    +'<p class="buttonsHolder">'
                                        +'<a href="#" original-title="Send a message" class="sendmessage-'+item.user_id+' ui-button  ui-button-special ui-state-default ui-corner-all">'
                                            +'<span class="ui-icon ui-icon-mail-closed"></span>'
                                        +'</a>'
                                        +'<a href="#" original-title="Unsubscribe" class="unsubscribe-'+item.user_id+' ui-button  ui-button-special ui-state-default ui-corner-all">'
                                            +'<span class="ui-icon ui-icon-minus"></span>'
                                        +'</a>'
                                    +'</p>'
                                +'</div>'
                            +'</li>';
                    });
                    //debuglog(htmlBox);
                    if(data.paging.pagingNumPages!=1){
                        var pagingBox = '';
                        var pagingAddBox = '';
                        var page = data.paging
                        if(page.pagingCurrentPage!=1){
                            pagingBox += '<a href="'+document.location.pathname+'?mpage='+$.getUrlVar('mpage')+'&spage=1" class="page-btn-icon ui-corner-all ui-state-default"><span class="ui-icon ui-icon-seek-first"></span></a>'
                                         +'<a href="'+document.location.pathname+'?spage='+(page.pagingCurrentPage-1)+'&mpage='+$.getUrlVar('mpage')+'" class="page-btn-icon ui-corner-all ui-state-default"><span class="ui-icon ui-icon-seek-prev"></span></a>'
                        }
                        if( (page.pagingNumPages-page.pagingCurrentPage) == 1 && page.pagingCurrentPage-1 != 0 ){
                           pagingAddBox += '<a href="'+document.location.pathname+'?spage='+(page.pagingCurrentPage-1)+'&mpage='+$.getUrlVar('mpage')+'" class="page-btn-text ui-corner-all ui-state-default"><span>'+(page.pagingCurrentPage-1)+'</span></a>';
                        }
                        if( (page.pagingNumPages-page.pagingCurrentPage) == 0 ){
                           if(page.pagingCurrentPage-2 != 0 ){
                                pagingAddBox += '<a href="'+document.location.pathname+'?spage='+(page.pagingCurrentPage-2)+'&mpage='+$.getUrlVar('mpage')+'" class="page-btn-text ui-corner-all ui-state-default"><span>'+(page.pagingCurrentPage-2)+'</span></a>';
                           }
                           if(page.pagingCurrentPage-1 != 0 ){
                                pagingAddBox += '<a href="'+document.location.pathname+'?spage='+(page.pagingCurrentPage-1)+'&mpage='+$.getUrlVar('mpage')+'" class="page-btn-text ui-corner-all ui-state-default"><span>'+(page.pagingCurrentPage-1)+'</span></a>';
                           }
                        }
                        //debuglog(pagingAddBox);
                        pagingBox +=pagingAddBox;
                        for(var z=page.pagingCurrentPage; z<=page.pagingNumPages; z++){
                            //alert(page.pagingNumPages-page.pagingCurrentPage);
                            if( z < page.pagingCurrentPage+3   ){
                                if( z == page.pagingCurrentPage ){
                                    pagingBox += '<span class="active-page ui-state-default ui-corner-all ui-state-active">'+z+'</span>';
                                }
                                else{
                                    pagingBox += '<a href="'+document.location.pathname+'?spage='+z+'&mpage=1" class="page-btn-text ui-corner-all ui-state-default"><span>'+z+'</span></a>';
                                }
                            }
                        }
                        if((page.pagingCurrentPage+1)<=page.pagingNumPages){
                            pagingBox += '<a href="'+document.location.pathname+'?spage='+(page.pagingCurrentPage+1)+'&mpage='+$.getUrlVar('mpage')+'" class="page-btn-icon ui-corner-all ui-state-default"><span class="ui-icon ui-icon-seek-next"></span></a>'
                                         +'<a href="'+document.location.pathname+'?spage='+page.pagingNumPages+'&mpage='+$.getUrlVar('mpage')+'" class="page-btn-icon ui-corner-all ui-state-default"><span class="ui-icon ui-icon-seek-end"></span></a>'
                        }
                        //debuglog(pagingBox);
                        $("#Spaging").empty().append(pagingBox);
                    }
                $("#followsBox ul").empty().append(htmlBox);
            }
    );
}

$(window).load(function(){
	//NETWORK + INBOX
    $('#networksData').tabs();
    $('#networksData').tabs( "select", parseInt( $('#selected_network_tab').val() ,10) ).fadeIn(500);

    $('#messagesAcc').accordion({
        active:false,
        collapsible: true,
        autoHeight: false
    }).fadeIn(500);

    $("#messagesAcc a.ui-button .ui-icon").livequery(function(){
        $(this).parent().tipsy({gravity: 's',fade:true});
    });
    $("#messages p > a.ui-button .ui-icon").livequery(function(){
        $(this).parent().tipsy({gravity: 's',fade:true});
    });
    $("#messagesAcc strong.ui-button .ui-icon").livequery(function(){
        $(this).parent().tipsy({gravity: 's',fade:true});
    });
    $("#messages p > strong.ui-button .ui-icon").livequery(function(){
        $(this).parent().tipsy({gravity: 's',fade:true});
    });

    $("[id^='read-icon-']").live('click', function(){
       return false;
    });
    $("[id^='sent-message-']").live('click', function(){
       return false;
    }); 
			
    $("a[id^='read-message-']").live('click',function(){
        var $obj = $(this);
        readMessage($obj);
        return false;
    });
	
		
    $("span[id^='read-message-']").live('hover',
        function(){
            $(this).css('cursor','pointer');
        },
        function(){
            $(this).css('cursor','none');
        }
    );
		
    $("a[id^='show-replies-']").live('click', function(){
        var $obj = $(this); 
        showReplies($obj);
        return false;
    });
	
    $("a[id^='hide-replies-']").live('click', function(){
        var $obj = $(this);
        showReplies($obj);
        return false;
    });
	
	$('.message_delete').live('click', function(){    
       var $message = $(this)
       var functionToCall = deleteMessage;
       deleteConfirmation(functionToCall, $message );
       return false; 
    });
    
    $('.reply-to-message').live('click', function(){
       var $obj = $(this); 
       replyToMessage($obj);
       return false;
    });

	$('#send-message').live('click', function(){
		var $obj = $(this);
		//debuglog($obj)
		sendMessage($obj);
		return false;
	});
	
    $("a[class^='page-btn-']", $("#Mpaging")).live('click',function(){
        var $actual_button = $(this);
        mPaging($actual_button);
        return false;
    });
	
	if($("#followsBox").length != 0){
		$("ul li:even", $("#followsBox")).each(function(){
			 $(this).addClass('news_content_hover').fadeIn(500);
		});
		
		$("#followsBox a.ui-button .ui-icon").livequery(function(){
	        $(this).parent().tipsy({live:true,gravity: 'n',fade:true});
	    });
		
		$("a.user_avatar").livequery(function(){
	        $(this).tipsy({live:true, gravity: 'e', fade:true});
	    });
		
	    $("a[class^='unsubscribe-']").live('click',function(ev){
	        ev.preventDefault();
			var $obj = $(this);
	        unSubscribe($obj);
	        return false;
	    });
	}
	
  
    $("a[class^='page-btn-']", $("#Spaging")).live('click',function(ev){
        ev.preventDefault();
		var $actual_button = $(this);
        sPaging($actual_button);
        return false;
    });

    
    $("a[class^='profileunsubscribe-']").live('click',function(){
        var $obj = $(this);
        unSubscribeFromProfile($obj);
        return false
    });
    $("a[class^='subscribe-']").live('click',function(){
        var $obj = $(this);
        Subscribe($obj);
        return false
    });

    $("a[class^='sendmessage-']").live('click',function(){
        var $obj = $(this);
        sendToSubscriber($obj);
        return false
    });
    $("a[id^='sendSmallForm']").live('click',function(){
        var $obj = $(this);
        sendToUser($obj);
        return false
    });
});

