

//��ʾ��ϸ��Ϣ
var showInfo = function() {

    SetPhoneNumber2Sms(infoData);
	$('.inChat').focus(function(){
		$(this).addClass('inChatFocus');						
	})
	$('.inChat').blur(function(){
		$(this).removeClass('inChatFocus');						
	})
	SetSendButtonStatus();
	
	//��ʼ�������?
	$("#name_vie").html(shortenWords_pub(infoNameData.name,15,false));
	$("#nickname_vie").html(infoNameData.nickname ? infoNameData.nickname : "&nbsp;");
	creatSelected();

	var table = $("<table />")
	for (var k in infoData) {
		$.each(infoData[k], function(i, n) {
			for (var m in n) {
				$("<tr />").html('<td>' + shortenWords_pub(m,15,false) + "&nbsp;" + '</td><td><font color="#707070" size="2">:&nbsp;' + shortenWords_pub(n[m],25,true) + '</font></td></tr>').appendTo(table);
			}
		})
	}
	
	$("#optionContainer").append(table);
	$('#contact-form,#sendMsgForm').jqTransform();
	$('#grupDefine>.jqTransformSelectWrapper>ul li a:not(:first)').each(function() {
		$(this).addClass('seling');
	})
	var len = $('#grupDefine ul li a.seling').length;
	$('#grupDefine>.jqTransformSelectWrapper span').html(len == 0 ? PBMainView_OneInfoPanel_ScrollPanel_BtnGroup : $('#grupDefine ul li a.seling:eq(0)').html());
	$('#grupDefine>.jqTransformSelectWrapper>ul li:eq(0)').hide();
	$('#addWrap>.jqTransformSelectWrapper>ul li:eq(0)').hide();
	for (var p in AccountSelData) {
		if (AccountSelData[p].length == 0) {
			$('#grupDefine').find('div:first').removeClass().addClass('jqTransformSelectWrapper1');			
		}
	}
	if (infoImage.Photo) {
		$('#avatar').html('<img src="data:image/png;base64,' + infoImage.Photo + '" width="70" height="70" />');
	}
	$("#account >div ul li a").removeClass().addClass("selecteDisable");
	$("#grupDefine >div ul li a").removeClass().addClass("selecteDisable");
}
//������ϸ��Ϣ�б�
var createSelect = function(type, dropable, j, key, val) {
	var liElement = [];
	liElement[0] = $('<select />');
	for (var i = 0, len = infoType[type].length; i < len; i++) {
		if (infoType[type][i] == key) {
			$('<option />').html(infoType[type][i]).attr('selected', 'selected').appendTo(liElement[0]);
		} else {
			$('<option />').html(infoType[type][i]).appendTo(liElement[0]);
		}
	}
	var name = infoTypeName[type][0];
	liElement[1] = $('<input />').attr({
		'type' : 'text',
		'rel' : infoTypeOther[j]
	}).val( val ? val : "");
	if (dropable) {
		//liElement[2] = $('<a />').html(PBMainView_MoreInfoPanel_BtnDelete).click(function() {
        liElement[2] = $('<img />').attr("src","/static/imgs/clear__.png").attr("style","margin:5px 0px 0px 0px").attr('title',PBMainView_MoreInfoPanel_BtnDelete).click(function(){
       
			if (type == $(this).parents('ul').attr('rel')) {
				$(this).parents('ul').prev().attr('rel', type);
			}
			$(this).parents('ul').remove();
		});

	}
	$('#optionContainer ul[rel="' + type + '"]').removeAttr('rel').addClass('ulSlt');
	var ulElement = $('<ul />').attr({
		'rel' : type,
		'wording' : type
	}).addClass('ulSlt');

	for (var i = 0, len = liElement.length; i < len; i++) {
		ulElement.append(liElement[i]);
		liElement[i].wrap('<li class="li_' + i + '"/>');
	}
	ulElement.append('<li class="errorMsg"></li>')
	return ulElement;
}
//���������б?��ѡ��ݣ�
var creatSelected = function() {
	var num = '';
	for (var p in AccountSelData) {
		num = p;
	}
	$("#grupDefine").html("");
	var groupStr = "<select class='' name='group' id='group'>";
	groupStr += "<option value=''>" + PBMainView_OneInfoPanel_ScrollPanel_BtnGroup + "</option>";
	$(AccountSelData[num]).each(function(i, n) {
		groupStr += "<option value='" + i + "'>" + n + "</option>";
	})
	groupStr += "</select>";
	$("#grupDefine").html(groupStr);
}
//���������б�
var creatGroupSelect = function(num) {
	var num = num ? num : '';
	curGroup = num;
	$("#grupDefine").html("");
	var groupStr = "<select class='' name='group' id='group'>";
	groupStr += "<option value=''>" + PBMainView_OneInfoPanel_ScrollPanel_BtnGroup + "</option>";
	$(AccountData[num]).each(function(i, n) {
		groupStr += "<option value='" + i + "'>" + n + "</option>";
	})
	groupStr += "<option value=''>" + PBMainView_WEB_ADDGROUP + "</option>";
	groupStr += "</select>";
	$("#grupDefine").html(groupStr);
}
//�����˻��б�
var creatAccountSelect = function(flag) {
	var accountCur = true ? 'account' : 'accountView';
	var nameCur = true ? 'phoneaccount' : 'phoneaccountView'
	$('#' + accountCur).html("");
	var groupStr = "<select class='' name='" + nameCur + "' id='" + nameCur + "'>";
	if (flag) {
		for (var p in AccountData) {
			if (p == '')
				p = PBMainView_EditPanel_BR_StaticBox_CB_Type;
			groupStr += "<option>" + p + "</option>";
		}
	} else {
		for (var p in AccountSelData) {
			if (p == '')
				p = PBMainView_EditPanel_BR_StaticBox_CB_Type;
			groupStr += "<option>" + p + "</option>";
		}
	}
	groupStr += "</select>";
	$('#' + accountCur).html(groupStr);
}
//������
var SetPhoneNumber2Sms = function(numbers){	
	for (var k in numberData) {
		$.each(numberData[k], function(i, n) {
			for (var m in n) {
				$('<option />').html(n[m]).appendTo($('#sendMsg'));
			}
		})
	}
	
	
}

