define (['ckfinder','ckfinderStart', 'bootstrapJs'], function () {
    var user = {
        init: function () {
            //初始化dot
            user.event ();
        },
        event: function () {
        	
        	
//      	$("#liebiao_pic_btn").click(function(){
//			    BrowseServer ('liebiao_pic_pre', function(url){
//			    	console.log(url);
//			        //$("#sss").attr("src",url);
//			    });
//			});
        	
        	
        	var _id = getUrlParam('id');
			if(_id != null){
				$.ajax({
				    type: 'GET',
				    url: '/index/houseEdit',
				    data: {
				    	'id': _id
				    },
				    timeout: 30000,
				    dataType: 'json',
				    beforeSend: function() {},
				    success: function(data) {
				        if(typeof data === 'object') {
				            if (data.code == 200) {
				                //fn(data);
				            }else {
				                alert(data['msg']);
				            };
				        }else{
				            alert('数据错误');
				        };
				    },
				    error: function() {
				        alert('error');
				    },
				    complete: function(xhr, textStatus){
				        if(textStatus === 'timeout'){
				            alert('请求超时');
				        };
				    }
				});
			}else{
				//fn();
			};
			
        	var _doc = $(document),
    			_shangpuTypeObj = $('#shangpuType'),//商铺类型
    			_showCdObj = $('#showCd'),//显示给C端用户看
    			_exclusiveTypeObj = $('#exclusiveType'),//是否独家
    			_exclusiveDate1Obj = $('#exclusiveDate1'),//独家代理有效期开始时间
    			_exclusiveDate2Obj = $('#exclusiveDate2'),//独家代理有效期结束时间
    			_exclusiveTelObj = $('#exclusiveTel'),//独家方电话
        		_internalNameObj = $('#internalName'),//对内商铺名称
        		_foreignNameObj = $('#foreignName'),//对外商铺名称
        		_landlordPhoneObj = $('#landlordPhone'),//房东手机号
        		_zujinTypeObj = $('#zujinType'),//租金模式
        		_moonPriceObj = $('#moonPrice'),//月租均价
        		_wuyePriceObj = $('#wuyePrice'),//物业管理费
        		_jinchangPriceObj = $('#jinchangPrice'),//进场费
        		_roomShengyuNumObj = $('#roomShengyuNum'),//剩余铺数
        		_roomAllNumObj = $('#roomAllNum'),//总铺数
        		_roomArea1Obj = $('#roomArea1'),//商铺面积起始值
        		_roomArea2Obj = $('#roomArea2'),//商铺面积结束值
        		_businessAreaObj = $('#businessArea'),//商业面积
        		_yetaiObj = $('.yetai'),//业态
        		_provinceInternalObj = $('#province_internal'),//对内地址省
        		_cityInternalObj = $('#city_internal'),//对内地址市
        		_discInternalObj = $('#disc_internal'),//对内地址区
        		_addressInternalObj = $('#address_internal'),//对内地址详细地址
        		_longitudeObj = $('#longitude'),//经度
        		_latitudeObj = $('#latitude'),//纬度
        		_provinceExternalObj = $('#province_external'),//对外地址省
        		_cityExternalObj = $('#city_external'),//对外地址市
        		_discExternalObj = $('#disc_external'),//对外地址区
        		_addressExternalObj = $('#address_external'),//对外地址详细地址
        		_trafficObj = $('#traffic'),//交通
        		_hasMovedObj = $('#hasMoved'),//已入住
        		_yingyeTimeObj = $('#yingyeTime'),//营业时间
        		_kaipanTimeObj = $('#kaipanTime'),//开盘时间
        		_kaiyeTimeObj = $('#kaiyeTime'),//开业时间
        		_hasGasObj = $('#hasGas'),//是否有燃气
        		_weilouLinkObj = $('#weilouLink'),//微楼书
        		_dajiangtangObj = $('#dajiangtang'),//大讲堂
        		_yongjinRuleObj = $('#yongjinRule'),//佣金规则
        		_internalYoushiObj = $('#internalYoushi'),//对内项目优势
        		_foreignYoushiObj = $('#foreignYoushi'),//对外项目优势
        		_qianyueRuleObj = $('#qianyueRule'),//签约规则
        		_roomTagObj = $('.roomTag');//商铺标签
            $ ('#liebiao_pic_btn').click (function () {
				BrowseServer ('liebiao_pic_pre');
			});
            
			/************************************************百度地址定位相关*************************************************************/
            //字符串格式化,参数为对象的形式 by xishifeng 2017-07-14
			String.prototype.stringFormatObj = function(){
				var formatted = this;
				for(var i in arguments[0]){
					formatted = formatted.replace(new RegExp('\\{'+ i + '\\}','gi'), arguments[0][i]);
				};
				return formatted;
			};
			
			//从baidu-position.js移过来
			var ulHtml = $('#main_ul>ul'),
				loadItem = $("#loading_pic"),
				noMoreItem = $("#no_more"),
				cityLimitItem = $('#address_city_title'),
				_cityInputObj = $('#city_internal'),
				_inputObj = $('#search_input'),
				valueCurrent = '';
			//初始化,百度地图相关对象
			var LocalSearch = new BMap.LocalSearch(),
				myGeo = new BMap.Geocoder();
			
			$('#position_btn').click(function(){
				$.each(_cityInputObj.find('option'), function(i,item) {
					var _item = $(item);
					if(_item.val() == _cityInputObj.val()){
						cityLimitItem.html(_item.html());
						return false;//jq跳出当前循环
					};
				});
			});
			
			//搜索地址的回调
			LocalSearch.setSearchCompleteCallback(function(data) {
				if(LocalSearch.getStatus() == BMAP_STATUS_SUCCESS) {
					console.log(data);
					var _html = "";
					for (var i = 0; i < data.getCurrentNumPois(); i ++){
						_html += '<li data-city="{2}" data-lat="{3}" data-lng="{4}" data-dismiss="modal"><p>{0}</p><p>{1}</p></li>'.stringFormatObj({
							'0': data.getPoi(i)["title"],
							'1': data.getPoi(i)["address"],
							'2': data.getPoi(i)["city"],
							'3': data.getPoi(i)["point"]["lat"],
							'4': data.getPoi(i)["point"]["lng"]
						});
		            };
					ulHtml.html(_html);
					loadItem.hide();
					noMoreItem.show();
				}
			});

			_inputObj.on('input', function(e) {
				e.preventDefault();
				e.stopPropagation();
				valueCurrent = $(this).val();
				if(valueCurrent != '') {
					addressResetLoad();
					addressLoadMain(valueCurrent);
				} else {
					ulHtml.html('');
					loadItem.hide();
					noMoreItem.show();
					return false;
				}
			});
		
			//key搜索
			_doc.keydown(function(event) {
				if(event.keyCode == '13') {
					addressResetLoad();
					addressLoadMain(valueCurrent);
					return false;
				};
			});
		
			//输入框的取消图标点击事件
			$('.cancel-pic').click(function(e) {
				e.preventDefault();
				e.stopPropagation();
				_inputObj.val('').focus();
				addressResetLoad();
			});
		
			_doc.on('click', '#main_ul>ul>li', function(e) {
				e.preventDefault();
				e.stopPropagation();
				var _this = $(this);
				$('#longitude').val(Number(_this.data('lng')));
				$('#latitude').val(Number(_this.data('lat')));
			});
		
			function addressResetLoad() {
				ulHtml.html('');
				loadItem.hide();
				noMoreItem.show();
			};
		
			function addressLoadMain(keyword) {
				loadItem.show();
				noMoreItem.hide();
				LocalSearch.setLocation(cityLimitItem.html());
				LocalSearch.search(keyword);
			};
			/************************************************百度地址定位相关****结束*************************************************************/
			
			/************省市区选择处理**************/
			//自动获取省列表，并追加后面的市和区
			getCityDisc({
				'getType': 'province'
			},function(_data){
				var _htmlTemp = '';
				$.each(_data, function(i, item) {
                	_htmlTemp += '<option value="{0}">{1}</option>'.stringFormatObj({
                		'0': item['code'],
                		'1': item['name']
                	});
                });
            	_provinceInternalObj.html(_htmlTemp).val('310000');
            	getCityDisc({
            		'dom': _provinceInternalObj,
            		'getType': 'city'
            	}, function(){
					getCityDisc({
						'dom': _provinceInternalObj.next(),
						'getType': 'disc'
					});
				});
			});
			
			//获取省市区输入时的真实值和所见值的对应
			function getText(_domObj, fn){
				var _arrTemp = _domObj.find('option');
    			if(_arrTemp.length > 0){
    				$.each(_arrTemp, function(i, item) {
        				var _item = $(item);
						if(_item.val() == _domObj.val()){
							fn(_item.html());
							return false;//jq跳出当前循环
						};
        			});
    			}else{
    				fn('');
    			};
    		};
    		
    		//对内地址省市区映射到对外地址
    		function mapInput(){
    			getText(_provinceInternalObj, function(_text){
        			_provinceExternalObj.val(_text);
        		});
        		getText(_cityInternalObj, function(_text){
        			_cityExternalObj.val(_text);
        		});
        		getText(_discInternalObj, function(_text){
        			_discExternalObj.val(_text);
        		});
        		return false;
    		};
			
			//获取省市区事件封装
			function getCityDisc(_obj, fn){
				var _data = {};
				if(_obj['getType'] != 'province'){
					if(!!_obj['dom'].val()){
						_data['parent_code'] = Number(_obj['dom'].val())
					}else{
						//处理没有市选项，区选项的内容
						_obj['dom'].next().html('');
						fn && fn();
						return false;
					};
				};
				$.ajax({
				    type: 'GET',
				    url: '/index/regions.html',
				    timeout: 30000,
				    data: _data,
				    dataType: 'json',
				    beforeSend: function() {},
				    success: function(data) {
				        if(typeof data === 'object') {
				            if (data.code == 200) {
				            	//如果是获取的省列表，直接直接返回数组
				            	if(_obj['getType'] == 'province'){
				            		fn(data['data']);
									return false;
				            	};
				                var _htmlTemp = '';
				                $.each(data['data'], function(i, item) {
				                	_htmlTemp += '<option value="{0}">{1}</option>'.stringFormatObj({
				                		'0': item['code'],
				                		'1': item['name']
				                	});
				                });
				                _obj['dom'].next().html(_htmlTemp);
				                _obj['getType'] == 'disc' && mapInput();//对内地址省市区映射到对外地址
				                fn && fn();
				            }else {
				                alert(data['msg']);
				            };
				        }else{
				            alert('数据错误');
				        };
				    },
				    error: function() {
				        alert('error');
				    },
				    complete: function(xhr, textStatus){
				        if(textStatus === 'timeout'){
				            alert('请求超时');
				        };
				    }
				});
			};
			
			//省选择框事件添加
			_provinceInternalObj.change(function(){
				var _this = $(this);
				getCityDisc({
					'dom': _this,
					'getType': 'city'
				}, function(){
					getCityDisc({
						'dom': _this.next(),
						'getType': 'disc'
					});
				});
			});
			
			//市选择框事件添加
			_cityInternalObj.change(function(){
				var _this = $(this);
				getCityDisc({
					'dom': _this,
					'getType': 'disc'
				});
			});
			_discInternalObj.change(function(){
				mapInput();//对内地址省市区映射到对外地址
			});
			
			/***************************************************省市区选择处理结束************************************************************/
			
			$('.input-add-tel').click(function(){
				var _this = $(this);
				if(_this.parent().find('.phone_jia').length < 5){
					_this.before('<div class="form-group phone-list-container"><input type="tel" class="form-control phone_jia" placeholder="请输入"><ul></ul><img src="/resource/image/search_gb.png" class="input-cancel-pic" /></div>');
				}else{
					alert('最多添加5个');
				};
			});
			
			_doc.on('click', '.input-cancel-pic', function(){
				$(this).parent().remove();
			});
			
			_doc.on('click', '.phone-list-container>ul>li', function(){
				var _this = $(this);
				_this.parent().prev().val(_this.html()).attr('data-id',_this.attr('data-id'));
				_this.parent().html('');
			});
			
			var _ajaxObjTel = null;
			_doc.on('input', '.phone_jia' ,function(){
				var _this = $(this);
				var _thisVal = $.trim(_this.val());
				console.log(_thisVal);
				if(_thisVal != ''){
					_ajaxObjTel && _ajaxObjTel.abort();
					_ajaxObjTel = $.ajax({
					    type: 'GET',
					    url: '/index/getBroker_new',
					    data: {
					    	'phone': $.trim(_this.val())
					    },
					    timeout: 30000,
					    dataType: 'json',
					    beforeSend: function() {},
					    success: function(data) {
					        if(typeof data === 'object') {
					            if (data.code == 200) {
					            	if(data['data'].length > 0){
					            		var _htmlTemp = '';
					            		$.each(data['data'], function(i, item) {
						                	_htmlTemp += '<li data-id="{3}">{2}{0}-{1}<li>'.stringFormatObj({
						                		'0': item['name'],
						                		'1': item['phone'],
						                		'2': _this.parent().nextAll('.input-add-tel').data('hideid')?'':(item['id']+'-'),
						                		'3': item['id']
						                	});
						                });
						                _this.next().html(_htmlTemp);
					            	}else{
					            		_this.next().html('');
					            	};
					            }else {
					                alert(data['msg']);
					            };
					        }else{
					            alert('数据错误');
					        };
					    },
					    error: function() {
					        //alert('error');
					    },
					    complete: function(xhr, textStatus){
					        if(textStatus === 'timeout'){
					            alert('请求超时');
					        };
					    }
					});
				};
			});
			
			/***************************************************电话号码输入相关交互处理***************************************************/
			
			/*********************************************是否独家************************************************************/
			_exclusiveTypeObj.change(function(){
				if($(this).val() == '1'){
					$('#li_dujia_area').slideDown().css('display','block');
				}else{
					$('#li_dujia_area').slideUp();
				}
			});
			
			_shangpuTypeObj.change(function(){
				if($(this).val() == '1'){
					_jinchangPriceObj.parent().prev().html('转让费');
					$('.shangchang-show-part').hide();
				}else{
					_jinchangPriceObj.parent().prev().html('进场费');
					$('.shangchang-show-part').show();
				};
			});
			
			_showCdObj.change(function(){
				if($(this).val() == '1'){
					//不显示给C端
					$('.show-c-part').hide();
				}else{
					//显示给C端
					$('.show-c-part').show();
				};
			});
			
			$('#saveBtn').click(function(e){
				e.preventDefault();
				e.stopPropagation();
				
				//多个input输入框验证
				var _isBreakFlag = false;
				$.each([
					_showCdObj,//显示给C端用户看
    				_exclusiveTypeObj,//是否独家
				], function(i,item) {
					if($.trim(item.val()) == ''){
						alert(item.data('alert'));
						_isBreakFlag = true;
						return false;
					};
				});
				if(_isBreakFlag){
					return false;
				};
				
				//独家里的选项验证
				if(_exclusiveTypeObj.val() == '1'){
					if(_exclusiveDate1Obj.val() == '' || _exclusiveDate2Obj.val() == ''){
						alert('请填写独家代理有效期！');
						return false;
					};
					if(_exclusiveTelObj.attr('data-id') == undefined || _exclusiveTelObj.attr('data-id') == null){
						alert('请填写独家方!');
						return false;
					};
				};
				
				//案场联系人
				var _acrPhoneArr = [];
				$.each($('#li_acr_phone input'), function(i,item) {
					var _id = item.getAttribute('data-id');
					if(_id !== undefined && _id !== null){
						_acrPhoneArr.push(item.value);
					};
				});
				console.log(_acrPhoneArr);
				if(_acrPhoneArr.length<1){
					alert('案场人电话至少需要填写一个!');
					return false;
				};
				
				//盘方
				var _pfPhoneArr = [];
				$.each($('#li_pf_phone input'), function(i,item) {
					var _id = item.getAttribute('data-id');
					if(_id !== undefined && _id !== null){
						_pfPhoneArr.push(_id);
					};
				});
				if(_pfPhoneArr.length<1){
					alert('盘方至少需要填写一个!');
					return false;
				};
				
				//案场权限人
				var _acqxPhoneArr = [];
				$.each($('#li_acqx_phone input'), function(i,item) {
					var _id = item.getAttribute('data-id');
					if(_id !== undefined && _id !== null){
						_acqxPhoneArr.push(_id);
					};
				});
				if(_acqxPhoneArr.length<1){
					alert('盘方至少需要填写一个!');
					return false;
				};
				
				$.each([
					_internalNameObj,//对内商铺名称
					_foreignNameObj,//对外商铺名称
					_landlordPhoneObj,//房东手机号
					_moonPriceObj,//月租均价
					_wuyePriceObj,//物业管理费
					_jinchangPriceObj,//进场费
					_roomShengyuNumObj,//剩余铺数
					_roomAllNumObj,//总铺数
					_roomArea1Obj,//商铺面积起始值
					_roomArea2Obj,//商铺面积结束值
					_businessAreaObj,//商业面积
					_addressInternalObj,//对内地址详细地址
					_longitudeObj,//经度
					_latitudeObj,//纬度
					_addressExternalObj,//对外地址详细地址
					_trafficObj,//交通
					_hasMovedObj,//已入住
					_yingyeTimeObj,//营业时间
					_kaipanTimeObj,//开盘时间
					_kaiyeTimeObj,//开业时间
					_yongjinRuleObj,//佣金规则
					_internalYoushiObj,//对内项目优势
					_foreignYoushiObj,//对外项目优势
					_qianyueRuleObj,//签约规则
					_weilouLinkObj//微楼书
				], function(i,item) {
					if($.trim(item.val()) == ''){
						alert(item.data('alert'));
						_isBreakFlag = true;
						return false;
					};
				});
				if(_isBreakFlag){
					return false;
				};
				
				//大讲堂验证
				var _dajiangtangVal = _dajiangtangObj.find('iframe').contents().find('body').html();
				if(_dajiangtangVal == '' || _dajiangtangVal == '<p><br></p>' || _dajiangtangVal == '<p><br /></p>' || _dajiangtangVal == '<p></p>'){
					alert('请填写大讲堂内容！');
					return false;
				};
				
				//业态验证
				var _yetaiArr = [];
				$.each($('.yetai'), function(i, item) {
					item.checked && _yetaiArr.push(item.value);
				});
				if(_yetaiArr.length<1){
					alert('业态至少需要填写一个!');
					return false;
				};
				
				//商铺标签验证
				var _roomTagArr = [];
				$.each($('.roomTag'), function(i, item) {
					item.checked && _roomTagArr.push(item.value);
				});
				if(_roomTagArr.length<1){
					alert('商铺标签至少需要填写一个!');
					return false;
				};
				
				var _data = {
					'shop_type': _shangpuTypeObj.val(),
					'is_show': _showCdObj.val(),
					'is_exclusive_type': _exclusiveTypeObj.val(),
					//'phone': _acrPhoneArr,
					'agent_dish': _pfPhoneArr.join(','),
					'agent_data': _acqxPhoneArr.join(','),
					'internal_title': $.trim(_internalNameObj.val()),
					'external_title': $.trim(_foreignNameObj.val()),
					'landlord_phone': $.trim(_landlordPhoneObj.val()),
					'rent_type': _zujinTypeObj.val(),
					'rent_price': _moonPriceObj.val(),
					'management_fee': _wuyePriceObj.val(),
					'slotting_fee': _jinchangPriceObj.val(),
					'residue_num': _roomShengyuNumObj.val(),
					'total': _roomAllNumObj.val(),
					'shop_area_start': _roomArea1Obj.val(),
					'shop_area_end': _roomArea2Obj.val(),
					'market_area': _businessAreaObj.val(),
					'province_code': _provinceInternalObj.val(),
					'city_code': _cityInternalObj.val(),
					'disc_code': _discInternalObj.val(),
					'external_address': $.trim(_addressInternalObj.val()),
					'longitude': _longitudeObj.val(),
					'latitude': _latitudeObj.val(),
					'external_address': $.trim(_addressExternalObj.val()),
					'traffic': $.trim(_trafficObj.val()),
					'enter_num': $.trim(_hasMovedObj.val()),
					'do_business_date': $.trim(_yingyeTimeObj.val()),
					'opening_date': _kaipanTimeObj.val(),
					'start_business_date': _kaiyeTimeObj.val(),
					'is_has_gas': _hasGasObj.val(),
					'fee_rule': $.trim(_yongjinRuleObj.val()),
					'internal_item_advantage': $.trim(_internalYoushiObj.val()),
					'external_item_advantage': $.trim(_foreignYoushiObj.val()),
					'singn_rule': $.trim(_qianyueRuleObj.val()),
					'tiny_brochure_url': $.trim(_weilouLinkObj.val()),
					'auditorium': _dajiangtangVal,
					'industry_type': '餐饮美食,百货零售',
					'shop_sign': '临近地铁,临街旺铺,无进场费'
				};
				if(_exclusiveTypeObj.val() == '1'){
					_data['agent_start_time'] = _exclusiveDate1Obj.val();
					_data['agent_end_time'] = _exclusiveDate2Obj.val();
					_data['exclusive_ids'] = _exclusiveTelObj.attr('data-id');
				};
				$.each(_acrPhoneArr, function(i, item) {
					_data['phone['+i+']'] = item;
				});
				$.ajax({
				    type: 'POST',
				    url: '/index/houseEdit',
				    data: _data,
				    timeout: 30000,
				    traditional: true,
				    dataType: 'json',
				    beforeSend: function() {},
				    success: function(data) {
				        if(typeof data === 'object') {
				            if (data.code == 200) {
				                
				            }else {
				                alert(data['msg']);
				            };
				        }else{
				            alert('数据错误');
				        };
				    },
				    error: function() {
				        alert('error');
				    },
				    complete: function(xhr, textStatus){
				        if(textStatus === 'timeout'){
				            alert('请求超时');
				        };
				    }
				});
			});
        }
    };
    return user;
});