var cityCours = {};
var localStorage_recentUse_total = 'ssdb_localTotal';
var localStorage_recentUse_city_start = 'ssdb_local';
var numberDesc = function(x,y){    
	if (x < y)      
	    return 1; 
	else            
	    return -1;
};
var recentUseLocal = {};
var recentUseLocalCount = 0;

var stageType = {'诉讼前':0,'诉讼中':1};//诉讼阶段
var targetType = {'房产':'S101','银行账户类':'S102','土地使用权':'S103','非上市公司股权':'S104','应收债权':'S105','采矿权':'S106','车辆':'S201','船舶':'S202','不易腐朽损坏货物':'S203','机器设备':'S204','商标专利':'S205','上市公司股票':'S301','非固定收益基金账户':'S302','易腐朽损坏货物':'S303'};
var targetTypeCount = 0;//混合标的总数
$(document).ready(function() {
	initCity();
	$('.modal-layout').click(function(event) {
		var _this = $(this);
		_this.addClass('hide');
		_this.find('.modal-wrapper').removeClass('animated')
		_this.find('.guarantee-modal-list').slideToggle('600');
	});
	// 选择诉讼阶段
	$('.online-letter-step').click(function(event) {
		var $layout = $('.modal-layout[data-target=online-letter-step]'); 
		var $item = $layout.find('.modal-radio-list li');
		$layout.removeClass('hide').find('.modal-wrapper').addClass('animated');
		$item.on('click',function(){
			var _this = $(this);
			var txt = _this.text();
			$layout.addClass('hide');
			$layout.find('.modal-wrapper').removeClass('animated');
			$('.online-letter-step').val(txt);
			$item.off('click');
		});
	});
	// 选择诉讼类型
	$('.online-letter-form').on('click','.online-letter-type',function(event) {
		var $layout = $('.modal-layout[data-target=online-letter-type]'); 
		var $typeTarget = $(this);
		var $item = $layout.find('.modal-radio-list li');
		$layout.removeClass('hide').find('.modal-wrapper').addClass('animated');
		$item.on('click',function(){
			var _this = $(this);
			var txt = _this.text();
			$layout.addClass('hide');
			$layout.find('.modal-wrapper').removeClass('animated');
			$typeTarget.val(txt);
			$item.off('click');
		})
	});
	// 添加标的类型
	$('.online-letter-add-type').click(function(event) {
		if(targetTypeCount > 1){
			showMsg('最多添加两个');
		}else{
			var str = '<div class="pad-r-35 ub ub-ac ub-pj fc-black list-item online-letter-type-wrapper">';
			str+='<label class="mar-r-25">选择标的类型</label>';
			str+='<input type="text" class="ub-f1 form-control online-letter-type fs-14" readonly="readonly" id=targetTypeName' + targetTypeCount + '>';
			str+='<span class="icon icon-list-dropdown"></span></div>';
			$('.online-letter-form').append(str);
			var $minus = $('.online-letter-minus-type');
			if($minus.hasClass('hide')){
				$minus.removeClass('hide');
			}
			targetTypeCount ++;
		}
	});
	// 删除标的类型
	$('.online-letter-minus-type').click(function(event) {
		var $wrapper = $('.online-letter-type-wrapper')
		if($wrapper.length>1){
			if ($wrapper.length == 2) {
				$('.online-letter-minus-type').addClass('hide');
			}
			$('.online-letter-type-wrapper').last().remove();
		}
		if(targetTypeCount > 0){
			targetTypeCount --;
		}else{
			targetTypeCount = 0;
		}
	});
	$('.online-letter-court').click(function(event) {
		$('.select-area-layout').removeClass('hide');
	});
	$('.area-back').click(function(event) {
		$('.select-area-layout').addClass('hide');
	});
	$('.select-court-btn').click(function(event) {
		var city = $('#currentCity').text();
		if(city.length > 0){
			$('.select-court-layout').removeClass('hide').addClass('pageIn');
			loadCityCourt(city);
		}else{
			showMsg('请选择城市');
		}
	});
	$('.area-recent-list li').click(function(event) {
		$('.select-court-layout').removeClass('hide').addClass('pageIn');
	});
	$('.court-back-btn,.court-back').click(function(event) {
		var $court = $('.select-court-layout');
		$court.css({
			'webkitTransform':'translate3d(0,0,0)',
			'transform':'translate3d(0,0,0)'
		});
		$court.removeClass('pageIn').addClass('pageOut');
		$court.on('animationend webkitAnimationEnd',function(){
			$court.removeClass('pageOut').addClass('hide').css({
				'webkitTransform':'translate3d(100%,0,0)',
				'transform':'translate3d(100%,0,0)'
			});
			$court.off('animationend webkitAnimationEnd');
		});

	});
	$('#online-letter-money').on('change',function(event){
		var value = $(this).val();
		var reg = new RegExp("^[0-9]*$");
		if(!/^[0-9]*$/.test(value)){  
			$(this).val('').focus();
			$('.online-letter-money-tips').removeClass('hide');
	    }  
	    else{
	    	$('.online-letter-money-tips').addClass('hide');
	    }
		
	});
	$('.online-letter-filter-btn').click(function(event) {
		searchCompany();
	});	
	
	showErrorMsg();
	
	initRecentUseLocal();
	
	$('#searchCity').click(function(event) {
		searchCity();
	});
});

