var c_origin_size;
var is_max = false;
var origin_size = 1;
var current_anchor = ""; 
var current_url = ""; 
var menu_timeout;
var SAVE_DRAFT_INTERVAL = 20000;
var last_draft = null;
var friend_group_data = null;
var friend_data = null;
var category_id = null;
var xuetang_go_url = null;
var KIND = {
  "note": 1,
  "category": 2,
  "course": 3
}
var logined = false;

function log(s) {
  if(self.console) {
    console.log(s);
  } else if($("#console_ie").length > 0) {
    $("#console_ie").html($("#console_ie").html() + "<br>" + s);
  } else {
//$(document.body).append("<div id='console_ie_c' style='position:absolute;top:0;left:0;background: #ccc; z-index: 100'><div id='console_ie'>" + s + "</div></div>");
}
}

function close_dialog() {
  $(".ui-dialog").hide();
}

function datepicker(id) {
  $("#"+id).datepicker($.extend({
    dateFormat: 'yy-mm-dd',
    showOn: 'button',
    buttonImage: '/images/calendar.gif',
    buttonImageOnly: true,
    showMonthAfterYear: false
  }, $.datepicker.regional["zh-CN"]));
	
}

function set_title(title) {
    
  document.title = title + default_title;
}

function _alert(msg, title) {
  if($("#alert_msg").length == 0) {
    __alert(msg);
    return;
  }
  $("#alert_content").html(msg);
  if(title) {
    $("#alert_title").html(title);
  }
  $.blockUI({
    message: $("#alert_msg"),
    css: {
      width: "30%",
      left: "35%"
    },
    timeout: 2000
  });
}

function is_ie6_7(){
  if ( $.browser.msie ) {
    var v = $.browser.version;
    if(v.indexOf("6") != -1) return true;
    if(v.indexOf("7") != -1) return true;
  }
  return false;
}

var __alert = window.alert;
window.alert = _alert;

//<![CDATA[
<!--

/*
 * This is the orginial function from Stuart Langridge at http://www.kryogenix.org/
 */
 