var imgWidth = 0;
var imgHeight = 0;
var jcrop_api;
var Jcrop_init = false;
function getImageUrlPath() {
	$.ajax({
		url : '/PB/loadImagePath?now=' + new Date().getTime(),
		async : false,
		dataType : 'json',
		success : function(result) {
			if (result.status == "wait") {
				setTimeout(function() {
					getImageUrlPath();
				}, 1000);
			} else {
				if (result.status == "finish") {
					jcrop_api.setImage(result.path);
					$('#imgText').val(result.path);
					imgWidth = result.width;
					imgHeight = result.height;
				}
			}
		}
	});
}
    function SetSendButtonStatus(){
		$.post("/SMS/GetSimInfo","",function(siminfo){
			var sim_string = '';
			var wording = '';
			var sim_info = siminfo.sim_info ;
			for(i=0;i<sim_info.length;i++){
				wording = GetButtonLabel(sim_info[i].SIMType,sim_info[i].SIMId,sim_info.length);
				if(sim_info[i].SimReady){
					sim_string += '<label class="sendButtom fl" SIMId="' + sim_info[i].SIMId + '">' + wording + '</label>';
				}
				else{
					sim_string += '<label class="sendButtom_Disable fl" SIMId="' + sim_info[i].SIMId + '">' + wording + '</label>';
				}
			}
			$("div.smsChat").append(sim_string);
		},"json")
	}
	
	function GetButtonLabel(simtype,simid,length){
		var label = "" ;
		if(length < 2){
			simid = 0;
		}
		if(simid == 1){
			if(simtype == 0){
				label = WEBSMS_SEND_SMS_1_0;
			}
			else if(simtype == 1){
				label = WEBSMS_SEND_SMS_1_1;
			}
			else if(simtype == 2){
				label = WEBSMS_SEND_SMS_1_2;
			}
			else{
				label = WEBSMS_SEND_SMS_1_UNKWON;
			}
		}
		else if(simid == 2){
			if(simtype == 0){
				label = WEBSMS_SEND_SMS_2_0;
			}
			else if(simtype == 1){
				label = WEBSMS_SEND_SMS_2_1;
			}
			else if(simtype == 2){
				label = WEBSMS_SEND_SMS_2_2;
			}
			else{
				label = WEBSMS_SEND_SMS_2_UNKWON;
			}
		}
		else if(simid == 0){
			if(simtype == 0){
				label = WEBSMS_SEND_SMS_0_0;
			}
			else if(simtype == 1){
				label = WEBSMS_SEND_SMS_0_1;
			}
			else if(simtype == 2){
				label = WEBSMS_SEND_SMS_0_2;
			}
			else{
				label = WEBSMS_SEND_SMS_0_UNKWON;
			}
		}
		else{
			if(simtype == 0){
				label = WEBSMS_SEND_SMS_UNKWON_0;
			}
			else if(simtype == 1){
				label = WEBSMS_SEND_SMS_UNKWON_1;
			}
			else if(simtype == 2){
				label = WEBSMS_SEND_SMS_UNKWON_2;
			}
			else{
				label = WEBSMS_SEND_SMS_UNKWON_UNKWON;
			}
		}
		return label;
	}
	