function cityListLiOnclick(obj){
	var city = $(obj).text();
	if(city.length > 0){
		cityCours = {};
		$('#cityCourtList').html('');
		$('#currentCity').html(city);
		$('#currentCitySpan').html(city);
		loadCityCourt(city);
		$('.select-court-layout').removeClass('hide').addClass('pageIn');
		if(window.localStorage){
			if(recentUseLocal[city] == undefined){ 
				if(recentUseLocalCount < 6){
					recentUseLocal[city] = [city,new Date().getTime(),recentUseLocalCount];
					localStorage.setItem(localStorage_recentUse_city_start + recentUseLocalCount, city + ',' + recentUseLocal[city][1]);
					recentUseLocalCount ++;
					localStorage.setItem(localStorage_recentUse_total, recentUseLocalCount);
					$('.area-recent-list li').unbind();
					$('.area-recent-list').append('<li class="br bg-white pull-left">' + city + '</li>');
					$('.area-recent-list li').click(function(event) {
						recentUseLocalClick(this);
					});
				}else{
					var value,min = null;
					for(var key in recentUseLocal){
						value = recentUseLocal[key];
						if(min == null){
							min = value;
						}else{
							if(min[1] > value[1]){
								min = value;
							}
						}
					}
					if(min != null){
						delete recentUseLocal[min[0]];
						recentUseLocal[city] = [city,new Date().getTime(),min[2]];
						localStorage.setItem(localStorage_recentUse_city_start + recentUseLocalCount, city + ',' + recentUseLocal[city][1]);
					}
					refreshRecentUseLocal();
				}
			}else{
				updateRecentUseLocalStore(city);
			}
		}
	}
}

function initCity(){
	var obj = $('#citySelect');
	obj.html('');
	var citys = '';
	var value = null;
	var chars = '<ul class="fs-12 area-search-list">';
	for(var key in searchCityObj){
		value = searchCityObj[key];
		citys += '<p class="pad-tb-5 pad-l-30 fs-12 fc-xlgrey" id="area-select-' + key + '">' + key.toUpperCase(); + '</p>'
		citys += '<ul class="bg-white fs-14 area-city-list">';
		chars += '<li><a href="#area-select-' + key + '">' + key.toUpperCase(); + '</a></li>';
		for(var i=0;i<value.length;i++){
			citys += '<li class="pad-l-20 pad-r-50 br-b"><p>' + value[i] + '</p></li>';
		}
		citys += '</ul>';
	}
	chars += '</ul>';
	obj.append(citys);
	obj.append(chars);
	$('.area-city-list li').click(function(event) {
		cityListLiOnclick(this);
	});
}

//加载最近访问城市
function initRecentUseLocal(){
	if(window.localStorage){
		var total = localStorage.getItem(localStorage_recentUse_total);
		if(total == null){
			total = 0;
			localStorage.setItem(localStorage_recentUse_total,0);
		}else{
			total = Number(total);
			var value,array = null;
			for(var i=0;i<total;i++){
				value = localStorage.getItem(localStorage_recentUse_city_start + i);
				if(value != null){
					array = value.split(',');
					recentUseLocal[array[0]] = [array[0],Number(array[1]),i];
				}
			}
			refreshRecentUseLocal();
		}
		recentUseLocalCount = total;
	}
}

//加载法院
function loadCityCourt(city){
	var url = baseUrl + '/B/android';
	var parameters = {'actionCode':'B505','city':city};
	postData(url, JSON.stringify(parameters), loadCityCourtSuccess, postDataDefaultErrorCallback);
}

