var guestbook=function()
{
    var self=this;
    var siteurl="";
    var messages=
    {
      msg_too_short: 'Вы ввели слишком короткое сообщение!',
      newmess_succ_goto_index: 'Ваше сообщение успешно добавлено. Хотите перейти на первую страницу?',
      trucate_moreText: "[показать весь текст]",
      trucate_lessText: "[скрыть]",
      confirm_to_delete_message_n_comments: "Вы уверены, что хотите удалить сообщение и все комментарии на него?",
      confirm_to_delete_comment: "Вы уверены, что хотите удалить комментарий?",
	  hide_answer_form: 'Скрыть',
	  show_answer_form: 'Ответить',
	  hide_comment_list: 'Скрыть комментарии',
	  show_comment_list: 'Показать комментарии',
	  loading_please_wait: 'Загрузка страницы...',
	  loading_data_please_wait: 'Загрузка данных...',
	  thanks_your_mesage_success_added: 'Спасибо, Ваш комментарий к сообщению успешно добавлен!',
	  SorryButNothingFound: 'Извините по Вашему запросу ничего не найдено',
	  confirm_to_ban_user: 'Вы уверены, что хотите добавить пользователя в черный список?'
    };
	var answer_marked=new Array();
    
    this.SetPageId=function(id)
    {
        self.PageID=id;
    }
    this.GetPageId=function(id)
    {
        return parseInt(self.PageID);
    }
    
    this.SetDate=function(dates,from_url)
    {
        //if (from_url) $('#rangeA').val(dates);
        self.Dates=dates;
    }
    this.GetDate=function()
    {
        return self.Dates;
    }
    this.SetSearchKey=function(keyw)
    {
        self.SearchKey=keyw;
    }
    this.GetSearchKey=function()
    {
        return self.SearchKey;
    }
    this.GetPaginator=function(id)
    {
        if (self.paginator) return self.paginator;
    }
    this.GetPaginator=function()
    {
        return self.paginator;
    }
    this.localredirech_toHash=function(pageid)
    {
        window.location = siteurl+self.fetch_PaginationUrl()+pageid;
    }
    this.Set_PaginationUrl=function(dates,searchkey)
    {
        PaginationUrl="#";
        if (dates || this.GetDate()) 
        {
            PaginationUrl+="dates=";
            PaginationUrl+= (dates) ? dates : this.GetDate();
            PaginationUrl+= "&";
        }
        if (searchkey || this.GetSearchKey())
        {
            PaginationUrl+= (searchkey) ? ("searchkey="+searchkey+"&") : ("searchkey="+this.GetSearchKey());
            PaginationUrl+= "&";
        }
        
        PaginationUrl+="page=";
        
        this.PaginationUrl=PaginationUrl;
        
//        if (date) self.PaginationUrl=+"date="+page;
//        if (type) self.PaginationUrl=+"type="+page;
    }
    this.fetch_PaginationUrl=function()
    {
         return self.PaginationUrl;
    }
    
    this.PaginationLoadEnginue=function(total, visible, current)
    {
    this.paginator = new Paginator(
        "pagination",total,visible,current,
        siteurl+this.fetch_PaginationUrl()
    );



    }
    
    
    this.nickname_qtip=function()
    {

        var bb=this;
           $('.nickname_func').qtip({
               content: 'Loading...',
                  api: {
                     onRender: function()
                     {
                        var self2 = this;
                        var userid=self2.elements.target.attr('rel');
                        bb.MyAjax(
                        {
                            url: "/api/gb/get_userinfo",
                            data: ({userid : userid}),
                              beforeSend: function() {},
                              success: function(json)
                              {
                                  self2.updateContent(json.name);
                              },
                              error: function(x,text,z)
                              {
                                alert(text);
                              }
                        });
                     }
                  },

              position: {
                 corner: {
                    target: 'topRight',
                    tooltip: 'bottomLeft'
                 }
              },
              style: {
                 name: 'red',
                 padding: '7px 13px',
                 width: {
                    max: 210,
                    min: 0
                 },
                 tip: true
              }
           });
           
     }

     
    this.load_page=function(newpage,newdate)
    {
        if (newpage) this.SetPageId(newpage);
        if (newdate) 
        {
            this.SetDate(newdate);
            this.Set_PaginationUrl();
        }

         var bb=this;
         
        
        this.MyAjax(
        {
            url: "/api/gb/list_messages",
            data: ({id : bb.GetPageId(), dates: bb.GetDate()}),
              beforeSend: function()
              {
				$("#AjaxPageContents").unbind();
				$("#AjaxPageContents *").unbind();
				$.blockUI({ message: '<h1>'+messages.loading_data_please_wait+'</h1>' });
              },
              success: function(json)
              {
			  //bb.DoShowHide("#pagination",true);
				  if (bb.paginator) $("#pagination table").remove();
					
				  if (!json.msg.length)
				  {
				  $('#AjaxPageContents').html(messages.SorryButNothingFound);
				  $.unblockUI();
				  return;
				  }

				  bb.PaginationLoadEnginue(json.page.total, 20, bb.GetPageId());
				  
                  var output = $('#MainTemplate').parseTemplate(json);
                  $('#AjaxPageContents').html(output);
 
                  if (bb.ReMessageList)
                  {
                    for (var i=0; i<bb.ReMessageList.length; i++) 
                    {
                        bb.TemplateReMessage('show_comments_list_'+bb.ReMessageList[i][0], bb.ReMessageList[i][1]);

                    }
                    delete bb.ReMessageList;
                  }
				  
	
					$("#AjaxPageContents .create_new_re_answer").click(function (event) { 
						  bb.ShowReplyForm(event,$(this));
						  return false;
						});
					$("#AjaxPageContents .addnew_re_comment_submit").click(function (event) { 
						  bb.CommentToPost(event,$(this));
						  return false;
						});

					/*
					@ Edit post
					*/
					$("#AjaxPageContents .edit_post_bttn").click(function (event) { 
						  bb.PostEditShowForm(event, $(this));
						  return false;
						});
					$("#AjaxPageContents .edit_subpost_bttn").click(function (event) { 
						  bb.SubPostEditShowForm(event,$(this));
						  return false;
						});
					/*
					@ Edit post  / 
					*/
					
					/*
						@ Show comments
					*/
					$("#AjaxPageContents .show_comments_bttn").click(function (event) { 
						  bb.CommentsShowList(event, $(this));
						  return false;
						});
						
					/*
						@ Delete Post
					*/
					$("#AjaxPageContents .do_delete_message").click(function (event) { 
						  bb.DeleteMainMessage($(this).attr('rel'));
						  return false;
						});
					$("#AjaxPageContents .do_delete_submessage").click(function (event) { 
						  bb.DeleteSubMessage($(this).attr('rel'));
						  return false;
						});

					/*
						Ban Unban
					*/
					
					$("#AjaxPageContents .do_ban_user").click(function (event) { 
						  bb.BanUser($(this).attr('rel'),$(this).attr('bn'));
						  return false;
						});

                  
					 $('.main_obj_text').jTruncate({
					  length: 500,
					  minTrail: 0,
					  moreText: messages.trucate_moreText,
					  lessText: messages.trucate_lessText, 
					  ellipsisText: " .........................",
					  moreAni: "fast",
					  lessAni: 500
					 });
					 
					 
					 $.unblockUI();
					 $('#AjaxPageContents').autoscroll();
					  bb.nickname_qtip();
              },
              error: function(x,text,z)
              {
                alert(text);
              }
        });
    }
    


    this.ReponsesLoadList=function(num,resp)
    {
        if (!this.ReMessageList) 
        {
            this.ReMessageList = new Array();
        }
        this.ReMessageList[this.ReMessageList.length] = new Array(num,resp);
    }
    
    
    this.BanUser=function(userid,do_ban)
	{
	var bb=this;
	if (do_ban) do_ban=0;
	else do_ban=1;
	
        var is_confirmed = confirm(messages.confirm_to_ban_user);
        if (!is_confirmed) return false;
        bb.MyAjax(
        {
            url: "/api/gb/ban_user",
            data: ({userid : userid, makeban: do_ban}),
              beforeSend: function()
              {
              },
              success: function(json)
              {
              },
              error: function(x,text,z)
              {
                alert(text);
              }
        });
	}
    this.CommentToPost=function(event, objs)
    {
        var bb=this;
        //var postid=$(event.target).parent().attr('title');
        var postid=$(objs).attr('title');
        var message=$("#add_new_re_comment_form_"+postid+" textarea").val();
		


        bb.MyAjax(
        {
            url: "/api/gb/add_comment",
            data: ({postid : postid, message: message}),
              beforeSend: function()
              {
                  if (message.length<4)
                  {
                      alert(messages.msg_too_short);
                      return false;
                  }
                
              },
              success: function(json)
              {

                var newjson= new Array();
                newjson['json']=json.msg;
                var output = $('#ReCommentTemplate').parseTemplate(newjson);
                $("#show_comments_list_"+postid).append(output).autoscroll();

				
	
				bb.DoShowHide("#gb_re_comment_"+postid,false);	
				bb.DoShowHide("#show_comments_list_"+postid,true);
                
                $("#add_new_re_comment_form_"+postid+" textarea").val("");

                //$.jGrowl(messages.thanks_your_mesage_success_added);
              },
              error: function(x,text,z)
              {
                alert(text);
              }
        });
    }
    

    this.TemplateReMessage=function(objectz,json)
    {
        var newjson= new Array();
        newjson['json']=json;
        $("#"+objectz).html($('#ReCommentTemplate').parseTemplate(newjson));
    }

    this.MessageSetRate=function(event,action)
    {
        var bb=this;
        postid=$(event.target).parent().attr('rel');

        bb.MyAjax(
        {
            url: "/api/gb/set_rate",
            data: ({postid : postid, action: action}),
              beforeSend: function(){},
              success: function(json)
              {
                switch (action)
                {
                    case 'plus':
                    $(event.target).parent().parent().prev().text(json.rate);
                    break;
                    case 'minus':
                    $(event.target).parent().parent().next().text(json.rate);
                    break;
                    case 'reset':
                    $(event.target).parent().parent().prev().prev().text(json.rate);
                    break;
                }
              },
              error: function(x,text,z)
              {
                alert(text);
              }
        });
        
    
    }
    
    this.search_by_key=function(from_link)
    {
        var bb=this;
        if (!from_link) bb.SetSearchKey($("#search_form input:text").val());
        keyw=bb.GetSearchKey();
		$("#search_form input:text").val(keyw);
        gb.Set_PaginationUrl(false,keyw);
		

        bb.MyAjax(
        {
            url: "/api/gb/search",
            data: ({id : bb.GetPageId(), key: keyw}),
              beforeSend: function()
              {
				$("#AjaxPageContents").unbind();
				$("#AjaxPageContents *").unbind();
				$.blockUI({ message: '<h1>'+messages.loading_data_please_wait+'</h1>' });
              },
              success: function(json)
              {
				bb.DoShowHide("#pagination",true);
				if (bb.paginator) $("#pagination table").remove();
				bb.PaginationLoadEnginue(json.page.total, 20, bb.GetPageId());

                var output = $('#MainTemplate').parseTemplate(json);
                $('#AjaxPageContents').html(output);
                $('#AjaxPageContents').highlight(keyw);
				  
				$.unblockUI();
				$('#AjaxPageContents').autoscroll();
				bb.nickname_qtip();
              },
              error: function(x,text,z)
              {
                alert(text);
				$.unblockUI();
              }
        });
    }
    this.SendNewComment=function(event,where)
    {
        var bb=this;
		var msg=messages;
        var message=$("#new_message_text").val();
        
                  
        bb.MyAjax(
        {
            url: "/api/gb/add_message",
            data: ({msg: message}),
              beforeSend: function()
              {
                  if (message.length<4)
                  {
                      alert(msg.msg_too_short);
                      return false;
                  }
              },
              success: function(json)
              {

                $("#new_message_text").val("");
                $("#new_message_text").parent().parent().parent().parent().parent().hide('fast');
                
                var is_confirmed = confirm(msg.newmess_succ_goto_index);
                if (is_confirmed) {
                    bb.load_page(1);
                }
				else bb.load_page();
					
              },
              error: function(x,text,z)
              {
                alert(text);
              }
        });
    }

    this.DeleteMainMessage=function(obid)
    {
		var bb=this;
        var obj="gb_main_ob_"+obid;

        var is_confirmed = confirm(messages.confirm_to_delete_message_n_comments);
        if (is_confirmed) 
        {
			bb.MyAjax(
			{
				url: "/api/gb/DeleteMessage",
				data: ({id : obid, main: true}),
				  beforeSend: function()
				  {
	
				  },
				  success: function(json)
				  {
					  bb.DoShowHide("#"+obj,false);
				  },
				  error: function(x,text,z)
				  {
					alert(text);
				  }
			});
            
        }
    }
    this.DeleteSubMessage=function(obid)
    {
		var bb=this;
        var obj="comment_ob_id_"+obid;

        var is_confirmed = confirm(messages.confirm_to_delete_comment);
        if (is_confirmed) 
        {
			bb.MyAjax(
			{
				url: "/api/gb/DeleteMessage",
				data: ({id : obid, main: false}),
				  beforeSend: function()
				  {
	
				  },
				  success: function(json)
				  {
					  bb.DoShowHide("#"+obj,false);
				  },
				  error: function(x,text,z)
				  {
					alert(text);
				  }
			});
        }
    }
	
    this.PostEditShowForm=function(event, objs)
    {
		var bb=this;
        //main_obj=$(event.target).parent().parent().parent().parent().parent().parent().parent().parent().parent().attr('id');
        main_obj=$(objs).parent().parent().parent().parent().parent().parent().parent().parent().parent().attr('id');
		var thid=main_obj.replace(/gb_main_ob_/g, '');
		if ($(".main_editor_obj_text").html()) return false;
		
			bb.MyAjax(
			{
				url: "/api/gb/GetPostBbcode",
				data: ({id : thid}),
				  beforeSend: function()
				  {
					$("#"+main_obj+" .main_obj_text").css("display", "none");
					
					var Tx = '<div class="text main_editor_obj_text" >'+
					'<textarea cols="20" rows="15" name="message"></textarea>'+
					'<br />'+
'<a href="#" class="rec_gray_red_btn save"><span><span class="answer"><strong class="png_fix">Сохранить</strong></span></span></a>'+
'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+
'<a href="#" class="rec_gray_red_btn cancel"><span><span class="answer"><strong class="png_fix">Отмена</strong></span></span></a>'+
					'</div>';
					$(Tx).insertAfter($("#"+main_obj+" .main_obj_text"));
					
					$("#AjaxPageContents .main_editor_obj_text .save").click(function (event) { 
						  bb.EditPostSave(event,$(this));
						  return false;
						});
					$("#AjaxPageContents .main_editor_obj_text .cancel").click(function (event) { 
						  bb.EditPostCancel(event,$(this));
						  return false;
						});
					
					$("#"+main_obj+" .main_editor_obj_text textarea").markItUp(mySettings);
					
					
					$("#"+main_obj+" .markItUp").block({ 
								message: '<h1>'+messages.loading_data_please_wait+'</h1>', 
								css: { border: '3px solid #a00' } 
							}); 
				  },
				  success: function(json)
				  {
				  $("#"+main_obj+" .main_editor_obj_text textarea").val(json.text);
					$("#"+main_obj+" .markItUp").unblock();
				  },
				  error: function(x,text,z)
				  {
					alert(text);
				  }
			});

        
    }
    this.SubPostEditShowForm=function(event, objs)
    {
		var bb=this;
        //sub_obj=$(event.target).parent().parent().parent().parent().parent().parent().parent().parent().parent().attr('id');
        sub_obj=$(objs).parent().parent().parent().parent().parent().parent().parent().parent().parent().attr('id');
		
		var curid=sub_obj.replace (/comment_ob_id_/g, '');
		if ($(".sub_editor_obj_text").html()) return false;
		
			bb.MyAjax(
			{
				url: "/api/gb/GetPostBbcode",
				data: ({id : curid}),
				  beforeSend: function()
				  {
					$("#"+sub_obj+" .answer_text_f").css("display", "none");
					
					var Tx = '<div class="text sub_editor_obj_text" >'+
					'<textarea cols="20" rows="15" name="message"></textarea>'+
					'<br />'+
'<a href="#" class="rec_gray_red_btn save"><span><span class="answer"><strong class="png_fix">Сохранить</strong></span></span></a>'+
'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'+
'<a href="#" class="rec_gray_red_btn cancel"><span><span class="answer"><strong class="png_fix">Отмена</strong></span></span></a>'+
					'</div>';
					$(Tx).insertAfter($("#"+sub_obj+" .answer_text_f"));
					
					$("#AjaxPageContents .sub_editor_obj_text .save").click(function (event) { 
						  bb.EditSubPostSave(event,$(this));
						  return false;
						});
					$("#AjaxPageContents .sub_editor_obj_text .cancel").click(function (event) { 
						  bb.EditSubPostCancel(event,$(this));
						  return false;
						});
					
					$("#"+sub_obj+" .sub_editor_obj_text textarea").markItUp(mySettings);
					
					
					$("#"+sub_obj+" .markItUp").block({ 
								message: '<h1>'+messages.loading_data_please_wait+'</h1>', 
								css: { border: '3px solid #a00' } 
							});  
				  },
				  success: function(json)
				  {
					$("#"+sub_obj+" .sub_editor_obj_text textarea").val(json.text);
					$("#"+sub_obj+" .markItUp").unblock();
				  },
				  error: function(x,text,z)
				  {
					alert(text);
				  }
			});
			
			

        
    }

    this.EditPostCancel=function(event,objs)
    {
        //main_obj=$(event.target).parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().attr('id');
		var main_obj=$(objs).parent().parent().parent().parent().parent().parent().parent().attr('id');
		
        $("#"+main_obj+" .main_editor_obj_text").remove();
        $("#"+main_obj+" .main_obj_text").css("display", "block");
    }
    this.EditPostSave=function(event, objs)
    {
		var bb=this;
        //var main_obj=$(event.target).parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().attr('id');
        var main_obj=$(objs).parent().parent().parent().parent().parent().parent().parent().attr('id');
		var text=$("#"+main_obj+" .main_editor_obj_text textarea").val();
		var curid=main_obj.replace (/gb_main_ob_/g, '');

			bb.MyAjax(
			{
				url: "/api/gb/SavePost",
				data: ({id : curid, msg: text}),
				  beforeSend: function()
				  {
					$("#"+main_obj+" .markItUp").block({ 
										message: '<h1>'+messages.loading_data_please_wait+'</h1>', 
										css: { border: '3px solid #a00' } 
									});
				  },
				  success: function(json)
				  {
					$("#"+main_obj+" .main_editor_obj_text").remove();
					$("#"+main_obj+" .main_obj_text").html(json.text);
					$("#"+main_obj+" .main_obj_text").css("display", "block").autoscroll();
					$("#"+main_obj+" .markItUp").unblock();
				  },
				  error: function(x,text,z)
				  {
					$("#"+main_obj+" .main_editor_obj_text").remove();
					$("#"+main_obj+" .main_obj_text").css("display", "block");
					alert(text);
					$("#"+main_obj+" .markItUp").unblock();
				  }
			});

    }
	this.EditSubPostSave=function(event, objs)
	{
		var bb=this;
		var sub_obj=$(objs).parent().parent().parent().parent().parent().parent().parent().attr('id');
		var text=$("#"+sub_obj+" .sub_editor_obj_text textarea").val();
		var curid=sub_obj.replace (/comment_ob_id_/g, '');

			bb.MyAjax(
			{
				url: "/api/gb/SavePost",
				data: ({id : curid, msg: text}),
				  beforeSend: function()
				  {
					$("#"+sub_obj+" .markItUp").block({ 
								message: '<h1>'+messages.loading_data_please_wait+'</h1>', 
								css: { border: '3px solid #a00' } 
							});
				  },
				  success: function(json)
				  {
					$("#"+sub_obj+" .sub_editor_obj_text").remove();
					$("#"+sub_obj+" .answer_text_f").html(json.text);
					$("#"+sub_obj+" .answer_text_f").css("display", "block").autoscroll();
					$("#"+sub_obj+" .markItUp").unblock();
				  },
				  error: function(x,text,z)
				  {
					$("#"+sub_obj+" .sub_editor_obj_text").remove();
					$("#"+sub_obj+" .answer_text_f").css("display", "block");
					$("#"+sub_obj+" .markItUp").unblock();
					alert(text);
				  }
			});
	}
    this.EditSubPostCancel=function(event, objs)
    {
        //sub_obj=$(event.target).parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().parent().attr('id');
		var sub_obj=$(objs).parent().parent().parent().parent().parent().parent().parent().attr('id');
        $("#"+sub_obj+" .sub_editor_obj_text").remove();
        $("#"+sub_obj+" .answer_text_f").css("display", "block");
    }
    this.CommentsShowList=function(event,objs)
    {
		var bb=this;
        var id=$(objs).attr('title');
        var obj="show_comments_list_"+id;

            if ($("#"+obj).css('display')=='none')
            {
				prev=$(objs).children().children().children().text();
                prev.match(/\(([^\)]*)/);
                var id = RegExp.$1;
				$(objs).children().children().children().html(messages.hide_comment_list+" (<strong>"+id+")</strong>");
				bb.DoShowHide("#"+obj,true);
            }
            else 
            {
				prev=$(objs).children().children().children().text();
				prev.match(/\(([^\)]*)/);
                var id = RegExp.$1;
				$(objs).children().children().children().html(messages.show_comment_list+" (<strong>"+id+")</strong>");
				
				 bb.DoShowHide("#"+obj,false);


            };
    }
	this.DoShowHide=function(obj,show)
	{
				$.each(jQuery.browser, function(i) {
				  if($.browser.msie){
				  if (show) 
					  {
						$(obj).css('display','block');
					  }
				  else 
					  {
						$(obj).css('display','none');
					  }
				  }else{
				  if (show) 
					  {
						$(obj).show('fast');
					  }
				  else 
					  {
						$(obj).hide('fast');
					  }
				  }
				});
	}
	
    this.NewPostShowBlock=function(event)
    {
	var bb=this;
	if (curent_userid==0)
		{
            $.blockUI({ message: $('#auth_dialog'), css: { width: '275px' } });  
			$('#auth_dialog .cancel').click(function() { 
				$.unblockUI(); 
				return false; 
			}); 
			return false;
		}
	var bb=this;
        if ($(".add_new_message_top_content").css('display')=='none')
        {
			bb.DoShowHide(".add_new_message_top_content",true);
			
			if (!bb.top_marked)
			{
				$(".add_new_message_top_content textarea").markItUp(mySettings);
				bb.top_marked=true;
			}
        }
        else 
        {
            bb.DoShowHide(".add_new_message_top_content",false);
        };
        return false;
    }
    this.SelectTextNPastToComment=function(event)
    {
        var s = $(".main_obj_text").selectedText();
        var text=s.text;
        if (text.length<4)
        {
          return false;
        }
        var sa="[q]"+s.text+"[/q]\n";
        old_val=$(".add_new_recomment_textblock[style='display: block;'] textarea").val();
        sa=(old_val ? (old_val+"\n") : "")+sa;
        $(".add_new_recomment_textblock[style='display: block;'] textarea").val(sa);
//        $(".markItUpEditor").val(sa);
    }
	this.ShowReplyForm=function(event,job)
	{
	var bb=this;
	if (curent_userid==0)
		{
            $.blockUI({ message: $('#auth_dialog'), css: { width: '275px' } });  
			$('#auth_dialog .cancel').click(function() { 
				$.unblockUI(); 
				return false; 
			}); 
			return false;
		}
        $(".add_new_recomment_textblock").hide('fast');
        $(".answer strong").text(messages.show_answer_form);
        //obj="gb_re_comment_"+$(event.target).parent().parent().parent().parent().attr('title');
        obj="gb_re_comment_"+$(job).attr('title');
        if ($("#"+obj).css('display')=='none')
        {
			//$(event.target).text(messages.hide_answer_form);
			$(job).children().children().children().children().text(messages.hide_answer_form);
			bb.DoShowHide("#"+obj,true);
			if (!answer_marked[obj])
			{
				$("#"+obj+" textarea").markItUp(mySettings);
				answer_marked[obj]=true;
			}
        }
        else 
        {
			//$(event.target).text(messages.show_answer_form);
			$(job).children().children().children().children().text(messages.show_answer_form);
			bb.DoShowHide("#"+obj,false);
        }  
	}

    this.MyAjax = function(_params){

         body = $.ajax({
              url: _params.url,
              global: false,
              type: "POST",
              data: _params.data ,
              beforeSend: _params.beforeSend,
              dataType: "json",
              success: function(json)
              {
                  if (json.success==true) _params.success(json.values);
                  else 
                  {
                      if(json.values) _params.error(false,json.values,false);
                      else _params.error(false,'Ошибка Сервера',false);
                  }
              },
               error: _params.error
           });
		}

}

