//Alex add for wifi LBS
$(function(){
	var ctx = $("#ctx").val();
	var map ;
	jspagesize = 15;//搜索的WiFi一页显示的条数
	 $( "#btn-toggle" ).click(function( event ) {
		$( "#divLBS" ).dialog( "open" );
		try{
			map = new AMap.Map('mapview',{level:12});
			if($('#cacheSelected').val().length>2){
				loadselectwifi(1);
			}
		}
		catch(e){alert('加载已选wifi时出错')}
			map.plugin(['AMap.MarkerClusterer'], function(){
			var cl = new AMap.MarkerClusterer(map, initMarker($("#cacheSelected")[0]));
		});
	});
		
	$( "#divLBS" ).dialog({
		autoOpen: false,
		width: 900,
		modal: true,
		open: function (event, ui) {
			$(".ui-dialog-titlebar-close", $(this).parent()).hide();
        }
	});
		
	
	$('#btnmapSearch').click(function(e){
		try{
			//var sdata = $("#frmwifisearch").serializeArray(); 
			var wifiArr = new Object();
			wifiArr['address'] = $("#address").val();
			wifiArr['prov'] = $("#prov").val();
			wifiArr['city'] = $("#city").val();
			wifiArr['mapdistance'] = $("#mapdistance").val();
			$.ajax({
				url: ctx+"/advertiser/main/ad/target/ad-group/wifiList",
				type: "POST",
				// formate "name=codeplayer&age=18&uid=1&uid=2&uid=3"
				data: wifiArr,
				datatype: 'json',
				// sucess
				success: function( rdata, textStatus, jqXHR ){
					try{
						if(rdata.length>4){
							$('#cacheSearched').val(rdata);
							alert(rdata);
							//map=window.map;
							map.plugin(['AMap.MarkerClusterer'], function(){
								var cl = new AMap.MarkerClusterer(map, initMarker($("#cacheSearched")[0]));
							});
							loadsearchwifi(1);
							tabshow($("#mnusearchedwifi")[0],'mnusearchedwifi')									
						}
						else{$("#cacheSearched").val("");$("#divsearchedwifi").html("没有搜索到wifi");}
														
					}catch(e){alert(e);}
				},
				// onfaile
				 error: function(jqXHR, textStatus, errorMsg){
					// jqXHR  object of XMLHttpRequest
					// textStatus value: null、"timeout"、"error"、"abort"或"parsererror"
					// errorMsg value: "Not Found"、"Internal Server Error"
					 alert("请求失败：" + errorMsg);
				 }
			});
		 }catch(e){alert(e.error);}			 	
	});
	
	$("#wifi-btn-save").click(function(){
		savewifi();
		$("#divLBS").dialog("close");
		return false;
	});
	$("#wifi-btn-cancel,#wifi-headclose").click(function(){
		$("#divLBS").dialog("close");
		return false;
	});
});

/*get wifi from cachedata*/
function initMarker(obj){
	try{
		if(obj.value.length>4){
			allwifi=jQuery.parseJSON(obj.value)
			markers = [];
			for (var i = 0; length= allwifi.length,i<length ;i ++) {
				var markerPosition = new AMap.LngLat(allwifi[i]['lat'],allwifi[i]['lng']);
				var marker = new AMap.Marker({
					position: markerPosition,
					icon: "http://developer.amap.com/wp-content/uploads/2014/06/marker.png"
				});
				markers.push(marker);
			}
			return markers;
		}
	}catch(e){return false;}
}

function savewifi(){
	try{
		wifiids=''
		selectedwificount=0
		if($("#cacheSelected").val().length>2){
			allwifi=$.parseJSON($("#cacheSelected").val())
			for (var i = 0; length= allwifi.length,i<length ;i ++) {
				wifiids += allwifi[i]['id']+',';
				selectedwificount+=1;
			}
			wifiids=wifiids.substring(0,wifiids.length-1)
		}
		$("#selectedwifi").val(wifiids);
		$("#spanselectedhint").html("共选择了" + selectedwificount + " 个 wifi")
		$("#spanselectedhint").show();
	}catch(e){alert(e)}
}

function tabshow(e,id){
	var mnu=['mnusearchedwifi','mnuselectedwifi']
	try{
		for(i=0;i<mnu.length;i++){
			mnuid=mnu[i];divid="#div" + mnuid.substr(3)
			if(mnu[i]==id){
				$('#'+mnuid).addClass('current');
				$(divid)[0].style.display='block';
			}
			else{
				$('#'+mnuid).removeClass('current');
				$(divid)[0].style.display='none';
			}
		}
	}catch(e){alert(e)}
}