//加载法院成功回调
function loadCityCourtSuccess(data){
	if(data.success){
		var courts = data.courts;
		var html = '';
		var court = null;
		for(var i=0;i<courts.length;i++){
			court = courts[i];
			html += '<li class="pad-l-20 pad-r-30 br-b">' + court.name + '</li>';
			cityCours[court.name] = court.value;
		}
		$('#cityCourtList').html(html);
		$('.court-list li').click(function(event) {
			var txt = $(this).text();
			$('.online-letter-court input').val(txt);
			$('#courtId').val(cityCours[txt]);
			$('.select-court-layout,.select-area-layout').removeClass('pageIn').addClass('hide');
		});
	}else{
		showMsg(data.message);
	}
}

//最近访问城市单击事件
function recentUseLocalClick(obj){
	var city = $(obj).text();
	if(city.length > 0){
		cityCours = {};
		$('#cityCourtList').html('');
		$('#currentCity').html(city);
		$('#currentCitySpan').html(city);
		$('.select-court-layout').removeClass('hide').addClass('pageIn');
		updateRecentUseLocalStore(city);
		loadCityCourt(city);
	}
}

//刷新最近访问城市
function refreshRecentUseLocal(){
	$('.area-recent-list li').unbind();
	var obj = {};
	var times = [];
	var local = null;
	for(var key in recentUseLocal){
		local = recentUseLocal[key];
		obj[local[1]] = local[0];
		times.push(local[1]);
	}
	times.sort(numberDesc);
	var html = '';
	var value,array = null;
	for(var i=0;i<times.length;i++){
		html += '<li class="br bg-white pull-left">' + obj[times[i]] + '</li>';
	}
	if(html.length > 0){
		$('.area-recent-list').html(html);
		$('.area-recent-list li').click(function(event) {
			recentUseLocalClick(this);
		});
	}
}

function searchCity(){
	var obj = $('#citySelect');
	obj.html('');
	var text = $('#searchCityText').val();
	if(text.length > 0){
		var citys,city = null;
		var html = '<ul class="bg-white fs-14 area-city-list">';
		for(var key in searchCityObj){
			citys = searchCityObj[key];
			for(var i=0;i<citys.length;i++){
				city = citys[i];
				if(city.indexOf(text) != -1){
					html += '<li class="pad-l-20 pad-r-50 br-b"><p>' + city + '</p></li>';
				}
			}
		}
		html += '</ul>';
		obj.html(html);
		$('.area-city-list li').click(function(event) {
			cityListLiOnclick(this);
		});
	}else{
		initCity();
	}
}

function searchCompany(){
	var cityCourtName = $('#cityCourtName').val();
	if(cityCourtName.length < 1){
		showMsg('请选择法院');
		return false;
	}
	var stageName = $('#stageName').val();
	if(stageName.length < 1){
		showMsg('请选择诉讼阶段');
		return false;
	}
	var targetAmount = $('#online-letter-money').val();
	if(targetAmount.length < 1){
		showMsg('请输入担保金额');
		return false;
	}else{
		targetAmount = Number(targetAmount);
		if(isNaN(targetAmount)){
			showMsg('担保金额只能为大于0的整数');
			return false;
		}
		if(targetAmount < 1){
			showMsg('担保金额只能为大于0的整数');
			return false;
		}
	}
	var targetTypeName = $('#targetTypeName').val();
	if(targetTypeName.length < 1){
		showMsg('请选择标的类型');
		return false;
	}
	var targetTypeNames = [];
	if(targetTypeCount > 0){
		var tmp = null;
		for(var i=0;i<targetTypeCount;i++){
			tmp = $('#targetTypeName' + i).val();
			if(tmp.length < 1){
				showMsg('请选择混合标的类型' + (i+1));
				return false;
			}
			targetTypeNames.push(tmp);
		}
	}
	$('#stage').val(stageType[stageName]);
	$('#bdCode').val(targetType[targetTypeName]);
	if(targetTypeNames.length > 0){
		for(var i=0;i<targetTypeNames.length;i++){
			$('#bdCode' + (i+1)).val(targetType[targetTypeNames[i]]);
		}
	}
	$('.online-letter-form').submit();
}

function showErrorMsg(){
	var msg = $('#errorMsg').val();
	if(msg.length > 0){
		$('#errorMsg').val('');
		showMsg(msg);
	}
}

//更新最新使用城市
function updateRecentUseLocalStore(city){
	var array = recentUseLocal[city];
	array[1] = new Date().getTime();
	recentUseLocal[city] = array;
	localStorage.setItem(localStorage_recentUse_city_start + array[2],city + ',' + array[1]);
}