/*
* This is the update function from Jeff Minard - http://www.jrm.cc/
*/
function superTextile(s) {
  var r = s;
  // quick tags first
  qtags = [['\\*', 'strong'],
  ['\\?\\?', 'cite'],
  ['\\+', 'ins'],  //fixed
  ['~', 'sub'],
  ['\\^', 'sup'], // me
  ['@', 'code']];
  for (var i=0;i<qtags.length;i++) {
    ttag = qtags[i][0];
    htag = qtags[i][1];
    re = new RegExp(ttag+'\\b(.+?)\\b'+ttag,'g');
    r = r.replace(re,'<'+htag+'>'+'$1'+'</'+htag+'>');
  }
  // code
  var code_re = new RegExp("{{{\\((.*?)\\)\n+((?:.|\s|\r|\n)*?)\n+}}}",'gm');
  var m = r.match(code_re);
	
  r = r.replace(code_re, "AIZIXUEAIZIXUE")

  // underscores count as part of a word, so do them separately
  re = new RegExp('\\b_(.+?)_\\b','g');
  r = r.replace(re,'<em>$1</em>');
	
  //jeff: so do dashes
  re = new RegExp('[\s\n]-(.+?)-[\s\n]','g');
  r = r.replace(re,'<del>$1</del>');

  // links
  re = new RegExp('\\s"(.+?)\\((.+?)\\)":([^\\s]+)','g');
  r = r.replace(re,'<a href="$3" title="$2">$1</a>');
  re = new RegExp('\\s"(.+?)":([^\\s]+)','g');
  r = r.replace(re,'<a href="$2">$1</a>');


  // images
  re = new RegExp('!\\b(.+?)\\(\\b(.+?)\\b\\)!','g');
  r = r.replace(re,'<img src="$1" alt="$2">');
  re = new RegExp('!\\b(.+?)\\b!','g');
  r = r.replace(re,'<img src="$1">');

	
    
  // block level formatting
	
  // Jeff's hack to show single line breaks as they should.
  // insert breaks - but you get some....stupid ones
  re = new RegExp('(.*)\n([^#\*\n].*)','g');
  r = r.replace(re,'$1<br />$2');
  // remove the stupid breaks.
  re = new RegExp('\n<br />','g');
  r = r.replace(re,'\n');
	
  lines = r.split('\n');
  nr = '';
  for (var i=0;i<lines.length;i++) {
    line = lines[i].replace(/\s*$/,'');
    changed = 0;
    if (line.search(/^\s*bq\.\s+/) != -1) {
      line = line.replace(/^\s*bq\.\s+/,'\t<blockquote>')+'</blockquote>';
      changed = 1;
    }
		
    // jeff adds h#.
    if (line.search(/^\s*h[1|2|3|4|5|6]\.\s+/) != -1) {
      re = new RegExp('h([1|2|3|4|5|6])\.(.+)','g');
      line = line.replace(re,'<h$1>$2</h$1>');
      changed = 1;
    }
		
    if (line.search(/^\s*\*\s+/) != -1) {
      line = line.replace(/^\s*\*\s+/,'\t<liu>') + '</liu>';
      changed = 1;
    } // * for bullet list; make up an liu tag to be fixed later
    if (line.search(/^\s*#\s+/) != -1) {
      line = line.replace(/^\s*#\s+/,'\t<lio>') + '</lio>';
      changed = 1;
    } // # for numeric list; make up an lio tag to be fixed later
    if (!changed && (line.replace(/\s/g,'').length > 0)) line = '<p>'+line+'</p>';
    lines[i] = line + '\n';
  }
	
  // Second pass to do lists
  inlist = 0;
  listtype = '';
  for (var i=0;i<lines.length;i++) {
    line = lines[i];
    if (inlist && listtype == 'ul' && !line.match(/^\t<liu/)) {
      line = '</ul>\n' + line;
      inlist = 0;
    }
    if (inlist && listtype == 'ol' && !line.match(/^\t<lio/)) {
      line = '</ol>\n' + line;
      inlist = 0;
    }
    if (!inlist && line.match(/^\t<liu/)) {
      line = '<ul>' + line;
      inlist = 1;
      listtype = 'ul';
    }
    if (!inlist && line.match(/^\t<lio/)) {
      line = '<ol>' + line;
      inlist = 1;
      listtype = 'ol';
    }
    lines[i] = line;
  }

  r = lines.join('\n');
  // jeff added : will correctly replace <li(o|u)> AND </li(o|u)>
  r = r.replace(/li[o|u]>/g,'li>');

  //recover code
  var arr = r.split("AIZIXUEAIZIXUE");
  var _arr = new Array();
  // console.log(m)
  for(var i = 0; i < arr.length; i++){
    _arr.push(arr[i]);
    try{
      // console.log(code_re.test(m[i]))
      // var code = m[i].replace(code_re,'<pre class="sh_$1">$2</pre>');
      var code = m[i].replace(code_re,'*_*_*pre class="sh_$1"_*_*_$2*_*_*/pre_*_*_')._escape_html();
      code = code.replace(/_\*_\*_/g, ">").replace(/\*_\*_\*/g, "<");
      // console.log(code)
      _arr.push(code);
    }catch(e){}
  }
  // console.log(_arr.join(""))

  return _arr.join("");
}

String.prototype._escape_html = function() {
  return this.replace(/&/g, "&amp;").replace(/<br.*?>/g, "\r\n").replace(/>/g, "&gt;").replace(/</g, "&lt;").replace(/\\r\\n/g, "<br>");
}

String.prototype._html2text = function() {
  return this.replace(/&nbsp;/g, " ").replace(/<br.*?>/g, "\r\n").replace(/<.+?>/g, "");
}

//-->
//]]>


function escape_pre(html) {
  // var s = html.replace(/(<pre.+?>)((?:.|\r|\n)+?)<\/pre>/g, '$1' + '$2'.toString().replace(/>/mg, "&gt;").replace(/</mg, "&lt;") + "</pre>");
  var re = /(<pre.+?>)((?:.|\r|\n)+?)<\/pre>/g;
  var token = "__AIZIXUE__";
  var arr1 = html.replace(re, '$1' + token + "</pre>").split(token);
  // console.log(arr1);
  var arr2 = html.match(re)
  // console.log(arr2);
  var arr = new Array();
  for(var i = 0;i < arr1.length;i++) {
    arr.push(arr1[i]);
    try{
      arr.push(arr2[i].replace(/(\<pre.+?>)/g, "").replace(/<\/pre>/g, "")._escape_html());
    }catch(e){};
  }
  // console.log(arr.join(""));
  return arr.join("");
}

function make_global_dialog(opt) {
  var callback = opt.callback || function(){
    return true;
  };
  $('#global_dialog').dialog({
    autoOpen: false,
    width: (opt.width || 700),
    // height: (opt.height || 415),
    buttons: {
      "确定": function() {
        if(callback.call()) $(this).dialog("close");
      },
      "取消": function() {
        $(this).dialog("close");
      }
    }
  });
}


function mini_editor(id, css_class) {
  $(document).unbind('keyup');
  if(!id) {
    id = "note_textile";
  }
  if(!css_class) {
    css_class = "mini_editor";
  }
  $("#is_textile").val("false");
  $("#" + id).htmlarea({
    css_class: css_class,
    loaded: function() {
      this.iframe[0].contentWindow.focus();
      $(this.iframe[0].contentWindow.document).bind('keydown', 'Cmd+s', function(){
        setTimeout(function(){
          $("p.buttons button").trigger("click");
        }, 500);
        return false;
      });
      $(this.iframe[0].contentWindow.document).bind('keydown', 'Ctrl+s', function(){
        setTimeout(function(){
          $("p.buttons button").trigger("click");
        }, 500);
        return false;
      });
    },
    css: "/stylesheets/editor.css",
    // js: "/stylesheets/jquery.js",
    toolbar: ["bold", "underline",
    {
      css: "link",
      text: "插入链接",
      action: function(btn) {
        _this = this;
        this.storeSelection();
        $("#web_link_url").val("");
        $("#web_link_title").val("");
        $("#web_link_text").val("");
        $("#inner_link_c input").val("");
        $("#list_container2").html("");
        setTimeout(function(){
          $("#web_link_url").focus();
        }, 50);
        do_insert_link = function(text, url, alt, target) {
          if(!alt) alt = text;
          var link_html;
          if(!url) { //inner link
            link_html = "<a href=\"/notes/" + text + "\"" + (target ? "target='" + target + "'" : "") + ">" + text.replace(/^\d+\//, "") + "</a>";
          } else {
            link_html = "<a href='" + url + "' title='" + alt + "' " + (target ? "target='" + target + "'" : "") + ">" + text + "</a>"
          }
          // console.log(code_body)
          // console.log(code_body._escape_html())
          // alert("<a href='" + url + "' title='" + alt + "' " + (target ? "target='" + target + "'" : "") + ">" + text + "</a>");
          _this.pasteHTML(link_html);
          try{
            $("#insert_link_dialog").dialog("close");
          }catch(e){}
        }
        insert_link(this.getSelectedHTML());
      }
    },
    {
      css: "image",
      text: "插入图片",
      action: function(btn) {
        _this = this;
        this.storeSelection();
        $("#web_img_url").val("");
        $("#web_img_height").val("");
        $("#web_img_width").val("");
        insert_img = function(html) {
          _this.pasteHTML(html);
          $('#insert_img_dialog').dialog("close");
        }
        $("#insert_img_iframe").attr("src", "/pictures/new");
        $('#insert_img_dialog').dialog("open");
      }
    },
    {
      // This is how to add a completely custom Toolbar Button
      css: "code",
      text: "代码",
      action: function(btn) {
        _this = this;
        this.storeSelection();
				
        do_insert_code = function(code_type, code_body) {
          // console.log(code_body)
          // console.log(code_body._escape_html())
          _this.pasteHTML("<pre class='" + code_type + "'>" + code_body._escape_html() + "</pre>");
        }
        insert_code(this.getSelectedHTML());
      }
    }
    //,
    // "|",
    // 				{
    // 				            // This is how to add a completely custom Toolbar Button
    // 				            css: "textile",
    // 				            text: "Textile",
    // 				            action: function(btn) {
    // 								switch_to_textile(this);
    // 				            }
    // 				        }
    ] // Overrides/Specifies the Toolbar buttons to show
  });
  // $(document).bind('keydown', 'Esc', function(){$("a.max_editor").trigger("click");});
  $(document).bind('keydown', 'ctrl+m', function(){
    $("#" + id + " a.max_editor").trigger("click");
    return false;
  });
  $(document).bind('keydown', 'cmd+m', function(){
    $("#" + id + " a.max_editor").trigger("click");
    return false;
  });
}

function editor(id, css_class) {
  $(document).unbind('keyup');
  if(!id) {
    id = "note_textile";
  }
  $("#is_textile").val("false");
  $("#" + id).htmlarea({
    css_class: css_class,
    loaded: function() {
      this.iframe[0].contentWindow.focus();
      $(this.iframe[0].contentWindow.document).bind('keydown', 'Cmd+s', function(){
        setTimeout(function(){
          $("p.buttons button").trigger("click");
        }, 500);
        return false;
      });
      $(this.iframe[0].contentWindow.document).bind('keydown', 'Ctrl+s', function(){
        setTimeout(function(){
          $("p.buttons button").trigger("click");
        }, 500);
        return false;
      });
    },
    css: "/stylesheets/editor.css",
    // js: "/stylesheets/jquery.js",
    toolbar: [{
      css: "remove_format",
      text: "删除格式",
      action: function(btn) {
        this.removeFormat();
      }
    },
    {
      // This is how to add a completely custom Toolbar Button
      css: "undo",
      text: "Undo",
      action: function(btn) {
        this.undo();
      }
    },
    {
      // This is how to add a completely custom Toolbar Button
      css: "redo",
      text: "Redo",
      action: function(btn) {
        this.redo()
      }
    },
    "bold", "italic", "underline","strikethrough",
    "|", "subscript", "superscript", "decreasefontsize","increasefontsize","forecolor",
    "|", "orderedlist", "unorderedlist", "indent", "outdent",
    "|", "h2", "h3", "h4", "h5", "h6",
    "|",
    {
      css: "link",
      text: "插入链接",
      action: function(btn) {
        _this = this;
        this.storeSelection();
        $("#web_link_url").val("");
        $("#web_link_title").val("");
        $("#web_link_text").val("");
        $("#inner_link_c input").val("");
        $("#list_container2").html("");
        setTimeout(function(){
          $("#web_link_url").focus();
        }, 50);
        do_insert_link = function(text, url, alt, target) {
          if(!alt) alt = text;
          var link_html;
          if(!url) { //inner link
            link_html = "<a href=\"/notes/" + text + "\"" + (target ? "target='" + target + "'" : "target='_blank'") + ">" + text.replace(/^\d+\//, "") + "</a>";
          } else {
            link_html = "<a href='" + url + "' title='" + alt + "' " + (target ? "target='" + target + "'" : "target='_blank'") + ">" + text + "</a>"
          }
          // console.log(code_body)
          // console.log(code_body._escape_html())
          // alert("<a href='" + url + "' title='" + alt + "' " + (target ? "target='" + target + "'" : "") + ">" + text + "</a>");
          _this.pasteHTML(link_html);
          try{
            $("#insert_link_dialog").dialog("close");
          }catch(e){}
        }
        insert_link(this.getSelectedHTML());
      }
    },
    "unlink",
    {
      css: "image",
      text: "插入图片",
      action: function(btn) {
        _this = this;
        this.storeSelection();
        $("#web_img_url").val("");
        $("#web_img_height").val("");
        $("#web_img_width").val("");
        insert_img = function(html) {
          _this.pasteHTML(html);
          $('#insert_img_dialog').dialog("close");
        }
        $("#insert_img_iframe").attr("src", "/pictures/new");
        $('#insert_img_dialog').dialog("open");
      }
    },
    {
      css: "flash",
      text: "插入多媒体",
      action: function(btn) {
        _this = this;
        this.storeSelection();
        $("#web_flash_url").val("");
        $("#web_flash_height").val("");
        $("#web_flash_width").val("");
        insert_flash = function(html) {
          _this.pasteHTML(html);
          $('#insert_flash_dialog').dialog("close");
        }
        insert_music = function(html) {
          _this.pasteHTML(html);
          $('#insert_flash_dialog').dialog("close");
        }
        $('#insert_flash_dialog').dialog("open");
      }
    },
    "horizontalrule",
    {
      // This is how to add a completely custom Toolbar Button
      css: "quote",
      text: "引用",
      action: function(btn) {
        this.storeSelection();
        this.pasteHTML("<blockquote>" + this.getSelectedHTML() + "</blockquote>");
      }
    },
    {
      // This is how to add a completely custom Toolbar Button
      css: "code",
      text: "代码",
      action: function(btn) {
        _this = this;
        this.storeSelection();
				
        do_insert_code = function(code_type, code_body) {
          // console.log(code_body)
          // console.log(code_body._escape_html())
          _this.pasteHTML("<pre class='" + code_type + "'>" + code_body._escape_html() + "</pre>");
        }
        insert_code(this.getSelectedHTML());
      }
    },
    "|",
    {
      // This is how to add a completely custom Toolbar Button
      css: "max_editor",
      text: "切换编辑器大小",
      action: function(btn) {
        $("#" + id).attr("jhtmlareaObject").storeSelection();
        $(document).scrollTop(0);
        // this.hideHTMLView();
        var c = $(this.container);
        if(this.max) { //min
          $(btn).css({
            "background-position": "-113px -32px"
          });
          c.removeClass("max_editor").css({
            width: this.max.w + "px",
            height: this.max.h + "px"
          });
          $("body").css({
            "overflow": "auto"
          });
          $("html").css({
            "overflow": "auto"
          });
          $("iframe", c).css({
            height: this.max.h_i + "px",
            width: this.max.w_i + "px"
          });
          this.max = false;
        } else { //max
          $(btn).css({
            "background-position": "-96px -32px"
          });
          var w = $(window).width();
          var h = $(window).height();
          this.max = {
            h: c.height(),
            w: c.width(),
            h_i: $("iframe", c).height(),
            w_i: $("iframe", c).width()
          }
          c.addClass("max_editor").css({
            width: (w) + "px",
            height: h + "px"
          });
          $("body").css({
            "overflow": "hidden"
          });
          $("html").css({
            "overflow": "hidden"
          });
							
          $("iframe", c).css({
            height: (h - 20) + "px",
            width: (w) + "px"
          });
        }
        setTimeout(function(){
          $("#" + id).attr("jhtmlareaObject").restoreSelection();
        }, 10);
      }
    }
    //,
    // "|",
    // 				{
    // 				            // This is how to add a completely custom Toolbar Button
    // 				            css: "textile",
    // 				            text: "Textile",
    // 				            action: function(btn) {
    // 								switch_to_textile(this);
    // 				            }
    // 				        }
    ] // Overrides/Specifies the Toolbar buttons to show
  });
  // $(document).bind('keydown', 'Esc', function(){$("a.max_editor").trigger("click");});
  var max_obj = $("a.max_editor", $("#" + id).parent());
  $(document).bind('keydown', 'ctrl+m', function(){
    max_obj.trigger("click");
    return false;
  });
  $(document).bind('keydown', 'cmd+m', function(){
    max_obj.trigger("click");
    return false;
  });
}

var __editor, __eventTarget, __intervalUpdateTextArea;

function textile() {
  $("#is_textile").val("true");
  $('#note_textile').markItUp(mySettings);
}

function switch_to_textile(btn) {
  $.post("/textile",
  {
    html: btn.toHtmlString()
  },
  function(data){
    if (self.__intervalUpdateTextArea) {
      clearInterval(__intervalUpdateTextArea);
    }
    __editor = btn;
    $('#note_textile').val(data);
    btn.updateHtmlArea();
    // btn.showHTMLView();
    btn.textarea.show();
    btn.htmlarea.hide();
    $("ul li:not(li:has(a.html))", btn.toolbar).hide();
    $("ul:not(:has(:visible))", btn.toolbar).hide();
    $("ul li a.html", btn.toolbar).addClass("highlighted");
    // console.log($('#note_textile').val())
    textile();
			
  }
  );
	
}


function switch_to_editor() {
  $('#note_textile').val(superTextile($('#note_textile').val()));
  // $("#note_textile").markItUpRemove();
  $("div.markItUpHeader").hide();
  if (self.__editor) {
    __editor.hideHTMLView();
  }
  editor();
}

function switch_link_type(t) {
  $("div.link_c").hide();
  $("#" + t + "_c").show();
}

function do_insert_code(code) {}
function do_insert_link(text, url, alt, target) {}

function _parse_code_type(html) {
  var re = new RegExp("class=\"sh_(.*?)\"", "ig");
  re.exec(html);
  return RegExp.$1;
}

function insert_code(code) {
  $("#code_body").val(code._html2text());
  $('#insert_code_dialog').dialog('open');
  return false;
}

function insert_link(html) {
  $('#insert_link_dialog').dialog('open');
  return false;
}

function ajax_paginate(){ 
  $('div.pagination a').click(function() {
    var url = this.href + "";
    if(url.indexOf("notes/list") > -1 && url.indexOf("recent") > -1){
      /page=(\d+)&recent=(\d+)/.exec(url);
      replace_anchor("#recent" +RegExp.$2 + "?page=" + RegExp.$1);
    }else if(url.indexOf("notes/list") > -1 && url.indexOf("latest") > -1){
      /latest=(\d+)&page=(\d+)/.exec(url);
      replace_anchor("#latest" +RegExp.$1 + "?page=" + RegExp.$2);
    }else if(url.indexOf("notes/list") > -1 && url.indexOf("readcount") > -1){
      /page=(\d+)&readcount=(\d+)/.exec(url);
      replace_anchor("#readcount?page=" + RegExp.$1);
    }else if(url.indexOf("notes/list") > -1 && url.indexOf("star") > -1){
      var s =  /page=(\d+)/.exec(url);
      var m = '';
      if(s == null)
        m = '1';
      else
        m = RegExp.$1
      replace_anchor("#star?page=" + m);
    }
    else if (url.indexOf("notes/list") > -1) { //note
      //http://i/notes/list/2?page=2
      /(-*\d+)(?:\.js)*\?page=(\d+)/.exec(url);
      replace_anchor("#" + RegExp.$1 + "?page=" + RegExp.$2);
    } else if (url.indexOf("/tags/") > -1) {
      //http://i/tags/13?page=2
      /(\d+)(?:\.js)*\?page=(\d+)/.exec(url);
      replace_anchor("#t_" + RegExp.$1 + "?page=" + RegExp.$2);
    }
    return false;
  });
  close_tip();
  $(document).scrollTop(0);
}

function ajax_paginate2(id){ 
  if(!id) id = "list_container2";
  $('div.pagination a').click(function() {
    tip();
    $("#" + id).load(this.href, ajax_paginate2);
    return false;
  });
  close_tip();
// $(document).scrollTop(0);
}

function save_draft(){
  if($("#note_textile").serialize() == "note%5Btextile%5D=") {
    return true;
  }
  if($("#note_textile").serialize() == last_draft){
    return true;
  } 
  last_draft = $("#note_textile").serialize();
  tip("保存草稿");
  $.post("/notes/draft", $("#note_title").serialize() + "&" + $("#note_tmp_title").serialize() + "&" + $("#note_textile").serialize(), function(tmp_title){
    $("#note_tmp_title").val(tmp_title);
    close_tip();
  })
}

function save_section_draft(){
  if($("#section_body").serialize() == last_draft){
    return true;
  }
  last_draft = $("#section_body").serialize();
  tip("保存草稿");
  $.post("/sections/draft", "hidden_section_id="+$("#hidden_section_id").val() +"&"+$("#section_body").serialize(), function(){
    close_tip();
  })
}

function load_draft(title){
  $.get("/notes/load_draft", "title=" + title, function(data){
    if(data != "") {
      $("#load_draft_yes").click(function(){
        $($("#jtadhtd iframe")[0].contentWindow.document.body).html(data);
        $.unblockUI();
      });
      $("#load_draft_no").click(function(){
        $.unblockUI();
      });
      $.blockUI({
        message: $("#load_draft"),
        timeout: 5000
      });			
    }
  })
}

var filter_notes;

function show_filter_notes() {
  if(filter_notes) {
    filter_notes = false;
    $("input.category_checkbox").hide();
    $("#filter_notes_tips").hide();
    $("#filter_notes_trigger").val("知识专辑筛选");
    $.cookie("select", null, {
      path: '/'
    });
    $.cookie("album", null, {
      path: '/'
    });
  } else {
    filter_notes = true;
    $("input.category_checkbox").show();
    $("#filter_notes_tips").show();
    $("#filter_notes_trigger").val("取消知识专辑筛选");
    $.cookie("select", "true", {
      path: '/'
    });
  }
}

function check_all(_class) {
  $.each($("." + _class), function(i, item){
    this.checked = true;
  });
}

function check_reverse(_class) {
  $.each($("." + _class), function(i, item){
    this.checked = !this.checked;
  });
}

function add2album() {
  var data = $("#batch_category_form").serialize();

        
  if(data == "") {
    alert("请选择知识");
    return;
  }
  if($.cookie("album")) {
    $("#filter_notes_spin").show();
    alert("add2album == "+data)
    $.post("/albums/add_notes",
      data + "&album_id=" + $.cookie("album"),
      after_add2album
      );
  } else {
    //select album first
    show_select_album(data);
  }
}

/*
//add selected_notes to album_cards
function add2card() {

        var data = $("#batch_category_form").serialize();
        
	if(data == "") {
		alert("请选择知识");
		return;
	}
	if($.cookie("album")) {
		$("#filter_notes_spin").show();
		$.post("/albums/add_cards",
		       data + "&album_id=" + $.cookie("album")
		);
	} else {
		//select album first
		show_select_album(data);
	}
}
*/

function show_select_album(data) {
  var opt = {
    width: 500,
    // height: 400,
    callback: function(){
      var album_id = 0;
      var ids = $("#global_dialog_iframe").contents().find("._radio");
      $.each(ids, function(){
        if(this.checked) album_id = this.value;
      });
      var album = $("#global_dialog_iframe").contents().find("#album").val();
      if (album_id == 0 && album.trim() == "") {
        alert("请选择或输入专辑名称");
        return false;
      }
      $("#filter_notes_spin").show();
      if (album_id > 0) {
        $.post("/albums/add_notes",
          data + "&album_id=" + album_id,
          after_add2album
          );
      } else {
        $.post("/albums/add_notes",
          data + "&album=" + album,
          after_add2album
          );
      }
		
      return true;
    }
  };
  $('#global_dialog').get(0).title = "选择专辑";
  make_global_dialog(opt);
  $("#global_dialog_iframe").css({
    width: "430px",
    // height: "290px",
    "overflow-x": "hidden"
  });
  $("#global_dialog_iframe").get(0).src = "/albums?act=select";
  $('#global_dialog').dialog("open");
}

function after_add2album(data) {
  $("#filter_notes_spin").hide();
  //add note to parent window if exist
  try{
    parent.add_notes(data)
  }catch(e){
    log(e)
  }
}

function ixue_timer(n) {
  if(n < 1) return false;
  $("#timer").text(n);
  setTimeout(function(){
    ixue_timer(n - 1)
  }, 1000);
}

function blur_all() { 
  $("#q").trigger("blur");
  $("#goto").trigger("blur");
}


var c_origin_size;
var is_max = false;
var origin_size = 1;
function zoom(n) {
  origin_size = origin_size * n;
  $("div.text_content *").css("font-size", origin_size + "em");
}  

function mail_note(){
  $('#the_share_form').show();
  $('#notice').hide();
  $("#the_share_form ul.holder li.bit-box").remove();
  $('#share_dialog').dialog("open");
  $(".facebook-auto").css({
    "width": "647px"
  });
}

function edit_tag() {
  $(".facebook-auto").css({
    "width": "565px"
  });
  $('#tag_dialog').dialog("open");
  setTimeout(function(){
    $("#note_tags_string_annoninput .maininput").focus();
  }, 10);
}

function edit_category() {
  $('#select_category_dialog').dialog('open');
}

function after_select_node(id, name) {
  tip("更新分类");
  $.post("/notes/update_category", {
    c_id: id,
    path: "true",
    "ids[]": note_id
  }, function(data){
    $("#path_c").html(data);
    close_tip();
    $('#select_category_dialog').dialog("close");
  });
}

function share_note_tip(s, auto_close) {
  if($("#a_tip").length) {
    $("#a_tip").html(s).show();
  } else {
    $("#friend_tree").before("<span style='color:red;font-size:0.8em' id='a_tip'>"+s+"</span>");
  }
  if(auto_close) {
    setTimeout(function(){
      $("#a_tip").hide();
    }, 2000);
  }
}

function get_note_id() {
  return note_id;
}

function get_category_id() {
  return category_id;
}



function select_friend_dialog(func) {
  if($('#select_friend_dialog').length) {
    $('#select_friend_dialog').remove();
  }
  var d = $("<div id='select_friend_dialog' style='display:none' title='选择好友或分组'></div>")
  .append("<div><input id='friend_search' type='text' value='搜索好友'></div><div id='group_list'><span style='color:red;font-size:0.8em' class='highlight'>正在加载...</span></div>");
  $(document.body).append(d);
  d.dialog({
    autoOpen: false,
    width: 280,
    // height: 400,
    buttons: {
      "确定": function() {
        func.call();
      }
    }
  }).dialog("open");
  $("#friend_search").select().focus(function(){
    $(this).select();
  }).keyup(function(){
    if ($(this).val().length > 0) {
      search_friend($(this).val());
    } else {
      render_friend_tree();
    }
  });
  $.getJSON("/friends/select_friend", function(data){
    friend_group_data = data;
    render_friend_tree();
  });
}

function select_from_friend(friends){
  var func = function() {
    //Submit
    var cks = $("#friend_tree input:checked:enabled");
    if(cks.length) {
      $.each(cks, function(){
        var o = $(this).parent();
        if(o.is(".li_group")) {
          $.each($("li > input", o), function(){
            var oo = $(this).parent();
            append_friend_to_list(friends, oo.text(), $(this).val());
          });
        } else {
          append_friend_to_list(friends, o.text(), $(this).val());
        }
      });
      $('#select_friend_dialog').dialog("close");
    } else {
      share_note_tip("请选择好友或分组", true);
    }
  };
  select_friend_dialog(func);
}

function append_friend_to_list(friends, name, id){
  if(friends[id]) return;
  friends[id] = true;
  $("#friend_s").append($("<div/>").attr("id", "friend_" + id).
    addClass("friend").
    append(name +
      "(待确认)<input type='hidden' name='friends[]' value='" + id + "' />" +
      "<span class='deleter' onclick='delete_friend(friends,"+
      id +")'>x</span>"));
}

function delete_friend(friends, id){
  friends[id] = false;
  $("#friend_" + id).remove();
}

function remove_share_content(id, obj) {
  $(obj).html("&nbsp;&nbsp;&nbsp;&nbsp;");
  right_loading(obj);
  $.post("/friends/remove_share", "&authenticity_token=" + authenticity_token + "&id=" + id, function(data){
    $('#share_content_' + id).remove();
    right_loaded(obj);
  });
}

function share_note(){ 
  _do_share(get_note_id(), "note");
}

function share_category(id){ 
  _do_share(id, "category");
}

function share_course(id){ 
  _do_share(id, "course");
}

function _do_share(id, kind_name){  
  var func = function() {
    //Submit
    var cks = $("#friend_tree input:checked:enabled");
    if(cks.length) {
      // log(cks.serialize());
      share_note_tip("正在提交...");
      $.post("/friends/share", cks.serialize() + "&authenticity_token=" + authenticity_token + "&id=" + id + "&kind=" + KIND[kind_name], function(data) {
        share_note_tip("分享成功");
        setTimeout(function(){
          $("#a_tip").hide();
          $("#friend_tree input:checked").attr("checked", false);
          $('#select_friend_dialog').dialog("close");
        }, 2000);
      });
    } else {
      share_note_tip("请选择好友或分组", true);
    }
  };
  select_friend_dialog(func);
}

function interest_category(c_id, obj_a) {
  tip("正在设置关注");
  if(!!obj_a) {
    $(obj_a).click(function(){
      return false
    });
  }
  $.post("/categories/follow", "id=" + c_id + "&authenticity_token=" + authenticity_token, function(data) {
    alert(data);
    close_tip();
  });
}

function search_friend(v) {
  function man(s) {
    var arr = [];
    for(var i = 0; i < v.length; i++){
      var last_index = 0;
      var c = v.charAt(i);
      var curr_index = s.toLowerCase().indexOf(c);
      var sub = s.substring(last_index, curr_index + 1);
      s = s.substring(curr_index + 1, s.length);
      last_index = curr_index;
      arr.push(sub.replace(new RegExp(c,"i"), "<span class='strong'>" + c + "</span>"));
    }
    return arr.join("");
  }
	
  var arr = [];
  for(var i = 0; i < v.length; i++){
    arr.push(v.charAt(i).replace(".", "\\.").replace(" ", "."));
  }
	
  var reg = new RegExp("(" + arr.join(".*?") + ")","i");
  arr = [];
  $.each(friend_data, function(index, u){
    item = u["name"];
    if(reg.test(item)){
      reg.exec(item);
      var s = RegExp.$1;
      item = item.replace(s, man(s))
      arr.push("<li><input type='checkbox' name='friends[]' value='" + u["id"] + "'/>"+ item +"</li>");
    }
  });
	
  $("#group_list").html("<ul id='friend_tree'>"+ arr.join("") +"</ul>");
}

function render_friend_tree() {
  var html = ["<ul id='friend_tree'>"];
  var g, arr, u;
  var in_map = {};
	
  friend_data = [];
	
	
  $.each(friend_group_data, function(){
    g = this["friend_group"];
    arr = g["friend_list"];
    html.push("<li class='li_group" + (arr.length == 0 ? " leaf" : " close") + "' id='group_" + g["id"] + "'><input type='checkbox' name='groups[]' value='" + g["id"] + "'/>" + g["name"]);
    if (arr.length > 0) {
      html.push("<ul class='ul_friend'>");
      $.each(arr, function(){
        u = this["user"];
        html.push("<li class='li_friend li_friend_" + u["id"] + "'><input type='checkbox' name='friends[]' value='" + u["id"] + "'/>" + u["name"] + " <span class='ft_12 cl_999'>"+ u["email"] + "</span>" +"</li>");
        if(!in_map[u["id"]]) {
          in_map[u["id"]] = true;
          friend_data.push(u);
        }
      });
      html.push("</ul>");
    }
    html.push("</li>");
  });
  html.push("</ul>");
  $("#group_list").html(html.join(""));
  $("#friend_tree > li.close").click(function(){
    if ($(this).is(".close")) {
      $(this).removeClass("close").addClass("open");
      $(">ul", $(this)).show();
    } else {
      $(this).removeClass("open").addClass("close");
      $(">ul", $(this)).hide();
    }
  });
  $("li.li_group > input").click(function(){
    var p = $(this).parent();
    $("li input", p).attr("checked", this.checked).attr("disabled", this.checked);
    if(p.is(".close")) {
      p.removeClass("close").addClass("open");
      $(">ul", p).show();
    }
    var _this = this;
    setTimeout(function(){
      $(_this).attr("checked", !_this.checked);
    }, 10);
    return false;
  });
  $("li.li_friend > input").click(function(){
    var _this = this;
    setTimeout(function(){
      $(_this).attr("checked", !_this.checked);
    }, 10);
    return false;
  });
	
  $("li.li_friend").click(function(){
    return false;
  }).mouseover(function(){
    $(this).addClass("highlight");
  }).mouseout(function(){
    $(this).removeClass("highlight");
  });
}

function max_view() { 
  $(document).scrollTop(0);
  var c = $("#cc");
  if (is_max) {
    $("body").css({
      "overflow": "auto"
    });
    $("#max_button").html('<img src="/images/ft.png" title="全屏" alt="全屏" class="icon img_layout_b" />');
    c.removeClass("maxxx").css({
      "width": c_origin_size.w + "px",
      "height": "auto",
      "min-height": "10px"
    });
    is_max = false;
  } else {
    $("body").css({
      "overflow": "hidden"
    });
    $("#max_button").html('<img src="/images/ft.png" title="全屏" alt="全屏" class="icon img_layout_s" />');
    c_origin_size = {
      h: c.height(),
      w: c.width()
    };
    var w = $(window).width();
    var h = $(window).height();
    w -= 60;
    var height_tag;
    if($.browser.msie) {
      c.addClass("maxxx").css({
        "top": 0,
        "width": w + "px",
        "height": $(document).height() + "px"
      }).scrollTop(0);
    } else {
      c.addClass("maxxx").css({
        "top": 0,
        "width": w + "px",
		"min-height": $(document).height() + "px"
      }).scrollTop(0);
    }
    is_max = true;
  }
}

function go_uncategory() {
  replace_anchor("#0");
}

function go_starred() {
  replace_anchor("#star");
}

function go_readcount() {
  replace_anchor("#readcount");
}

function go_recent(day){
  replace_anchor("#recent"+day);
}

function go_latest(day){
  replace_anchor("#latest"+day);
}


function go_tag(id) {
  replace_anchor("#t_" + id);
}

function go_note(title) {
  replace_anchor("#n_" + title);
}

function replace_anchor(s) {
  self.location.href = self.location.href.toString().replace(/#.*$/gi, "") + s;
}

function load_content(url) {
  try{
    $('#tag_dialog').remove();
    $('#share_dialog').remove();
    $('#select_category_dialog').remove();
    $('#recipients').remove();
  }catch(e){}
	
	
  $("#share_dialog").remove();
  if($("#list_container").get(0)){
    tip();
    $("#list_container").load(url, ajax_paginate);
  }
}

function untip_me(tip_id) {
  $.get("/tips/untip?id=" + tip_id);
}

function handle_back() {
  var url = top.location.href.toString();
  if(current_url == url) {
    return false;
  } else {
    current_url = url;
  }
  url = url.replace(/\/(notes)\/.*?#/, "/notes/#");
  // if(/\/notes\/.*?#/.test(top.location.href.toString())) {
  //         top.location.href = url;
  //     }
  var arr = /#(.*)$/.exec(url);
  if(arr == null) {
    if(current_anchor && current_anchor.length > 0) {
      current_anchor = "";
      load_content("/notes?format=js");
    }
    return false;
  }
  var s = arr[1];
	
  if (s == "" || current_anchor == s) {
    return false;
  }
	
  // log(url)
  // 	log("current_anchor=" + current_anchor)
  // 	log("s=" + s)
	
  current_anchor = s;
	
  var page;
  // log("s=" + s)
  // 	log("/page=(\\d+)/.exec(s)=" + /page\=(\d+)/.exec("0?page=2"))
  // 	log("s=" + s)
  if((arr = /page=(\d+)/.exec(s)) != null) {
    page = parseInt(arr[1]);
  }
  // log("page=" + page)
	
	
  if (s.indexOf("t_") == 0) {
    var q = s.replace("t_", "");
    if($.browser.msie) {
      q = encodeURIComponent(q);
    }
    load_content("/tags/" + q + (isNaN(page) ? "?format=js" : "?format=js&page=" + page))
    return;
  } else if (s.indexOf("n_") == 0) {
    var q = s.replace("n_", "");
    if($.browser.msie) {
      q = encodeURIComponent(q);
    }
    load_content("/notes/" + q + "?format=js")
    return;
  } else if (s.indexOf("s_") == 0) {
    var q = s.replace("s_", "");
    if($.browser.msie) {
      q = encodeURIComponent(q);
    }
    load_content("/search/notes?format=js&q=" + q)
    return;
  } else if( s.indexOf("star") == 0){
    var b = /page=(\d+)/.exec(s);
    var  m = RegExp.$1;
    if(b == null)
      m = 1;
    load_content("/notes/list?star=1&page=" + m);
    return;
  } else if( s.indexOf("readcount") == 0 ){
    var b = /page=(\d+)/.exec(s);
    var   m = RegExp.$1;
    if(b == null)
      m = 1;
    load_content("/notes/list?readcount=1&page=" + m);
    return;
  }else if( s.indexOf("recent0") == 0){
    var b = /page=(\d+)/.exec(s);
    var   m = RegExp.$1;
    if(b == null)
      m = 1;
    load_content("/notes/list?recent=0&page=" + m);
    return;
  }else if( s.indexOf("recent1") == 0){
    var b = /page=(\d+)/.exec(s);
    var   m = RegExp.$1;
    if(b == null)
      m = 1;
    load_content("/notes/list?recent=1&page=" + m);
    return;
  }else if( s.indexOf("recent7") == 0){
    var b = /page=(\d+)/.exec(s);
    var   m = RegExp.$1;
    if(b == null)
      m = 1;
    load_content("/notes/list?recent=7&page=" + m);
    return;
  }else if( s.indexOf("recent30") == 0){
    var b = /page=(\d+)/.exec(s);
    var   m = RegExp.$1;
    if(b == null)
      m = 1;
    load_content("/notes/list?recent=30&page=" + m);
    return;
  }else if( s.indexOf("latest0") == 0){
    var b = /page=(\d+)/.exec(s);
    var   m = RegExp.$1;
    if(b == null)
      m = 1;
    load_content("/notes/list?latest=0&page=" + m);
    return;
  }else if( s.indexOf("latest1") == 0){
    var b = /page=(\d+)/.exec(s);
    var   m = RegExp.$1;
    if(b == null)
      m = 1;
    load_content("/notes/list?latest=1&page=" + m);
    return;
  }else if( s.indexOf("latest7") == 0){
    var b = /page=(\d+)/.exec(s);
    var   m = RegExp.$1;
    if(b == null)
      m = 1;
    load_content("/notes/list?latest=7&page=" + m);
    return;
  }else if( s.indexOf("latest30") == 0){
    var b = /page=(\d+)/.exec(s);
    var   m = RegExp.$1;
    if(b == null)
      m = 1;
    load_content("/notes/list?latest=30&page=" + m);
    return;
  }
  var id = parseInt(s);
  //if(!isNaN(id)) {
  load_content("/notes/list?id=" + id + (isNaN(page) ? "&format=js" : "&format=js&page=" + page));
//}
}  


function tip(msg) {
  var o = $("#ajaxtips");
  if(!msg) {
    msg = "正在装载"
  }
  $('span', o).html(msg);
  o.show().css({
    "z-index": 998
  });
}

function tip_confirm(msg) {
  var o = $("#ajax_confirm");
  if(!msg) {
    msg = "装载成功"
  }
  $('span', o).html(msg);
  o.show().css({
    "z-index": 999
  });
}

function close_tip(msg) {
  $("#ajaxtips").hide();
  if(msg) {
    tip_confirm(msg);
    setTimeout(function(){
      $("#ajax_confirm").hide();
    }, 1000);
  }
    
}

var batch_category = false;
var fire_select = false;

function iXue_alert(m) {
  alert(m);
}

function show_batch_category() {
  if(batch_category) {
    batch_category = false;
    $("input.category_checkbox").hide();
    $("#batch_category_tips").hide();
    $("#batch_category_trigger strong").text("批量管理分类");
  } else {
    batch_category = true;
    $("input.category_checkbox").show();
    $("#batch_category_tips").show();
    $("#batch_category_trigger strong").text("取消批量管理分类");
  }
}


function select_node(NODE, TREE_OBJ) {
  // var arr = new Array();
  // for(var k in NODE){
  // 	arr.push("NODE[" + k + "]=" + (typeof NODE[k] == 'function' ? NODE[k] + " <b>F</b>" : NODE[k]));
  // }
  // $("#list_container").html(arr.join("<br/>"))
  // return false
  if($("#note_category_id").get(0)){
    $("#category_name").val(node_path(NODE));
    $("#note_category_id").val(node_id(NODE));
  } else {
    if (batch_category) {
      set_category(NODE.id.replace("c_", ""));
    } else {
      // list_category(NODE.id.replace("c_", ""));
      self.location.href = self.location.href.toString().replace(/#.*$/gi, "") + "#"+node_id(NODE);
    }
  }
}


function set_category(id) {
  // console.log(id)
  var notes = $("input.category_checkbox");
  var arr = new Array();
  $.each(notes, function(index, item){
    if(item.checked){
      arr.push(item.value);
    }
  });
  if(arr.length == 0) {
    alert("请选择要设置分类的项目。如果不想进行批量分类管理，请先取消批量管理分类。", "注意");
    return;
  }
  tip("正在设置分类");
  // var data = new Object();

  $.post("/notes/update_category", "c_id=" + id + "&ids[]=" + arr.join("&ids[]="), function(data){
    // remove the select notes
    $.each(arr, function(){
      $(".note_" + this).remove();
    });
    close_tip();
  // alert("完成设置分类", "恭喜");
  })
}

function list_category(id) {
  if($("#list_container").get(0)){
    $("#list_container").load("/notes/list?format=js&id=" + id, ajax_paginate);
  }
}

function pre_node_id(NODE) {
  var pre = $(NODE.previousSibling);
  if(pre) {
    return pre.get(0).id;
  }
  return 0;
}

function node_name(NODE) {
  return $("a:first", $(NODE)).text();
}

function node_path(NODE) {
  var arr = [];
  while($(NODE).get(0).tagName != "DIV") {
    if($(NODE).get(0).tagName == "LI") {
      arr.push(node_name(NODE));
    }
    NODE = $(NODE).parent();
  }
  return arr.reverse().join(" > ");
} 

function node_id(NODE) {
  if(NODE) {
    return $(NODE).get(0).id.replace("c_", "");
  }
  return 0;
}

function rename(NODE) {
	
  var id = NODE.id;
  var name = $("a:first", $(NODE)).text();
  if(/^p_c_\d+/i.test(id)) {
    $.post("/categories/create", {
      name: name,
      id: id,
      pre: pre_node_id(NODE)
    }, function(data){
      NODE.id = data;
      if($("#note_category_id").get(0)){
        $("#note_category_id").val(node_id(NODE));
      }
    } );
  } else {
    $.post("/categories/update", {
      name: name,
      pre: pre_node_id(NODE),
      id: id,
      _method: 'put'
    });
  }

}

function move_node(NODE, TREE_OBJ) {
  var parent_id = node_id(TREE_OBJ.parent(NODE));
  var id = node_id(NODE);
  $.post("/categories/update", {
    id: id,
    pre: pre_node_id(NODE),
    parent_id: parent_id,
    _method: 'put'
  });
}

function remove(NODE) { 
  $.post("/categories/destroy", {
    id: id
  });
}

function check_delete(NODE) {
  id = NODE.id;
  if (id == "c_0") {
    alert("此分类不可删除");
    return;
  }
  if($(NODE).is(".haschild")) {
    iXue_alert("请删除分类下的Note再删除分类！");
    return false;
  }
  if(confirm("该操作将同时删除所有的子类，并将相关知识归为未分类。\n确定删除吗？")){
    return true
  }else{
    return false
  }
}

function right_loading(obj) {
  $(obj).css({
    background: "url('/images_old/indicator.gif') right center no-repeat"
  });
}

function right_loaded(obj) {
  $(obj).css({
    background: "transparent"
  });
}

function change_bg(a){
  if(a){
    $("#categories a.clicked").removeClass("clicked");
    $(a).addClass("clicked");
  } else{
    $("#uncategory").removeClass("clicked").trigger("blur");
  }
}

function close_send_msg(){
  $('#send_msg_dialog').dialog("close");
}

function send_msg(user_id,user_name) {
  if(user_id == 0) {
    self.location = "/login";
    return;
  }
  if($('#send_msg_dialog').length) {
    $('#send_msg_dialog').remove();
  }
  var d = $("<div id='send_msg_dialog' style='display:none' title='给"+ user_name +"发送消息'></div>")
  .append("<div id='send_msg_c'>正在加载...</div>");
  $(document.body).append(d);
  d.dialog({
    autoOpen: false
  // width: 345,
  // height: 365,
  // buttons: {
  // 			"取消": function() {
  // 				$('#send_msg_dialog').dialog("close");
  // 			}
  // 		}
  }).dialog("open");
  $("#send_msg_c").load("/messages/new?user_id="+ user_id);
}

function dialog_from_url(url, title, id) { 
  if(!id) id = "from_url_dialog"
  if($('#' + id).length) {
    $('#' + id).remove();
  }
  var d = $("<div id='" + id + "' style='display:none' title='"+ title +"'></div>")
  .append("<div id='" + id + "_c'>正在加载...</div>");
  $(document.body).append(d);
  d.dialog({
    autoOpen: false,
    buttons: {
      "取消": function() {
        $("#" + id).dialog("close");
      }
    }
  }).dialog("open");
  $("#" + id + "_c").load(url);
}

function dismiss(obj) {
  $(obj).after($("<span/>").text($(obj).text())).remove();
}
var xuetang_task_interval;
function poll_task(task_id, func, per_second) {
  if(!per_second) per_second = 5;
  if(!func) func = function(){};
  xuetang_task_interval = setInterval(function(){
    $.get("/tasks/" + task_id, function(data){
      clearInterval(xuetang_task_interval);
      func(data);
    });
  }, per_second * 1000);
}

function highlight_code(){
  sh_highlightDocument('/javascripts/code/lang/', '.min.js');
}

function go_pay(id){
  $.blockUI({
    message: $('#block_msg'),
    css: {
      backgroundColor: '#82BD1E',
      color: '#fff',
      padding: "20px",
      "line-height": "20px"
    }
  });
  //增加报名记录
  $.get("/kecheng/confirm_apply/" + id, {
    need_pay: "true"
  });
  //pay
  $("#payment_form_" + id).get(0).submit();
}

function login_and_go(url) {
  if(url == "#reload") {
    xuetang_go_url = self.location.href;
  } else {
    xuetang_go_url = url;
  }
  if(!logined){
    $("#ajax_login_box").dialog("open");
  }else{
    do_after_ajax_login_success() ;
  }
	
}

function do_after_ajax_login_success() {
  if( /^func,.*$/.exec(xuetang_go_url)){
    var func_call = xuetang_go_url.split(",") ;
    var func_name =   func_call  [1];
    var params =  func_call.slice(2,func_call .length);
    for(var i=0;i<params.length;i++){
      params[i]="\'"+params[i]+"\'"
    }
    params = params.join(",");
          
    eval(func_name+'('+params+')');
    $("#ajax_login_box").dialog("close");
  }else{
    self.location = xuetang_go_url;
  }
}

function ajax_login(form) {
  tip();
  $.post("/session/js_login", $(form).serialize(), function(data){
    if(data == "true") {
      do_after_ajax_login_success() ;
      logined=true;
    } else {
      $("#ajax_login_box .msg").html("登陆失败，请重试！");
    }
    close_tip();
  });
}

function show_more_cats(obj){
  $(">span", $(obj).parent()).show();
  $(obj).remove();
}