function wificlick(e){
	var nval="",v=$(e).attr("dataj"),oldval,strcache=$('#cacheSelected').val()
	if(strcache.length>2){
		oldval=$.parseJSON(strcache);
	}
	try{
		if(e.checked == true){//add string to cache
			if(strcache.length>2){
				if(strcache.indexOf(v)<1){
					strcache= strcache.substr(0,strcache.length-1) +',' + v + ']'
				}
			}
			else{
				strcache='['+ v +']';
			}
		}
		if(e.checked== false){
			if(strcache.indexOf(v)>1){
				strcache='['+strcache.substring(1,strcache.indexOf(v)) + strcache.substring(strcache.indexOf(v)+v.length,strcache.length-1)+ ']'
				strcache=strcache.replace(",,",",");
				strcache=strcache.replace("[,","[");
				strcache=strcache.replace(",]","]");			
			}
			else{strcache='[]'}
		}
		//alert(strcache);
		$('#cacheSelected').val(strcache);
		loadselectwifi($('#selectedPage').val())
		loadsearchwifi($('#searchedPage').val())
		//alert($('#cacheSelected').val())
	}catch(e){alert(e)}
}

function loadsearchwifi(p){
	var totalcount,pageno,swifi
	try{
		if($('#cacheSearched').val().length>2){
			swifi=$.parseJSON($('#cacheSearched').val())
			totalcount = swifi.length
			pagecount=Math.ceil(totalcount/jspagesize)
			$("#searchedPage").val(p)
			if(isNaN(p)|| typeof(p)!=='number' || parseInt(p)!==p || parseInt(p)>pagecount){pageno=1;}
			else{pageno=p;}
			$("#searchPage").val(p)
			wifihtm = '<div class="wifilist">';
			//select item in wifisections
			for(i=jspagesize*(pageno-1);i<jspagesize*(pageno-1)+jspagesize;i++){
				if(swifi[i]){
					wifihtm +="<div class=\"wifiitem\"><input type=\"checkbox\" name=\"swifi["+swifi[i]['id'] +"]\" id=\"swifi"+swifi[i]['id'] +"\" value=\""+swifi[i]['id'] +"\" onclick=\"wificlick(this)\"   dataj='" + JSON.stringify(swifi[i]) +"'";
					if($("#cacheSelected")[0].value.indexOf(JSON.stringify(swifi[i]))>-1){wifihtm +=' checked ';}
					wifihtm+= ">&nbsp;<lable class=\"wifilab\" for=\"swifi" +swifi[i]['id'] +"\">"  +swifi[i]['address'] + "</lable></div>";
				}
			}
			wifihtm += '</div>';
			resulthtm= wifihtm+genwifinav(pagecount,pageno,'loadsearchwifi');
			$("#divsearchedwifi").html(resulthtm);
		}	
		else{$("#divsearchedwifi").html('没有搜索到wifif信息')}
	}
	catch(e){$("#divsearchedwifi").html('加载wifi信息出错');}
}

function loadselectwifi(p){
	var totalcount,pageno,allwifi
	try{
		if($('#cacheSelected').val().length>2){
			var allwifi=$.parseJSON($('#cacheSelected').val())
			totalcount = allwifi.length
			pagecount=Math.ceil(totalcount/jspagesize)
			if(isNaN(p)|| typeof(p)!=='number' || parseInt(p)!==p || parseInt(p)>pagecount){pageno=1;}
			else{pageno=p;}
			$("#selectedPage").val(p)
			wifihtm = '<div class="wifilist">';
			//show select item in wifisections
			for(i=jspagesize*(pageno-1);i<jspagesize*(pageno-1)+jspagesize;i++){
				if((allwifi[i])){
				wifihtm +="<div class=\"\"><input type=\"checkbox\" name=\"swifi[]\" id=\"swifi"+allwifi[i]['id'] +"\" value=\""+allwifi[i]['id'] +"\" onclick=\"wificlick(this) \" dataj='" + JSON.stringify(allwifi[i]) + "'  checked>&nbsp;<lable class=\"\" for=\"swifi" +allwifi[i]['id'] +"\">"  +allwifi[i]['address'] + "</lable></div>"
				}
				else{break;}
			}
			wifihtm += '</div>';
			resulthtml= wifihtm+genwifinav(pagecount,pageno,'loadselectwifi');
		   $("#divselectedwifi").html(resulthtml);
	   }
	   else{$("#divselectedwifi").html("没有选择wifi");}
	}
	catch(e){$("#divselectedwifi").html("加载wifi时出错");}
}

function genwifinav(pcount,pno,fun){
	//pageinvbar
	wifinavhtm='<div class="pagination-wifi"><ul class="pagination-mini-wifi">';
	if(pcount<=7){pagebegin=1;pageend=pagecount;}
	else{
		if(pno<=4){pagebegin=1;pageend=pagecount;}
		else{
			if(pagecount-pno<4){pagebegin=pcount-6;pageend=pcount;}
			else{pagebegin=pno-3;pageend=pno+3}
			}
	}
	for(i=pagebegin;i<=pageend;i++){
		wifinavhtm +="<li ><a href=\"javascript:\" onclick=\""+ fun + "("+ i +")\""
		if(i==pno){wifinavhtm+=" class=\"disabled\""}
	
		wifinavhtm+= ">"+ i +"</li>"
	}
	wifinavhtm +='</ul></div>';
	return wifinavhtm;
}