function Initial()
{
	if(first)
	{
	inner = $("#before").html();
	first = false;
	}
    if (!viewOrEdit) {

			showInfo();			
	}	
	else {
		editFlag = true;
		$("#edit").removeClass('save').addClass('cancel');
		editInfo();
	}

	//===================�༭==========================
	$("#edit").click(function() {
	    
		if (editFlag)
			return false;
		editFlag = true;
		viewOrEdit = true;
		$(this).removeClass('save').addClass('cancel');
		editInfo();
				
	});
	//==================�༭����===========================
	$("#cancel").click(function() {
		if(IsMerge)
		{
		   location.href = "multiselect.html";
		   return;
		}
		$('#before').html(inner);
		editFlag = false;
		viewOrEdit = false;
		Initial();
		
	});
	//===================�˻�ѡ���߼�==================
	$('#account ul li a').click(function() {
		if (!viewOrEdit)
			return;
		var num = $(this).html() == PBMainView_EditPanel_BR_StaticBox_CB_Type ? '' : $(this).html();
		creatGroupSelect(num);
		$('#contact-form').removeClass('jqtransformdone').jqTransform();
		$('#grupDefine>.jqTransformSelectWrapper>ul li:eq(0)').hide();
	});
	//===================��ѡ���߼�======================================
	$('#addWrap>.jqTransformSelectWrapper>ul li a').click(function() {
		if ($(this).attr('index')) {
			var key = function(idx) {
				var i = 0;
				for (var j in infoType) {
					if (++i == idx) {
						return j;
					};
				}
			}($(this).attr('index'));
			var k = $(this).attr('index') - 1;
			var ul = $('#optionContainer ul[rel="' + key + '"]');
			if (ul.length != 0) {
				ul.after(createSelect(key, true, k));
			} else {
				var len = $("#optionContainer ul[class = ulSlt]").length * 1;
				if (len == 0) {
					$('#optionContainer').append(createSelect(key, true, k));
				} else {
					//len = len > 2 ? len : 2;
					$('#optionContainer ul[class = ulSlt]:eq(' + (len - 1) + ')').after(createSelect(key, true, k));
				}
			}
			$('#contact-form').removeClass('jqtransformdone').jqTransform();
			$('.jqTransformSelectWrapper').each(function(index) {
				$(this).css('zIndex', 100 - index);
			})
			$(this).attr('class', '').parents('ul').find('li:eq(0) a').attr('class', 'selected');
			$('#addWrap span:eq(0)').html(PBMainView_WEB_SELECT);
		}
	});
//�ϴ�ͷ���¼�
	/*
	 $("#defaultPic").Jcrop({
	 aspectRatio:1
	 },function() {
	 jcrop_api = this;
	 });
	 */

	$('#avatar').click(function() {
		if (!viewOrEdit)
			return false;

		//return false;
		$('#imgText').val('');
		art.dialog({
			title : SELECT_YOUR_IMG,
			content : $('#uploadImg')[0],
			okVal: PB_BUTTON_OK,
			cancelVal: PBMainView_WEB_CANCEL,
			lock : true,
			padding : 0,
			width: '100%',
			height: '30%',
			background : '#fff',
			opacity : 0.7,
			ok : function() {
				this.close
				//alert(imgWidth+"==="+imgHeight);
				var path = $('#imgText').val();
				if (path == '')
					return;
				$('#loadPic img').attr('src', path);
				var inWidth = imgWidth + 50;
				var inHeight = imgHeight + 75;
				var outWidth = $('#wrap').width();
				var outHeight = $('#wrap').height() + 76;
				var left = (outWidth - inWidth) / 2;
				var top = (outHeight - inHeight) / 2;
				//alert(inWidth+":"+inHeight+":"+outWidth+":"+outHeight+":"+left+":"+top);
				//art.dialog({id: 'uploadAvater'}).position({'left':left});
				//�ǵ÷���jQuery(window).load(...)�ڵ��ã�����Jcrop�޷���ȷ��ʼ��

				var dialog = art.dialog({
					id : 'uploadAvater',
					lock : true,
					background : '#fff',
					opacity : 0.70,
					okVal: PB_BUTTON_OK,
			        cancelVal: PBMainView_WEB_CANCEL,
					content : $('#loadPic')[0],
					title : false,
					left : left + 'px',
					top : top + 'px',
					ok : function() {
						var data = {};
						data.path = path;
						/*
						 data.x = marginleftImg;
						 data.y = margintopImg;
						 data.w = widthImg;
						 data.h = heightImg;
						 */
						var jcropData = jcrop_api.tellSelect();
						data.x = jcropData.x;
						data.y = jcropData.y;
						data.w = jcropData.w;
						data.h = jcropData.h;
						$.post('/PB/cutImage', data, function(resp) {
							$('#avatar').html('<img src="data:image/png;base64,' + resp.img + '" width="70" height="70" />');
							//alert($('#avatar img').attr('src'));
						})
					},
					cancel : function() {
						//jcrop_api.destroy();
					}
				});
			},
			cancel : function() {
				//jcrop_api.release();
			}
		})
	});
     
	$('#imgButton').click(function() {
		var data = {};
		$.post('/PB/ImageAdd', data, function() {

		})
		setTimeout("getImageUrlPath()", 1000);
	});
	//=============================================
	$("#save").click(function() {
		document.getElementById("save").disabled=true
		var inputHaveContentLen = $(':input[type = text]').filter(function() {
			return $(this).val() != '';
		}).length;
		var inputErrorLen = $('li[class = errorMsg]').filter(function() {
			return $(this).css('display') != 'none';
		}).length;
		if (inputHaveContentLen == 0) {
			art.dialog({
				title : '',
				content : PBMainView_AddItem_Error,
				lock : true,
				background : '#fff',
				opacity : 0.7,
				icon : 'error',
				ok : function() {

				}
			})
			//alert('������ֻʣһ����Ϣ');
			return false;
		}
		if (inputErrorLen > 0)
			return;
		var data = {};
		data.Name_FirstName = $("#name").val();
		data.Nickname = $("#nickname").val();
		//if($.trim(data.Name_FirstName) == "" && $.trim(data.Nickname) == "") return false;
		var tempACctName = $("#phoneaccount").val();
		data.Account = tempACctName == PBMainView_EditPanel_BR_StaticBox_CB_Type ? "" : tempACctName;
		data.Group = [];
		var len = $('#grupDefine ul li a.seling').length;
		if (len == 0) {
			data.Group[0] = '';
		} else {
			$('#grupDefine ul li a.seling').each(function() {
				data.Group.push($(this).text());
			})
		}
		var dataArr = [];
		var dataArr = $("#optionContainer :input[type = text]");
		//dataArr.reverse();
		var arr = [];
		var arrOther = [];
		$(dataArr).each(function(i, n) {
			var val = $(this).val();
			var type = $(this).parents('ul').attr("wording");
			var index = $(this).parents('ul').find('a[class = selected]').attr('index') * 1;
			var tempName = infoTypeName[type][index];
			if ($.inArray(tempName, infoTypeOther) != -1) {//�ж��Ƿ����Զ������
				var nameOther = $(this).parents('ul').find('span').text();
				var tempNameOther = tempName + "-" + nameOther;
				if ($.inArray(tempNameOther, arrOther) != -1) {//�ж��Ƿ�������
					for (var i = 0, k = 0; i < arrOther.length; i++) {
						if (arrOther[i] == tempNameOther)
							k++;
						var name = tempNameOther + "-" + k;
					}
				} else {
					var name = tempNameOther + "-" + 0;
				}
				arrOther.push(tempNameOther);
				data[name] = val;
			} else {
				if ($.inArray(tempName, arr) != -1) {//�ж��Ƿ�������
					for (var i = 0, k = 0; i < arr.length; i++) {
						if (arr[i] == tempName)
							k++;
						var name = tempName + "-" + k;
					}
				} else {
					var name = tempName + "-" + 0;
				}
				arr.push(tempName);
				data[name] = val;
			}
		})
		data.StorageLocation = m_StorageLocation;
		var postCmd = "/PB/edit";
        
		if (IsMerge) {
			postCmd = "/PB/merge";
		}

		$.post(postCmd, data, function() {

		})
		});
		
		//send msg evet
	//$('.sendButtom').click(function(){
	 $('.sendButtom').live('click', function(){
		var data = {};
		data.number = $('#sendMsgForm .jqTransformSelectWrapper span').html();
		data.content = $('.inChat').val();
		data.SIMId = $(this).attr('SIMId');
		if (data.number != "")
		{
		   $.post("/SMS/send",data,function(){					
					
		   },"json")
		}
		else
		{
		   $('#PhoneTip').html(PBMainView_WEB_PHONE_CANOT_EMPTY);
		   $('.sendButtom').bind("mouseout",function(){
		   $('#PhoneTip').html("");									
	     });
		}
		
		$('.inChat').val("");	
		var data = {};
		data.content = "";
		data.number = "";
		$.post("/PB/input",data,function(){					
					},"json")		
	});
	
	$('.inChat').keyup(function(){
		var data = {};
		data.content = $('.inChat').val();
		data.number = $('#sendMsgForm .jqTransformSelectWrapper span').html();
		$.post("/PB/input",data,function(){					
					},"json")					
	});
    
    data = {}
	$.post('/PB/loadfinish', data, function() {

		})
}

