/***********************************************************************************
*The rules of variable name:
*The front of underline is function name,while the behind of it is page name.
*Such as,shortenWords_pub. shortenWords is function name, and pub means for public.
*getAccountGroupJson_multiselect.getAccountGroupJson is function name, and multiselect
*means the function is only for multiselect page.
*
*************************************************************************************/
var first_symbol = true;
$(function(){ 
	if(first_symbol)
	{
	   first_symbol = false;
	   img = $("<img/>");
	   img.attr("src","../../static/imgs/button_Hover.png");
	   img.attr("style","display:none");
	   $("body").append(img);
	   img.attr("src","../../static/imgs/refresh_Hover.png");
	   img.attr("src","../../static/imgs/button_Down.png");	   
	   img.attr("src","../../static/imgs/refresh_Down.png");
	}
    
}) 

String.prototype.transfer=function() 
{ 
	if(arguments.length==0) return this; 
	for(var s=this, i=0; i<arguments.length; i++) 
	s=s.replace(new RegExp("\\{"+i+"\\}","g"), arguments[i]); 
	return s; 
}

function shortenWords_pub(words,limit,ellipsis)
   {
      if(words.length >= limit)
      {
         words = words.substring(0,limit);
         if(ellipsis)
         {
            words += "...";
         }
         
      }
      return words;
   }
   
   

function stopPropagation_pub(e)
{
   var e=window.event || event;
   if(e.stopPropagation)
   {
	  e.stopPropagation();
   }
   else
   {
	  e.cancelBubble = true;
   } 
}
   
function modal_pub(html)
{
    var newMaskID = "mask";  //遮罩层id
    var  newMaskWidth =document.body.scrollWidth;//遮罩层宽度
    var  newMaskHeight =document.body.scrollHeight;//遮罩层高度    
      //mask遮罩层  
    newMask = document.createElement("div");//创建遮罩层
    newMask.id = newMaskID;//设置遮罩层id
    newMask.style.position = "absolute";//遮罩层位置
    newMask.style.zIndex = "30";//遮罩层zIndex
    newMask.style.width = "100%";//设置遮罩层宽度
    newMask.style.height = "100%";//设置遮罩层高度
    newMask.style.top = "0px";//设置遮罩层于上边距离
    newMask.style.left = "0px";//设置遮罩层左边距离
    newMask.style.background = "#fff";//#33393C//遮罩层背景色
    newMask.style.filter = "alpha(opacity=95)";//遮罩层透明度IE
    newMask.style.opacity = "0.70";//遮罩层透明度FF
    document.body.appendChild(newMask);//遮罩层添加到DOM中
   
    //新弹出层
    var newDivWidth = 300;//新弹出层宽度
    var newDivHeight = 200;//新弹出层高度
    newDiv = document.createElement("div");//创建新弹出层
    newDiv.id = "newDivID";//设置新弹出层ＩＤ
    newDiv.style.position = "absolute";//新弹出层位置
    newDiv.style.zIndex = "9999";//新弹出层zIndex
 
    newDiv.style.width = newDivWidth + "px";//新弹出层宽度
    newDiv.style.height = newDivHeight + "px";//新弹出层高度
    var newDivtop=document.body.scrollTop + newMask.style.height/2  - newDivHeight/2;//新弹出层距离上边距离
    var newDivleft=document.body.scrollLeft + newMask.style.width/2 - newDivWidth/2;//新弹出层距离左边距离
    newDiv.style.top = "50%";//新弹出层距离上边距离
    newDiv.style.left = "50%";//新弹出层距离左边距离
    //newDiv.style.background = "#fff";//新弹出层背景色
    //newDiv.style.border = "1px solid #333";///新弹出层边框样式
    newDiv.style.margin = "-100px 0 0 -150px";
    
    //var newImg = document.createElement("img");
    //newImg.src = '../../static/imgs/pb/loading.gif';
    //newDiv.innerHTML = "<img src='../../static/imgs/pb/loading.gif'/>";//新弹出层内容
    //newImg.style.margin = "50px 0 0 100px";
    //newDiv.appendChild(newImg);
   document.body.appendChild(newDiv);//新弹出层添加到DOM中
}

function getAccountGroupJson_multiselect()
{
    $.ajax({
		    url : '/PB/LoadAccountGroupData?now=' + new Date().getTime(),
			async : false,
			dataType : 'json',
			success : function(result){
			   expandAccountGroup_multiselect(result);
			}
	});
}
   
