$(document).ready(function () {
  
  //SyntaxHighlighter.all();
  
  // tabs.
  var selected_index = 0;
  $("#tabs_read").tabs({
    select: function(event, ui) {
      /*
      if(ui.index==1) {
      }else if(ui.index==2) {
        bookSearch();
      }else if(ui.index==3) {
        loadRecentChanges();
      }*/

      if(ui.index==1) {
        bookSearch();
      }else if(ui.index==2) {
        loadRecentChanges();
      }
    },
    load: function(event, ui) {
    }
  });
  $("#tabs_read").removeClass("ui-corner-all");
  $("#tabs_read").addClass("ui-corner-top");

  // buttons.
  $("#infoBtn").button({ icons:{ primary: 'ui-icon-info' }});
  $("#infoBtn").click(function(event){
    location.href = "/";
  });

  $("#toEditBtn").button({ icons:{ primary: 'ui-icon-pencil' }});
  $("#toEditBtn").click(function(event){
    var pageno = $("#g_pageno").val();
    location.href = "/edit/page/"+pageno;
  });

  $("#loginBtn").button({ icons:{ primary: 'ui-icon-power' }});
  $("#loginBtn").click(function(event){
    location.href = "/read/logined";
  });

  $("#logoutBtn").button({ icons:{ primary: 'ui-icon-power' }});
  $("#logoutBtn").click(function(event){
    location.href = "/accounts/logout";
  });

  //$("#read_toc_link").button();
  $("#commentSubmitBtn").button({ icons:{ primary: 'ui-icon-comment' }});
  $("#commentSubmitBtn").click(function(event){
    var comment_pageno = $("#comment_pageno").val();

    var comment_nickname = $("#comment_nickname").val();
    var comment_homepage = $("#comment_homepage").val();
    var comment_passwd = $("#comment_passwd").val();
    var comment_content = $("#comment_content").val();

    if (!comment_nickname) {
      alert("이름을 입력하세요");
      $("#comment_nickname").focus();
      return;
    }

    if (!comment_passwd) {
      alert("비밀번호를 입력하세요");
      $("#comment_passwd").focus();
      return;
    }

    if (!comment_content) {
      alert("댓글을 입력하세요");
      $("#comment_content").focus();
      return;
    }
    
    $.post("/read/comment/add/ajax", { 
      "comment_pageno": comment_pageno,
      "comment_nickname": comment_nickname,
      "comment_homepage": comment_homepage,
      "comment_passwd": comment_passwd,
      "comment_content": comment_content
    }, function(data){
        $("#comment_list").html(data);
        $("#comment_content").val("");
    }, "html");
  });

  $("#commentLoginBtn").button({ icons:{ primary: 'ui-icon-comment' }});
  $("#commentLoginBtn").click(function(event){
    var comment_pageno = $("#comment_pageno").val();
    location.href="/read/comment/login?comment_pageno="+comment_pageno;
  });

  // toc.
  $("#toc_navigation").treeview({
    control: "#treecontrol",
    collapsed: true,
    persist: "location"
  });
  $('#treecontrol a:eq(1)').click();

  $("#book_navigation").treeview({
    control: "#book_treecontrol",
    collapsed: true,
    persist: "location"
  });
  $('#book_treecontrol a:eq(1)').click();

  $("#sub_navigation").treeview({
    control: "#sub_treecontrol",
    collapsed: true,
    persist: "location"
  });
  $('#sub_treecontrol a:eq(1)').click();

  $(".opentoc").click(function(event){
	  openToc();
  });

  // library for author.
  $("#book_search").change(bookSearch);

  // search book.
  //$("#bookSearchBtn").button();
  $("#bookSearchBtn").click(function(event){
    loadBookSearch();
  });

  // shortcut
  $(document).bind('keydown', 'f2',function (evt){
	  openToc();
  });

  loadNotification();

});

function openToc() {
	$("#normal_dialog").dialog("destroy");
	$("#normal_dialog").dialog({
	  resizable: false,
	  width:350,
	  height:400,
	  modal: true,
	  title: "목차 보기 (F2)",
	  buttons: {
	    "확 인": function() {
	      $(this).dialog('close');
	    }
	  }
	});
}

function loadNotification() {
  $.post("/read/notification/ajax", {
  }, function(data){
      $("#notification").html(data);
  }, "html");
}