function editInfo()
{
if (Jcrop_init == false) {
		$("#defaultPic").Jcrop({
			aspectRatio : 1
		}, function() {
			jcrop_api = this;
		});
		Jcrop_init = true;
	}
	if (IsMerge) {
		if (infoImage.Photo) {
			$('#avatar').html('<img src="data:image/png;base64,' + infoImage.Photo + '" width="70" height="70" />');
		}
	}
	$('#editorWrap').hide();
	$('#Sms').hide();
	$('#grupDefine').removeClass('fr').addClass('fl');
	
	$('#account').removeClass('fr').addClass('fl');
	
	$('#maininfor').append($('#editAccountGroup').html());
	$('#editAccountGroup').remove();
	//$('#accountView').hide();
	//$('#account').show();
	$('#grupDefine').removeClass('mart10').addClass('mart4');
	$('#account').removeClass('mart10').addClass('mart4');
	/*	
	$('#account>.jqTransformSelectWrapper>ul li:eq(0)').show();
	$('#account').find('div:first').removeClass().addClass('jqTransformSelectWrapper');
	------------------*/
	var selMenu;
	for (var p in AccountSelData) {
		curGroup = p;
		selMenu = p == '' ? PBMainView_EditPanel_BR_StaticBox_CB_Type : p;
	}
	creatGroupSelect(curGroup);
	//��ƺ��ǳ�
	var input = '<input id="name" type="text"  name="name" class="name" maxlength="320"/><input type="text" id="nickname" name="nickname" class="nickname mart4" maxlength="320"/>';
	$("#maininfor .mainInfor").empty().append(input);
	if (infoNameData.name != "")
	{
	   $("#name").val(infoNameData.name);
	}
	else
	{
	   $("#name").attr("placeholder",PBMainView_FuncBtn_BR_StaticBox_TC_Name);
	}
	if (infoNameData.nickname != "")
	{
	   $("#nickname").val(infoNameData.nickname);
	}
	else
	{
	   $("#nickname").attr("placeholder",PBMainView_EditPanel_NickNameSBox_Key);
	}
	
	//��ϸ��Ϣ
	$('#optionContainer').empty().append('<div class="claer"></div>');
	for (var k in infoData) {
		var x = function(key) {
			var i = 0;
			for (var j in infoType) {
				i++;
				if (key == j)
					return i - 1;
			}
		}(k);
		$(infoData[k]).each(function(i, n) {
			for (var m in n) {
				//var addFlag = i == 0 ? false : true;//�ж��Ƿ��������� false:��,true:��
				$('#optionContainer').append(createSelect(k, true, x, m, n[m]));
				$('#contact-form').removeClass('jqtransformdone').jqTransform();
				if ($.inArray(m, infoType[k]) == -1) {//�ж��Ƿ����Զ������
					$("#optionContainer ul[class = ulSlt]:last").find("span").html(m);
					$("#optionContainer ul[class = ulSlt]:last").find("li:eq(0) li:eq(0) a").attr("class", "");
					$("#optionContainer ul[class = ulSlt]:last").find("li:eq(0) li:last a").attr("class", "selected");
				}
			}
		})
	}
	$('#contact-form').removeClass('jqtransformdone').jqTransform();
	$('#grupDefine>.jqTransformSelectWrapper>ul li:eq(0)').hide();
	$('#account span').html(selMenu);
	$('#account>.jqTransformSelectWrapper ul li a').each(function(i, n) {
		if ($(this).text() == selMenu) {
			if (!$(this).hasClass('selected'))
				$(this).addClass('selected');
			$('#phoneaccount')[0].selectedIndex = i;
		} else {
			$(this).removeClass('selected');
		}
	})
	hasChild = false
	firstChild = ""
	$('#grupDefine>.jqTransformSelectWrapper>ul li a:not(:last)').each(function() {

		if ($.inArray($(this).text(), AccountSelData[curGroup]) > -1)
			{
				$(this).addClass('seling');
				if (! hasChild)
				{
					firstChild = $(this).text();
					hasChild = true;
				}
			}
	})
	
	var len = $('#grupDefine ul li a.seling').length;
	$('#grupDefine>.jqTransformSelectWrapper span').html(len == 0 ? PBMainView_OneInfoPanel_ScrollPanel_BtnGroup : $('#grupDefine ul li a.seling:eq(0)').text());
	if (hasChild)
	{
		$('#grupDefine>.jqTransformSelectWrapper span').html(firstChild);
	}	
	$('.jqTransformSelectWrapper').each(function(index) {
		$(this).css('zIndex', 100 - index);
	})
	//�����ȡ��
	$("#addWrap").show();
	$("#saveAndCancel").show();
}
$(function() {
    
    m_nameNickname = $("<font id='name_vie'  name='name_vie' class='name'></font><br/><br/><br/><p id='nickname_vie' name='nickname_vie' class='nickname'></p>");
    $('.mainInfor').append(m_nameNickname);
    
    m_groupAccount = $("<div class='fl account mart10' id='account'><select class='' name='phoneaccount' id='phoneaccount'></select></div><div class='fl account mart10' id='accountView'  style='display:none'><select class='' name='phoneaccountView' id='phoneaccountView'></select></div><div class='fl group mart10' id='grupDefine'></div>");
    $('#editAccountGroup').append(m_groupAccount);
    
    var initimgPath = "/static/imgs/avatar.png";
    $("#avatar img").attr("src",initimgPath);

	for (var k in infoType) {
		$('<option />').html(k).appendTo($('#infoTypeSelector'));
	}
	creatAccountSelect(IsMerge);	

})
$(document).ready(Initial)