function expandAccountGroup_multiselect(accountGroup)
{
    base = $("#container");
    ul = $("<ul />")
	first = 1;
	var groupsUl = null;
	var li = null;
	var a = null;
	jQuery.each(accountGroup,function(account,groups)
	{	   
	   li = $("<li />");
	   a = $("<a />");  
	   if (account == "")
	   {
		  a.text(PBMainVew_ComBox_PhoneAccount);
	   }
	   else
	   {
		  a.text(account);
	   }
	   if (first == 1)
	   {
		  a.attr("class","firstitemaopened");
		  first = 0;
	   }
	   else
	   {
		  a.attr("class","closed");
	   }
	   li.append(a);
	   groupsUl = $("<ul />")    
	   jQuery.each(groups,function(index,group)
	   {		                 
		  var groupLi = $("<li />");
		  groupLi.attr("title",account);
		  if($.inArray(group,selectedGroups) != -1)
		  {
			  groupLi.addClass("checked");
		  }
		  groupLi.text(group);
		  groupsUl.append(groupLi);
		});
		addGroupLi = $("<li />");
		addGroupLi.attr("title",account);
		addGroupImg = $("<img/>");
		addGroupImg.attr("src","../../static/imgs/myspacesmall.png");
		addGroupImg.attr("style","margin:3px 0px 0px 0px");
		addGroupImg.attr("title",PBMainView_WEB_ADDGROUP);
		addGroupImg.attr("alt",account);
		addGroupButton = $("<input />");
		addGroupButton.attr("type","button");
		addGroupButton.attr("title",account);
		addGroupButton.attr("value",PBMainView_WEB_ADDGROUP);
		addGroupLi.append(addGroupImg);
		//addGroupLi.append(addGroupButton);
		groupsUl.append(addGroupLi);
		li.append(groupsUl);
		ul.append(li);
   });
		         /*-------var li = $("<li />");
		         var span = $("<span />");
		         addGroup = $("<input />");
		         addGroup.attr("type","button");
		         addGroup.attr("value","addGroup");
		         addGroup.attr("onclick","modalConfirm()");
		         span.append(addGroup);
		         joinGroup = $("<input />");
		         joinGroup.attr("type","button");
		         joinGroup.attr("value","joinGroup");
		         joinGroup.attr("onclick","join()");
		         span.append(joinGroup);
		         cancel = $("<input />");
		         cancel.attr("type","button");
		         cancel.attr("value","cancel");
		         cancel.attr("onclick","out()");
		         span.append(cancel);
		         
		         span.attr("class","closed");;
		         li.append(span);
		         ul.append(li);---------*/		         
	groupsUl.addClass("lilastitemul");
	ul.attr("class","navBase");
	base.append(ul);
	attachAccountClickHandler_multiselect();
	attachGroupClickHandler_multiselect($(".navBase li li"));
	attachAddGroupClickHandler_multiselect();
	
}

function attachAccountClickHandler_multiselect()
{
    $("#container").click(function(e){
        stopPropagation_pub(e);
        
		/*if($$(this).hasClass("firstitemaopened"))
		{
		    $$(this).removeClass().addClass("firstitemclosed");
		}
		else if ($$(this).hasClass("firstitemclosed"))
		{
		    $$(this).removeClass().addClass("firstitemaopened");
		}
		else if ($$(this).hasClass("closed"))
		{
		    $$(this).removeClass().addClass("aopened");
		}
		else if ($$(this).hasClass("aopened")){
		    $$(this).removeClass().addClass("closed");
		}
		//$$(this).parent().siblings().find("a").next().slideUp("fast");
		$$(this).next().slideToggle();*/
		
    });
}

