var jcrop_api;
var Jcrop_init = false;

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'));
			}
		})
	}	
}

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;
}

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));


    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 createSelect = function( j, key, val) {
	var liElement = [];
	liElement[0] = $('<select />');
    
    $('<option />').html(key).attr('selected', 'selected').appendTo(liElement[0]);

	var name = infoTypeName[key][0];
	liElement[1] = $('<input />').attr({
		'type' : 'text',
		'rel' : infoTypeOther[j]
	}).val( val ? val : "");
   
	$('#optionContainer ul[rel="' + key + '"]').removeAttr('rel').addClass('ulSlt');
	var ulElement = $('<ul />').attr({
		'rel' : key,
		'wording' : key
	}).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;
}

function editInfo()
{
    
	$('#editorWrap').hide();
	$('#Sms').hide();
	
	$('#editAccountGroup').remove();
    
	var input = $("<ul rel='$trans('PBMainView_FuncBtn_BR_StaticBox_TC_Name')' wording='$trans('PBMainView_FuncBtn_BR_StaticBox_TC_Name')' class='ulSlt' style='margin-left: 22px; margin-top: 10px;'><li calss='li_1'> <input id='name' type='text'  name='name' class='name'/></li><li class='errorMsg'></li></ul>");
	$("#maininfor .mainInfor").empty().append(input);
    
	if (infoNameData.name != "")
	{
	   $("#name").val(infoNameData.name);
	}
	else
	{
	   $("#name").attr("placeholder",PBMainView_FuncBtn_BR_StaticBox_TC_Name);
	}
	
	
	//��ϸ��Ϣ
	$('#optionContainer').empty().append('<div class="claer"></div>');
    
    var index = 0
    for (var tname in infoType)
    {
        var value = '';
        for (var k in infoData){
            $.each(infoData[k], function(key,obj) {
                $.each(obj,function(mkey,mvalue){  
                    if (mkey == tname){
                        value = mvalue;

                    }
                })
            })
        }
        $('#optionContainer').append(createSelect( index, tname, value));
        $('#contact-form').removeClass('jqtransformdone').jqTransform(); 
        index ++;    
    }
   
	$('#contact-form').removeClass('jqtransformdone').jqTransform();
	

	$('#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');
		}
	})

	$("#saveAndCancel").show();
}


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() {
		
		$('#before').html(inner);
		editFlag = false;
		viewOrEdit = false;
		Initial();
		
	});
    
    $("#save").click(function() {
		document.getElementById("save").disabled=true
		var inputHaveContentLen = $(':input[rel = PhoneNumber1]').filter(function(){
			return $(this).val() != '';
		}).length;
		var inputErrorLen = $('li[class = errorMsg]').filter(function() {
			return $(this).css('display') != 'none';
		}).length;
        
        var hasfirstname = $("#name").val() != "";
        
		if (inputHaveContentLen == 0 || hasfirstname == false) {
			art.dialog({
				title : '',
				content : PBMainView_AddItem_MustFill_Error,
				lock : true,
				background : '#fff',
				opacity : 0.7,
				icon : 'error',
				ok : function() {
				}
			})
			
			return false;
		}
		if (inputErrorLen > 0)
			return;
		var data = {};
		data.Name_FirstName = $("#name").val();

		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.Account = "";
        data.Nickname = "";
        data.StorageLocation = m_StorageLocation;
		var postCmd = "/PB/Simedit";

		$.post(postCmd, data, 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")					
	});
    
    $('.mainInfor :input[type = text]').live('keyup',function(){
            var str = $(this).val();
            var cArr = str.match(/[^\x00-\xff]/ig);
            count = str.length;
            var input = $(this).parents('ul').find('li[class = errorMsg]');
            var restriction_length = 14;
            if (m_StorageLocation != '0')
            {
                restriction_length = restriction['ContactItemNameLen'];
                if (cArr)
                {
                    restriction_length = restriction_length/2;
                }
            }
            if(count > restriction_length){
                input.html(WORDS_TOO_LONG).show();
                recaculate(input);
                vaild = false;
                return ;
            }else{
                input.html('').hide().parents('ul').css('height','30px');
                vaild = true;
            }
           
        })
        
    var recaculate = function(input){
            var height = input.css('height');
            height = height.substring(0,height.length-2) * 1;
            input.parents('ul').css('height',35+height + 'px');
        }
    
    data = {}    
    $.post('/PB/loadfinish', data, function() {})
}



$(function() {
    
    m_name = $("<ul rel='$trans('PBMainView_FuncBtn_BR_StaticBox_TC_Name')' wording='$trans('PBMainView_FuncBtn_BR_StaticBox_TC_Name')' class='ulSlt' style='margin-left: 22px; margin-top: 10px;'><li calss='li_1'> <font id='name_vie' type='text'  name='name_vie' class='name'/></li><li class='errorMsg'></li></ul>");
    $('.mainInfor').append(m_name);
    
    
    if (sim_ecount == 1)
    {
        var initimgPath = "/static/imgs/contacts_default_sim.png";
    }
    else{
        if (m_StorageLocation == "1")
        {
            var initimgPath = "/static/imgs/contacts_default_sim1.png";
        }
        else
        {
            var initimgPath = "/static/imgs/contacts_default_sim2.png";
        }
    }
    $("#avatar img").attr("src",initimgPath);


})
$(document).ready(Initial)