var curZIndex = 1000;
var curFormId = "";
var formList = {};
var homePage = null;

(function($){
  //拖拽插件,参数:id或object
  $.Move = function(_this){
      if(typeof(_this)=='object'){
          _this=_this;
      }else{
          _this=$("#"+_this);
      }
      if(!_this){return false;}

      _this.css({'position':'absolute'}).hover(function(){$(this).css("cursor","move");},function(){$(this).css("cursor","default");})
      _this.mousedown(function(e){//e鼠标事件
          var offset = $(this).offset();
          var x = e.pageX - offset.left;
          var y = e.pageY - offset.top;
          _this.css({'opacity':'0.3'});
          $(document).bind("mousemove",function(ev){//绑定鼠标的移动事件，因为光标在DIV元素外面也要有效果，所以要用doucment的事件，而不用DIV元素的事件
              _this.bind('selectstart',function(){return false;});
              var _x = ev.pageX - x;//获得X轴方向移动的值
              var _y = ev.pageY - y;//获得Y轴方向移动的值
              _this.css({'left':_x+"px",'top':_y+"px"});
          });
      });

      $(document).mouseup(function(){
          $(this).unbind("mousemove");
          _this.css({'opacity':''});
      })
  };
})(jQuery);

function changeTheme(id, path) {
  if(!confirm("切换风格会造成未保存的数据丢失，确定切换吗？")) return;
  
  var service = new TaskMsgService();
  service.app = "sys";
  service.path = "theme/setUserTheme";
  service.request({id: id, path: path}, onSetUserTheme);
};

function onSetUserTheme(req, res) {
  location = req.path;
}

function openForm(title,url,icon,width,height, srcElement, opener) {
  if(!title) {
	  alert("请设置窗口标题！");
	  return;
	}
	if(!url) {
	  alert("请设置窗口URL路径！");
	  return;
	}
  if(url.indexOf("/")!=0 && url.indexOf("../")!=0 && url.indexOf("http")!=0) 
    url = "/"+url;
  var form = $("#divFormTemplate").clone();
	form.attr("id", "form"+curZIndex);
	curFormId = "form"+curZIndex;
	form.css("zIndex", curZIndex);
	curZIndex++;
	if(width) form.css("width", width);
	if(height) form.css("height", height);
	var top = (document.documentElement.clientHeight-60-getPixel(form.css("height")))/2;
	if(top>0) form.css("top", parseInt(top)+"px");
	var left = (document.documentElement.clientWidth-getPixel(form.css("width")))/2;
	if(left>0) form.css("left", parseInt(left)+"px");
	if(icon) form.find("div.divFormIcon").css("backgroundImage", "url("+icon+")");
	form.find("div.divFormTitle").text(title);
	form.find("iframe.frameForm").attr("src", url);
	$.Move(form);
	form.appendTo("#bodyConsole");
  form.srcElement = $(srcElement);
  form.opener = opener;
  formList[curFormId] = form;
  $("#divMask").show();
	form.show();
}

function closeSelfForm(formCloseBtn) {
  var form = formCloseBtn.parent().parent();
  closeForm(form);
}

function closeCurForm() {
  closeForm($("#"+curFormId));
}

function closeForm(form) {
  var formId = form.attr("id");
  delete formList[formId];
  form.remove();
  if(formId==curFormId) {
    curFormId = "";
    for(formId in formList) {
      curFormId = formId;
      return;
    }
  }
  $("#divMask").hide();
}

function getCurForm() {
  return formList[curFormId];
}

function openTabPage(title, url) {
  gotoPage(url);
}

function gotoPage(url) {
  if(url.indexOf("/")!=0 && url.indexOf("../")!=0 && url.indexOf("http")!=0) 
    url = "/"+url;
  $("#ifm").attr("src", url);
}
  
function changeFrameHeight(){
  var ifm= document.getElementById("ifm"); 
  ifm.height=document.documentElement.clientHeight-60;
}

window.onresize=function(){  
  changeFrameHeight();
} 

function showApp(cid, url) {
  $("#divAppType_"+cid).removeClass("selectedAppType");
  $("#divAppType_"+cid).find(".appTypeRight").hide();
  $("#divAppList_"+cid).hide();

  gotoPage(url);
}

function appTypeOnMouseOver(div, cid) {
  $(".divAppType").removeClass("selectedAppType");
  $(div).addClass("selectedAppType");
  $(div).find(".appTypeRight").show();
  $(".appList").hide();
  if(cid) $("#divAppList_"+cid).show();
}

function appTypeOnMouseOut(div, cid) {
  $(div).removeClass("selectedAppType");
  $(div).find(".appTypeRight").hide();
  if(cid) $("#divAppList_"+cid).hide();
}

function appListOnMouseOver(div, cid) {
  $(".divAppType").removeClass("selectedAppType");
  $("#divAppType_"+cid).addClass("selectedAppType");
  $("#divAppType_"+cid).find(".appTypeRight").show();
  $(div).show();
}

function appListOnMouseOut(div, cid) {
  $("#divAppType_"+cid).removeClass("selectedAppType");
  $("#divAppType_"+cid).find(".appTypeRight").hide();
  $(div).hide();
}

function appOnMouseOver(div) {
  $(".appInfo").removeClass("selectedApp");
  $(div).addClass("selectedApp");
}

function appOnMouseOut(div) {
  $(div).removeClass("selectedApp");
}