function attachGroupClickHandler_multiselect(lis)
{
    lis.each(function(index){
	    $(this).click(function(){
		if($(this).children().length >= 1)
		{
		   return;
		}
		
		addGroup = [];
		rmGroup = [];
		liSelected = $(this);
		selectedAccount = null;
		isChangeAccount = false;
		if (! $(this).hasClass("checked"))
		{
		   addGroup.push($(this).text());
		   selectedAccount = $(this).attr("title");
		   tip = "";
		   if(currAccount == null)
		   {
			  if (selectedAccount == "")
			  {
			      tip = MULTISELECT_MERGE_MANY_TO_ONE.transfer(PBMainVew_ComBox_PhoneAccount);
			  }
			  else
			  {
			      tip = MULTISELECT_MERGE_MANY_TO_ONE.transfer(selectedAccount);
			  }
			  isChangeAccount = true;
		    }
			else if (currAccount != selectedAccount)
			{
			    para1 = currAccount;
			    para2 = selectedAccount;
				if (para1 == "")
				{
				    para1 = PBMainVew_ComBox_PhoneAccount;
				}
			    if (para2 == "")
			    {
			        para2 = PBMainVew_ComBox_PhoneAccount;
			    }
			    tip = MULTISELECT_TRANSFER_OTHER_TO_ONE.transfer(para1,para2);
			    isChangeAccount = true;
			 }
			 if(isChangeAccount)
			 {
			     $('#content').html(tip);
			     hasMask = true;
			     art.dialog({
							title : Friendly_Tip,
							content : $('#confirmArea')[0],
							okVal: PB_BUTTON_OK,
							cancelVal: PBMainView_WEB_CANCEL,
							lock : true,
							background : '#fff',
							opacity : 0.7,
							ok : function(e) {									   
								this.close;
								stopPropagation_pub(e);
								currAccount = selectedAccount;
								jQuery.each($("#container .checked:[title != '"+currAccount+"']"),function(){
									    rmGroup.push($(this).text());				             
								});
								join_multiselect();
								hasMask = false;						
												   
							}, 
							cancel : function(e){
								this.close;
								stopPropagation_pub(e);
								hasMask = false;
								
							}
				  });
			   }
			   else
			   {
			      join_multiselect();
			   }	                              
			}
	        else
	        {
	           rmGroup.push($(this).text());                       
			   join_multiselect();
	        }		             
		});
    });
    
   	
}

function attachAddGroupClickHandler_multiselect()
{
   $(".navBase li li img").click(function(e){
       stopPropagation_pub(e);
       currAddGroupButton = $(this);
       addGroupModal_multiselect($(this).attr("alt"));
   });
}

function join_multiselect()
{

   var item = {};
   item.addgroup = addGroup;
   item.rmgroup = rmGroup;
   item.changeacc = isChangeAccount;
   item.Account = currAccount;
   $(".navBase").slideUp("fast");
   modal_pub();
   $.post('/PB/setitemsgroup', item, function() {});
   timer = setTimeout("iterateState_multiselect()",1000); 
}
   
function iterateState_multiselect()
{
   $.getJSON("/PB/LoadAccGroupChagetResult?"+Math.random(),
   function(data){
      if (data["finish"])
      {
         if(data["success"])
         {
            jQuery.each($(".navBase li li"),function(){
				if($.inArray($(this).text(),addGroup) != -1)
				{
				   $(this).removeClass().addClass("checked");
				}
				if($.inArray($(this).text(),rmGroup) != -1)
				{
				   $(this).removeClass();
				}					             
			});
			addGroup = [];
			rmGroup = [];
		  }
          document.body.removeChild(newMask);//移除遮罩层   
          document.body.removeChild(newDiv);////移除弹出框
          clearTimeout(timer);
       }
       else
       {
          timer = setTimeout("iterateState_multiselect()",1000); 
       }
   });         
}

function addGroupModal_multiselect(account)
{
   $("#userDefindGroup").val('');
   $("#userDefindGroupWrong").hide();
   hasMask = true;
   art.dialog({
				title: PBMainView_WEB_USERDEF_CONTACTINFO,
				content: $('#userGroupTwo')[0],
				lock: true,
				okVal: PB_BUTTON_OK,
				cancelVal: PBMainView_WEB_CANCEL,
				background:'#fff',
				opacity: 0.7,
				ok: function(e){
				               stopPropagation_pub(e);
							   var name = $("#userDefindGroup").val();
							   if($.trim(name) == "")
							   {
								   $("#userDefindGroupWrong").html(PBMainView_WEB_GROUPNAME_CANOT_EMPTY).show();
								   return false;
							   }else if(name.length > groupLen)
							   {
								   $("#userDefindGroupWrong").html(PBMainView_WEB_GROUPNAME_TOOLONG).show();
								   return false;
							   }
							   else
							   {							       
                                   if (!compareAccountGroup_multiselect(name))
                                   {
                                      $("#userDefindGroupWrong").html(PBMainView_WEB_GROUPNAME_EXISTS).show();
                                      return false;
                                   }
                                   else
                                   {
                                      var data = {};
								      data.Name = name;
								      data.Account = account;
								      currAddGroupName = name;
								      modal_pub();																
								      $.post("/PB/AddGroup",data,function(){			
								      });
								      timer = setTimeout("iterateAddGroupState_multiselect()",0); 
                                   }								  
								}
					            hasMask = false;							
				},
				cancel: function(e)
				{
				   stopPropagation_pub(e);
				   hasMask = false;
				   this.close;	    
				}
   });
}