var gb=new guestbook();



$(document).ready(function() {
	gb.DoShowHide(".botton_new_message_content",true);
	
	(CurrenPageID=$.url.param("page")) ? gb.SetPageId(CurrenPageID) : gb.SetPageId(1);
	if (newdate=$.url.param("dates")) gb.SetDate(newdate,true);

	if (keyword=$.url.param("searchkey")) 
	{
		gb.SetSearchKey(keyword);
		gb.search_by_key(true)
	}
	else 
    {
        gb.Set_PaginationUrl();
        gb.load_page();
    }



$("#rangePicker").datepicker({
			changeMonth: true,
			changeYear: true,
			dateFormat: "dd-mm-yy",
			onSelect: function(dateText, inst) 
			{
				gb.Set_PaginationUrl(dateText);
				gb.localredirech_toHash(1);
				

				return false;
			}
		});


    

    
 
 /*
    @Action: Select text for quote
 */  
/* 
$('.main_obj_text') 
    .livequery('mouseup', function(event) {
    gb.SelectTextNPastToComment(event);
    });
*/     
  
/*    
$('.set_rate_plus') 
    .livequery('click', function(event) { 
        gb.MessageSetRate(event,'plus') ;
        return false;
    });
    
$('.set_rate_minus') 
    .livequery('click', function(event) { 
        gb.MessageSetRate(event,'minus') ;
        return false;
    });
    
$('.set_rate_reset') 
    .livequery('click', function(event) { 
        gb.MessageSetRate(event,'reset') ;
        return false;
    });
 */


	$(".reload_page_bttn").click(function (event) { 
		gb.load_page();
		return false;
	});

	$(".send_new_glob_comment").click(function (event) { 
		gb.SendNewComment(event,'top');
		return false;
	});
	$(".add_new_message_top").click(function (event) { 
		gb.NewPostShowBlock(event);
		return false;
	});



	/*
		@ Search
	*/
	$("#search_form").submit(function (event) { 
		gb.search_by_key(event);
		return false;
	});
    
  
	$(document).bind('hashChange', function(e, newHash)
	{
		$.hashstr.setStr(newHash);
		(CurrenPageID=$.hashstr.param("page")) ? gb.SetPageId(CurrenPageID) : gb.SetPageId(1);
		if (newdate=$.hashstr.param("dates")) gb.SetDate(newdate,true);

		if (keyword=$.hashstr.param("searchkey")) 
		{
			gb.SetSearchKey(keyword);
			gb.search_by_key(true)
		}
		else 
			{
				gb.Set_PaginationUrl();
				gb.load_page();
			}
	});



$(document).bind('keydown', 'Ctrl+left', function (evt)
{
	var pageid=gb.GetPageId()-1;
	if (pageid<1) return false;
	gb.localredirech_toHash(pageid);
	return false; 
});
$(document).bind('keydown', 'Ctrl+right', function (evt)
{
	var pageid=gb.GetPageId()+1;
	if (pageid<1) return false;
	gb.localredirech_toHash(pageid);
	return false; 
});
$(document).bind('keydown', 'f5',function (evt)
{
	gb.Set_PaginationUrl();
	gb.load_page();
	return false; 
});



});