$(function(){
  var loginname = sessionStorage.getItem("l");
  $("#divUserName").html(loginname);
  var sex = sessionStorage.getItem("sex");
  if(sex==1) $("#imgUserHead").attr("src", "/images/icon/48/women.png");
  var orgName = sessionStorage.getItem("orgname");
  $("#divOrgName").html(orgName);

  var service = new TaskMsgService();
  service.app = "sys";
  service.path = "theme/getConsoleInfo";
  service.request(null, onLoadAppData);
});
  
function onLoadAppData(args, res) {
  var categorys = {};
  var apps = {};
  for(var i=0;i<res.categorys.length;i++) {
    var c = res.categorys[i];
    c.apps = [];
    categorys[c.id] = c;
  }
  for(var i=0;i<res.apps.length;i++) {
    var app = res.apps[i];
    apps[app.app_id] = app;
    if(app.category_id in categorys) categorys[app.category_id].apps.push(app.app_id);
  }

  var div = $("#divAppTypes");
  for(var i=0;i<res.categorys.length;i++) {
    var c = categorys[res.categorys[i].id];
    if(c.apps.length==0 || c.parent_id!=0) continue;
    var str = "<div id=\"divAppType_"+c.id+"\" class=\"divAppType\" "
      +"onmouseout=\"appTypeOnMouseOut(this, "+c.id+")\" onmouseover=\"appTypeOnMouseOver(this, "+c.id+")\">";
    var iconPath = "/images/icon/16/app_white.png";
    if(c.icon_code) {
      iconPath = "/TaskMsgDownload?thumbnail=true&fileCode="+c.icon_code
        +"&sessionId="+tmClient.getSessionId();
    }
    str += "<img src=\""+iconPath+"\" class=\"appTypeImg\" />";
    str += "<div class=\"appTypeName\">"+c.name+"</div>";
    str += "<div class=\"appTypeRight\">&gt;</div>";
    str += "</div>";
    $(str).insertBefore("#divAppType_exit");
    str = "<div id=\"divAppList_"+c.id+"\" class=\"appList\" style=\"top:"+(150+i*40)+"px;\" "
        +"onmouseout=\"appListOnMouseOut(this, "+c.id+")\" onmouseover=\"appListOnMouseOver(this, "+c.id+")\">";
    for(var j=0;j<c.apps.length;j++) {
      var app = apps[c.apps[j]];
      str += "<div id=\"divApp_"+app.id+"\" class=\"appInfo\" "
        +"onmouseout=\"appOnMouseOut(this)\" onmouseover=\"appOnMouseOver(this)\""
        +" onclick=\"showApp("+c.id+", '"+app.url_web+"')\">";
      if(app.icon_path || app.icon_code) {
        var iconPath = app.icon_path;
        if(!iconPath)
          iconPath = "/TaskMsgDownload?thumbnail=true&fileCode="+app.icon_code
            +"&sessionId="+tmClient.getSessionId();
        str += "<img src=\""+iconPath+"\" class=\"appImg\" />";
        str += "<div class=\"appName\">"+app.app_name+"</div>";
      } else {
        str += "<div class=\"appName\" style=\"margin-left:44px\">"+app.app_name+"</div>";
      }
      str += "</div>";
    }
    str += "</div>";
    $("body").append(str);
  }

  for(var i=0;i<res.themes.length;i++) {
    var theme = res.themes[i];
    if(theme.id=="3") {
      $("#divSysSkin").append("<div>√ "+theme.name+"</div>");
    } else {
      $("#divSysSkin").append("<div onClick=\"changeTheme('"+theme.id+"','"
        +theme.path+"')\">&nbsp;&nbsp;&nbsp;"+theme.name+"</div>");
    }
  }

  if(res.homePage) {
    homePage = res.homePage;
    $("#divAppType_home").show();
    gotoPage(res.homePage);
  }
};

function showNewMsg(){
  //alert("查看消息");
  $("#newMsgCount").hide();
}

function help(){
  //alert("帮助");
}

function showUserSetting(type){
  if(type==0){
    $(".divUserSetting").show();
  }else{
    $(".divUserSetting").hide();
  }
}

function openForm(title,url,icon,width,height,srcElement,opener) {
  if(!title) {
	  alert("请设置窗口标题！");
	  return;
	}
	if(!url) {
	  alert("请设置窗口URL路径！");
	  return;
	}
  if(url.indexOf("/")!=0 && url.indexOf("../")!=0 && url.indexOf("http")!=0) 
    url = "/"+url;
  var form = $("#divFormTemplate").clone();
	form.attr("id", "form"+curZIndex);
	curFormId = "form"+curZIndex;
	form.css("zIndex", curZIndex);
	curZIndex++;
	if(width) form.css("width", width);
	if(height) form.css("height", height);
	var top = (document.documentElement.clientHeight-60-getPixel(form.css("height")))/2;
	if(top>0) form.css("top", parseInt(top)+"px");
	var left = (document.documentElement.clientWidth-getPixel(form.css("width")))/2;
	if(left>0) form.css("left", parseInt(left)+"px");
	if(icon) form.find("div.divFormIcon").css("backgroundImage", "url("+icon+")");
	form.find("div.divFormTitle").text(title);
	form.find("iframe.frameForm").attr("src", url);
	$.Move(form);
	form.appendTo("#bodyConsole");
  form.srcElement = $(srcElement);
  form.opener = opener;
  formList[curFormId] = form;
  $("#divMask").show();
	form.show();
}

function gotoHome() {
  gotoPage(homePage);
}

function quit() {
  if(!confirm("确定退出？")) return;
  var service = new TaskMsgService();
  service.app = 'sys';
  service.path = 'quit';
  service.request(null);
  location = '/index.html';
}