function iterateAddGroupState_multiselect()
{
   $.getJSON("/PB/LoadGroupAddResult?"+Math.random(),
   function(data){
      if (data["finish"])
      {
         if(data["success"])
         {
            brother = currAddGroupButton.parent();
            var li = $("<li/>");
            li.attr("title",brother.attr("title"));
            li.text(currAddGroupName);
            li.insertBefore(brother);
            attachGroupClickHandler_multiselect(li);
            currAddGroupName = null;
            currAddGroupButton = null;
		  }
          document.body.removeChild(newMask);//移除遮罩层   
          document.body.removeChild(newDiv);////移除弹出框
          clearTimeout(timer);
       }
       else
       {
          timer = setTimeout("iterateAddGroupState_multiselect()",1000); 
       }
   });       
}

function clearAddGroupArea_multiselect()
{
   $("#userDefindGroup").val('');
   $("#userDefindGroupWrong").val('');
   $("#userDefindGroupWrong").hide();
}
  
function expandContacts_multiselect(contacts)
{
   var table = $("#Contacts");
   jQuery.each(contacts,function(index,contact){
       var tr = $("<tr />");
       var td = $("<td />");
       var img = $("<img />");
       if (contact["Photo"] != "")
       {
          img.attr("src","data:image/png;base64,"+contact["Photo"]);
       }
       else
       {
          if (contact["StorageLocation"] == 0)
          {
            img.attr("src","/static/imgs/avatar.png");
          }
          else
                if (sim_ecount == 1)
                {
                    img.attr("src","/static/imgs/contacts_default_sim.png");
                }
                else
                {
                    if (contact["StorageLocation"] == 1)
                    {
                        img.attr("src","/static/imgs/contacts_default_sim1.png");
                    }
                    else
                    {
                        img.attr("src","/static/imgs/contacts_default_sim2.png");
                    }
                }
       }
       img.attr("style","margin:4px 0px 0px 0px");
       img.attr("width","30");
       img.attr("height","30");
       td.append(img);
       tr.append(td);
       td = $("<td />");
       td.attr("title",contact["Name"]);
       td.html(shortenWords_pub(contact["Name"],10,true));
       tr.append(td);
       td = $("<td />");
       phones = "";
       jQuery.each(contact["PhoneNumber"],function(index,phone){
         if (index != 0)
         {
            phones += ";";
            phones += phone["Number"];
         }
         else
         {
             phones += phone["Number"];  
          }           
       });
       td.attr("title",phones);
       td.html(shortenWords_pub(phones,20,true));
       tr.append(td);
       table.append(tr);
   });
}

function compareAccountGroup_multiselect(groupName)
{
   var symbol = true;
   $.ajax({
		    url : '/PB/LoadAccountGroupData?now=' + new Date().getTime(),
			async : false,
			dataType : 'json',
			success : function(result){
			   jQuery.each(result,function(account,groups)
				{
				   if(groupName != null)
				   {
				      if($.inArray(groupName,groups) != -1)
				      {
				          symbol = false;
				      }
				   }				   
				   var lastChild = null;
				   $(".navBase li li[title='"+account+"']").each(function(index){
				       if($(this).children().length >= 1)
						{
						   lastChild = $(this);
						}
					   if(lastChild == null)
					   {
					      index = -1;
				          if((index = $.inArray($(this).text(),groups)) == -1)
						  {						      
						      $(this).remove();
						  }
						  else
						  {
						      delete groups[index];
						  }
					   }
					   			
				   });
				   if(groups.length > 0)
				   {
					   jQuery.each(groups,function(index,group){
						   if(lastChild != null)
						   {
						       var li = $("<li/>");
						       li.attr("title",account);
						       li.text(group);
						       li.insertBefore(lastChild);
						       attachGroupClickHandler_multiselect(li);
						   }   
					   });
				   }
			   });
			}
	});
	return symbol;
}

function out_multiselect()
{
   if(!hasMask)
   {
      $(".navBase").slideUp("fast");
   }
   
}

function sendMsg_multiselect()
{
   $.post('/PB/sendsms', {}, function() {});  
}

function combine_multiselect()
{
   $.post('/PB/mutlimerge', {}, function() {});  
}