(function($){
$.fn.autoscroll = function() {
jQuery('html,body').animate(
{
scrollLeft: this.offset().left,
scrollTop: this.offset().top
},
500
);
return this;
};
})(jQuery);



jQuery.fn.selectedText = function(win){
    win = win || window;
    
    var obj = null;
    var text = null;

    // Get parent element to determine the formatting applied to the selected text
    if(win.getSelection){
        var obj = win.getSelection().anchorNode;

        var text = win.getSelection().toString();
        // Mozilla seems to be selecting the wrong Node, the one that comes before the selected node.
        // I'm not sure if there's a configuration to solve this,
        var sel = win.getSelection();
//        console.log(win.getSelection());
        if(!sel.isCollapsed&&$.browser.mozilla){
            // If we've selected an element, (note: only works on Anchors, only checked bold and spans)
            // we can use the anchorOffset to find the childNode that has been selected
            if(sel.focusNode.nodeName !== '#text'){
                // Is selection spanning more than one node, then select the parent
                if((sel.focusOffset - sel.anchorOffset)>1)
                {
                    obj = sel.anchorNode;
//                    console.log("Selected spanning more than one",obj);
                }
                else if ( sel.anchorNode.childNodes[sel.anchorOffset] && sel.anchorNode.childNodes[sel.anchorOffset].nodeName !== '#text' )
                {
                    obj = sel.anchorNode.childNodes[sel.anchorOffset];
//                    console.log("Selected non-text",obj);
                }
                    
                else
                {
                    obj = sel.anchorNode;
//                    console.log("Selected whole element",obj);
                }
                    
            }
            // if we have selected text which does not touch the boundaries of an element
            // the anchorNode and the anchorFocus will be identical
            else if( sel.anchorNode.data === sel.focusNode.data ){
                obj = sel.anchorNode.parentNode;
//                console.log("Selected non bounding text",obj);
            }
            // This is the first element, the element defined by anchorNode is non-text.
            // Therefore it is the anchorNode that we want
            else if( sel.anchorOffset === 0 && !sel.anchorNode.data ){
                obj = sel.anchorNode
//                console.log("Selected whole element at start of paragraph (whereby selected element has not text e.g. &lt;script&gt;",obj);
            }
            // If the element is the first child of another (no text appears before it)
            else if( typeof sel.anchorNode.data !== 'undefined' 
                        && sel.anchorOffset === 0 
                        && sel.anchorOffset < sel.anchorNode.data.length ){
                            obj = sel.anchorNode.parentNode;
//                            console.log("Selected whole element at start of paragraph",obj);
            }
            // If we select text preceeding an element. Then the focusNode becomes that element
            // The difference between selecting the preceeding word is that the anchorOffset is less that the anchorNode.length
            // Thus
            else if( typeof sel.anchorNode.data !== 'undefined'
                        && sel.anchorOffset < sel.anchorNode.data.length ){
                            obj = sel.anchorNode.parentNode;
//                console.log("Selected preceeding element text",obj);
            }
            // Selected text which fills an element, i.e. ,.. <b>some text</b> ...
            // The focusNode becomes the suceeding node
            // The previous element length and the anchorOffset will be identical
            // And the focus Offset is greater than zero
            // So basically we are at the end of the preceeding element and have selected 0 of the current.
            else if( typeof sel.anchorNode.data !== 'undefined' 
                    && sel.anchorOffset === sel.anchorNode.data.length 
                    && sel.focusOffset === 0 ){
                        obj = (sel.anchorNode.nextSibling || sel.focusNode.previousSibling);
//                console.log("Selected whole element text",obj );
            }
            // if the suceeding text, i.e. it bounds an element on the left
            // the anchorNode will be the preceeding element
            // the focusNode will belong to the selected text
            else if( sel.focusOffset > 0 ){
                obj = sel.focusNode.parentNode;
//                console.log("Selected suceeding element text", obj);
            }
        }
        else if(sel.isCollapsed)
            obj = obj.parentNode;
        
    }
    else if(win.document.selection){
        var sel = win.document.selection.createRange();
        var obj = sel;

        if(sel.parentElement)
            obj = sel.parentElement();
        else 
            obj = sel.item(0);

        text = sel.text || sel;
    
        if(text.toString)
            text = text.toString();
    }
    else 
        throw 'Error';
        
    // webkit
    if(obj.nodeName==='#text')
        obj = obj.parentNode;

    // if the selected object has no tagName then return false.
    if(typeof obj.tagName === 'undefined')
        return false;

    return {'obj':obj,'text':text};
};