function delete_comment(comment_id) {
  $("#comment_passwd_dialog").val("");

  //delete_comment_dialog
  $("#delete_comment_dialog").dialog("destroy");
  $("#delete_comment_dialog").dialog({
    resizable: false,
    height:140,
    modal: true,
    title: "댓글 삭제?",
    buttons: {
      '삭제합니다': function() {

        var comment_passwd_dialog = $("#comment_passwd_dialog").val();
        var comment_pageno = $("#comment_pageno").val();
        if(!comment_passwd_dialog) {
          alert("비밀번호를 입력하세요");
          $("#comment_passwd_dialog").focus();
          return;
        }

        $.post("/read/comment/delete/ajax", { 
          "comment_pageno": comment_pageno,
          "comment_passwd": comment_passwd_dialog,
          "comment_id": comment_id
        }, function(data){

            if(data.message) {
              alert(data.message);
            }else {
              $("#delete_comment_dialog").dialog("destroy");
              refreshCommentList(comment_pageno);
            }
        }, "json");
      },
      Cancel: function() {
        $(this).dialog('close');
      }
    }
  });
}

function refreshCommentList(pageno) {
  $.post("/read/comment/get/ajax", { 
    "comment_pageno": pageno
  }, function(data){
      $("#comment_list").html(data);
  }, "html");
}

function bookSearch() {
  $("#search_kw").val("");
  var selected_search = $("#book_search option:selected").val();
  if(selected_search == "" || selected_search == "mybook") {
    $("#search_kw").css("display", "none");
    //$("#bookSearchBtn").css("display", "none");
    loadBookSearch();
  }else {
    $("#search_kw").css("display", "");
    //$("#bookSearchBtn").css("display", "");
  }
}


function loadBookSearch(_type) {
  // ---------------------------------
  // jqGrid init
  // ---------------------------------

  var pageno = $("#g_pageno").val();
  var selected_search = $("#book_search option:selected").val();

  if(_type) {
    selected_search = _type;
  }

  $("#book_search_grid").GridUnload();
  $("#book_search_grid").jqGrid({
    url:'/read/book/search/ajax?type='+selected_search+"&kw="+$("#search_kw").val(),
    datatype: "xml",
    mtype: 'GET',
    colNames:['Book', '책이름', '작성자', '태 그', '최근 수정일', '조회수', '요약'],
    colModel:[
      {name:'bookimg',index:'bookimg', sortable:false, align:"center", title:false, width:160},
      {name:'name',index:'name', align:"center", sortable:true, title:false},
      {name:'author',index:'author', align:"center", sortable:false, title:false},
      {name:'tags',index:'tags', align:"left", sortable:false, title:false},
      {name:'modify_date',index:'modify_date', align:"center", sortable:true, title:false, hidden:true},
      {name:'query_count',index:'query_count', align:"center", sortable:true, title:false, 
        formatter:'integer', formatoptions:{thousandsSeparator: ","}},
      {name:'summary',index:'summary', align:"left", sortable:false, title:false, width:250}
    ],
    
    height:400,
    width:800,
    rowNum:20,
    rowList:[20,50,100],
    pager: '#book_search_pager',
    sortname: 'query_count',
    viewrecords: true,
    sortorder: "desc",
    sortable: false,

    gridComplete: function(){
      var ids = jQuery("#book_search_grid").jqGrid('getDataIDs');
      for(var i=0;i < ids.length;i++){
          var hid = ids[i];
          var bookimg = jQuery("#book_search_grid").jqGrid('getCell', hid, "bookimg");
          
          jQuery("#book_search_grid").jqGrid('setRowData',ids[i],{bookimg:"<div><img src='/static/bookimg/"+bookimg+"' class='bookimg' /></div>"});
      }
    },

    onSelectRow: function(rowid, status) {
      location.href = "/read/book/"+rowid;
    }
  });
}


function loadRecentChanges() {
  $("#recent_changes_grid").GridUnload();
  $("#recent_changes_grid").jqGrid({
    url:'/read/page/recent/ajax',
    datatype: "xml",
    mtype: 'GET',
    colNames:['Action', '작성자', '책이름', '페이지 제목', '최근 수정일'],
    colModel:[
      {name:'act',index:'act', sortable:false, width:40, align:"center", title:false, hidden:true},
      {name:'author',index:'author', align:"left", sortable:false, title:true},
      {name:'name',index:'name', align:"left", sortable:false, title:true},
      {name:'subject',index:'tags', align:"left", sortable:false, title:true},
      {name:'modify_date',index:'modify_date', align:"center", sortable:false, title:true}
    ],
    
    height:400,
    width:800,
    rowNum:30,
    rowList:[30, 50,100],
    pager: '#recent_changes_pager',
    sortname: 'modify_date',
    viewrecords: true,
    sortorder: "desc",
    sortable: false,

    gridComplete: function(){
      var ids = jQuery("#recent_changes_grid").jqGrid('getDataIDs');
    },

    onSelectRow: function(rowid, status) {
      location.href = "/read/"+rowid;
    }
  });
}

