//Author: ljq_sc
//create-time:09/04/26
//last-modify-time:
function isNull(val)
{
	return(val==null || typeof(val)=="undefined");
}

function isBlank(val){
	if(isNull(val))
		return true;
	val += "";
	for(var i=0;i<val.length;i++) {
		switch(val.charAt(i))
		{
			case " ":
			case "\t":
			case "\n":
			case "\r":
				break;
			default:
				return false;
		}
	}
	return true;
}
function isValidEmail(email)
{
	//var pattern = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
	var pattern = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
	var flag = pattern.test(email);
	if(!flag){
		return false; 
	}else{
		return true;
	}
}
function isValidMobile(mobile)
{
	if (isBlank(mobile))
		return false;
	var reg = /^(((13[0-9]{1})|159|(15[0-9]{1}))+\d{8})$/;
	var reg0 = /^13\d{5,9}$/;
    var reg1 = /^153\d{4,8}$/;
    var reg2 = /^159\d{4,8}$/;
    var reg3 = /^0\d{10,11}$/;
    var my = false;
    if (reg0.test(mobile))my=true;
    if (reg1.test(mobile))my=true;
    if (reg2.test(mobile))my=true;
    if (reg3.test(mobile))my=true;

	return my;
}
function isValidPhone(phone)
{
	if (isBlank(phone))
		return false;
	var pattern =  /^(([0\+]\d{2,3}-)?(0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/; 
	var flag =  pattern.test(phone); 
	if(!flag){
	    return false;
	}else{
	    return true;
    }
}	
//form表单验证
//验证是否是手机号
function checkMobile( s ){
	var regu =/^[1][3|5][0-9]{9}$/;
	var re = new RegExp(regu);
	if (re.test(s)) {
		return true;
	}else{
		return false;
	}
} 
//验证是否是整数
function isNumber( s ){
	var regu = "^[0-9]+$";
	var re = new RegExp(regu);
	if (s.search(re) != -1) {
		return true;
	} else {
		return false;
	}
} 
//check the phone number
function checkPhone( strPhone ) {
	//var phoneRegWithArea = /^[0][1-9]{2,3}-[0-9]{5,10}$/;
	var phoneRegWithArea =  /^(([0\+]\d{2,3}-)?(0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/
	//var phoneRegNoArea = /^[1-9]{1}[0-9]{5,8}$/;
	var prompt = "您输入的电话号码不正确!"
	if( phoneRegWithArea.test(strPhone) ){
			return true;
	}else{
			//alert( prompt );
			return false;
	}
	/*
	if( strPhone.length > 9 ) {
		if( phoneRegWithArea.test(strPhone) ){
			return true;
		}else{
			//alert( prompt );
			return false;
		}
	}else{
		if( phoneRegNoArea.test( strPhone ) ){
			return true;
		}else{
			//alert( prompt );
			return false;
		}

	}
	*/
} 

function checkEmail(strEmail) {
	var emailReg = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;
	if( emailReg.test(strEmail) ){
		return true;
	}else{
		return false;
	}
} 
function iszipcode(postid){
	var tel = /^[0-9]{6}$/; 
	var flag = tel.test(postid);
	if(flag){
		return true;
	}else{
		return false;
	}
}
function isInteger(val){
	if(isNull(val)){return false;}
	val += "";
	if(val.length == 0) return false;
	var string="1234567890";
	for(var i=0;i<val.length;i++){
		if (string.indexOf(val.charAt(i))==-1)
			return false;
	}
	return true;
}


var URL = '';
var APP	 =	 '/index';
var site_host = 'http://'+document.domain+'/';
var areas=['北京','上海','广州','沈阳','大连','无锡','温州','深圳','杭州','成都','重庆','厦门','南京'];
var classTypes=['我的地标','我的约会','我的exchange'];
var add = true;

/**
 * 删除分组
 *
 */
function closeqc(){
	$('#QC').remove();	
}
function doAjax(rel,id){

	$('#QC').html("<b><font size=2 color=green>正在提交...</font></b>");
	var delId="#map_"+id;
	var alt = $("#"+id).attr('alt');
	$.post(rel,{id:id},function(txt){
	   if(alt =='join'){
		  if(txt=='1'){
			$(delId).fadeOut('slow');
			//$(delId).prev('span').show();
			$(delId).parents('span').html('<font color=red>参赛中..</font>');
			$('#QC').html("<b><font size=2 color=blue>操作成功!</font></b>");
			setTimeout(function(){$('#QC').remove();},500);
			}else if(txt == '-1'){
				$('#QC').html("<b><font size=2 color=blue>操作失败!</font></b>");
				setTimeout(function(){$('#QC').remove();},500);
			}else if(txt == '-2'){
				$('#QC').html("<b><font size=2 color=blue>你好没有填写参赛个人信息!</font></b><span style='margin-top:20px;'><input class='fb-yes' type='button' onclick=\"window.location='"+APP+"/Map/joins/id/"+id+"'\" value='填写参赛个人信息'/>           <input class='fb-no' type='button' onclick='closeqc();' value='取消'/></span>");
				//setTimeout(function(){$('#QC').remove();},500);		
			}
		}else if(alt =='del' || alt =='map'){
			 var fragment = rel.split('/');
			 var frag = fragment[fragment.length-1];
			 var num = 	parseInt($('#'+frag+'num').text());
	   		 if(parseInt(txt)=='1'){
				$('#'+frag+'num').text(num-1);
				$(delId).fadeOut('slow');
				$('#QC').html("<b><font size=2 color=blue>操作成功!</font></b>");
				setTimeout(function(){$('#QC').remove();},500);
				 if($('input[@name=module]').val() == 'my'){
					 setTimeout(function(){ 
						$.facebox.close(); 
						window.location=APP+"/Map/my";
					},1500);
				 }
			 }else if(parseInt(txt)=='-2'){
				$('#QC').html("<b><font size=2 color=blue>不能删除别人的地标!</font></b>");
				setTimeout(function(){$('#QC').remove();},500);
			 }else{
				$('#QC').html("<b><font size=2 color=blue>操作失败!</font></b>");
				setTimeout(function(){$('#QC').remove();},500);
			 }
			 
		}
	});
}	
//增加
function ajaxInsert(){
	var errorstr='';
	var title = $("#Maptitle").val();//标题
	var area = $("select[@name=area] option[@selected]").val();//地区
	var classType = $("select[@name=classType] option[@selected]").val();//类别	
	//var status = $('.public_set[checked=true]').val();
	var deadline='';
	if( parseInt(classType)>0){
		deadline = $("#deadline").val();
	}
	var location = $("#location").val();//location
	var describe = $("#describes").val();//描述
	var cover = $("#cover").val();//
	var tags = $("#tags").val();//标签
	var status = $('input[@name=openset][@checked]').val();//隐私
    //map 活动 cate标记
	var cate ='';
	if($('input[@name=cate]').length>0){
		cate  =  $('input[@name=cate]').val();	
	}
	//if(area==""){
		//errorstr +='*  地区不能为空\n';
	//}
	if(title==''){
		errorstr +='*  标题不能为空\n';
	}
	if( parseInt(classType)>0  && deadline==''){
		errorstr +='*  时间不能为空\n';
	}
	if(location==''){
		errorstr +='*  详细地址不能为空\n';
	}
	if(describe==''){
		errorstr +='*  描述不能为空\n';
	}
	if(cover==''){
		errorstr +='*  图片不能为空，请选择上传\n';
	}
	if(tags==''){
		errorstr +='*  标签不能为空\n\r';
	}
	if(errorstr){
		errorstr =	'每项均需填写\n\r'+errorstr;
		alert(errorstr);
		return;
	}
	$.post(APP+"/Map/insert",{title:title,area:area,deadline:deadline,classType:classType,status:status,location:location,describe:describe,cover:cover,tags:tags,cate:cate},function(txt){
		if(txt!=""){
			var date =  new  Date();		
			var ids=txt;
            $("#newMapInsertId").val(ids);
			$("#newMapInsertIdx").val(ids);
			$("#areaId").val(area);
            $("#fShare").attr("rel",APP+"/Share/map/id/"+ids);
			$("#shareOut").attr("rel",APP+"/Map/shareMap/id/"+ids);
			$("#titlet").html(title);
			$("#cover_url").html('<img src="/Public/Thumb/?w=295&h=179&t=c&url='+cover+'" />');
			$("#describe").html(describe);
			if(status==0){
				$("#status").html("公   开");
			}else{
				$("#status").html("不公开");
			}
			$("#dates").html( (date.getMonth() + 1).toString()+"月"+(date.getDate()).toString()+"日");
			/*由cate来标记 icon选择页面的引入方式*/
			if(cate == '1'){
				$("#map_canvas").html($('#confirm').html());
			}else{
				$("#facebox .content").html($('#confirm').html());	
				//$("#facebox .content").html($('#confirm').html());
			}
		}else{
			alert("添加失败！");
		}
	});
}
//更新
function ajaxUpdate(type){
	var errorstr='';
	if(type == 'marker'){
		add = false;
	}
	var mapId = $('input[@name=mapId]').val();
	var title = $("#Maptitle").val();//标题	 
	var area = $("select[@name=area] option[@selected]").val();//地区
	var classType = $("select[@name=classType] option[@selected]").val();//类别
	var location = $("#location").val();//location
	var deadline='';
	if( parseInt(classType)>0){
		deadline = $("#deadline").val();
	}
	var describe = $("#describes").val();//描述
	var cover = $("#cover").val();//
	var icon = 	$("input[@name=iconurl]").val();
	var tags = $("#tags").val();//标签
	var status = $('input[@name=openset][@checked]').val();//隐私
	if(title==''){
		errorstr +='*  标题不能为空\n';
	}
	if( parseInt(classType)>0  && deadline==''){
		errorstr +='*  时间不能为空\n';
	}
	if(location==''){
		errorstr +='*  详细地址不能为空\n';
	}
	if(describe==''){
		errorstr +='*  描述不能为空\n';
	}
	if(cover==''){
		errorstr +='*  图片不能为空，请选择上传\n';
	}
	if(tags==''){
		errorstr +='*  标签不能为空\n\r';
	}
	if(errorstr){
		errorstr =	'每项均需填写\n\r'+errorstr;
		alert(errorstr);
		return;
	}
	$.post(APP+"/Map/Update",{mapId:mapId,title:title,area:area,deadline:deadline,classType:classType,status:status,location:location,describe:describe,cover:cover,tags:tags,icon:icon},function(txt){
		if(txt=="1"){
			date =  new  Date();
			$("#m_deadline").hide();
			if(classType ==1){
				title = classTypes[parseInt(classType)]+':'+title ;
				$("#m_deadline").html('<td><font color=red>约会时间：'+deadline+'</font></td>');
				$("#m_deadline").show();
			}else if(classType ==2){
				$("#m_deadline").html('<td><font color=red>截止时间：'+deadline+'</font></td>');
				$("#m_deadline").show();
			}
            $("#m_title").html(title);
			$("#m_cover").attr('src','/Public/Thumb/?w=300&h=200&t=c&url='+cover);
            $("#m_describe").html(describe);
			$("#m_area").html('发布地区：'+areas[area]+' - '+location);
			/*继续修改坐标信息*/
			if(type=='marker' || type=='new')
			{
				$("#newMapInsertId").val(mapId);
				$("#areaId").val(area);
				$("#fShare").attr("rel",APP+"/Share/map/id/"+mapId);
				$("#titlet").html(title);
				$("#cover_url").html('<img src="/Public/Thumb/?w=295&h=179&t=c&url='+cover+'" />');
				if(icon !=''){
					$(".icons_show").find('img').eq(0).attr('src',icon);	
				}
				$("#describe").html(describe);
				if(status==0){
					$("#status").html("公   开");
				}else{
					$("#status").html("不公开");
				}
				$("#dates").html( (date.getMonth() + 1).toString()+"月"+(date.getDate()).toString()+"日");
				var lat =  $('input[@name=lat]').val();
				var lng =  $('input[@name=lng]').val();
				if(type == 'marker')
				{
					var center =[lat,lng] ;
					$("#clickbutton").html('<input type="button" name="button3" id="button3" value="确　　定" class="bnt_yellow_mp" style="margin-left:5px;"  onclick="toeditmarker('+mapId+','+lat+','+lng+');"/>');
				}else if(type == 'new'){
					$("#clickbutton").html('<input type="button" name="button3" id="button3" value="确　　定" class="bnt_yellow_mp" style="margin-left:5px;"  onclick="toeditmarker('+mapId+',\'\',\'\');"/>');					
				}
				$("#facebox .content").html($('#confirm').html());
			}else{
			   $("#facebox .edit").html('更新成功');
			   setTimeout(function(){
					$.facebox.close(); 
				},1500);
			}
		}else{
			//alert("添加失败！");
			$("#facebox .edit").html('更新失败');
			setTimeout(function(){
				$.facebox.close(); 
			},1500);
		}
		
	});
}
//选择地图上显示的图片
function showMapIcon(){
	$(".icons_show").mouseover(function(){
				$('.icos_map_c').show();	
	});
}
//得到地图上显示的图片
function getMapIcon(){
	$(".icos_map_c img").each(function(){
		$(this).click(function(){
			$(".icons_show img").attr("src",this.src);
			$('.icos_map_c').hide();
		});
	});
}
/** 站外分享-start*/
function outShare(url){
	var mapUrl = url;
	//更新当前站外分享地址
	$("#mapUrl").val(url);
	jQuery('#dialog3').jqm().jqmShow();
	//reGetHeight();
	return false;
}

	function reGetHeight(){
		var jqm_c_h=jQuery('#jqm_c1').height();
		jQuery('#jqm_l_img img,#jqm_r_img img').height(jqm_c_h);
		jQuery('#blog_unin_dialog').pngFix();//修复png ie6透明度,点击那个修复那个层
	}
function share(){
	var mapUrl = $("#mapUrl").val();
	var emailTitle = $("#emailTitle").val();
	var emails = $("#emails").val();	
	var content = $("#emailContent").val();
	var username = $("#shareuname").val();
	
	if(!emails){
		alert('请输入email!');
		return false;
	}
	$.post(APP+"/Map/share",{emailTitle:emailTitle,content:content,mapUrl:mapUrl,username:username,emails:emails},function(txt){		
		if(txt == 1){
			alert('分享成功！');
			setTimeout(function(){$.facebox.close();},1500);
		}else{
			alert('分享失败！');
			setTimeout(function(){$.facebox.close();},1500);
		}
	});
}
function deleteMarker()
{

	var mapId = $('#deletebutton').attr('alt');
	$.post(APP+"/Map/delete",{id:mapId},function(txt){
		if(txt == '0'){
			$('#facebox  .delete .faceboxcontent').html("<p>删除失败</p>");
		}else if(txt == '-2'){
			$('#facebox  .delete .faceboxcontent').html("<p>删除失败</p>");
		}else if(txt == '1'){
			$('#facebox  .delete .faceboxcontent').html("<p>删除成功</p>");
		}
	});
	setTimeout(function(){ 
		$.facebox.close(); 
		window.location=APP+"/Map/my";
	},1500);
	
}
function doFaveAll(id){
	var keyValue = id;
	$('#facebox .content .faceboxcontent').html("<b><font size=2 color=green>正在提交...</font></b>");
	$.post(APP+"/Map/doFave",{id:keyValue},function(txt){
		if(parseInt(txt) == txt){
			if(txt=='1'){
				//alert("收藏成功");
				$('#facebox .content .faceboxcontent').html("<p>收藏成功</p>");
				setTimeout(function(){ 
					$.facebox.close(); 
				},1500);
			}else if(txt=='-1'){
				//alert("您已经收藏过这个Idea了！");
				$('#facebox .content .faceboxcontent').html("<p>您已经收藏过这个Idea了！</p><p><input class='fb-yes' type='button' onclick='$.facebox.close();' value='确定'/></p>");
			}else if(txt=='-2'){
				//alert("收藏失败");
				$('#facebox .content .faceboxcontent').html("<p>收藏失败</p><p><input class='fb-yes' type='button' onclick='$.facebox.close();' value='确定'/></p>");
			}
		}else{
			//alert(txt);
			$('#facebox .content .faceboxcontent').html(txt+"<p><input class='fb-yes' type='button' onclick='$.facebox.close();' value='确定'/></p>");
		}
	});
}

//Map的四个页面的Ajax调用
function changeTab(type){
	theType = type;	
//	if(type == 'MyMap'){
//		$("#newMap").attr('src','/SNS/Tpl/default2/Public/img_Map/db_menu_1_a.gif'); 
//		$("#hotMap").attr('src','/SNS/Tpl/default2/Public/img_Map/db_menu_2_a.gif');
//		$("#MyMap").attr('src',"/SNS/Tpl/default2/Public/img_Map/db_menu_3_b.gif");
//		getMyMap();
//	}else
	if(type == 'hotMap'){
		$("#newMap").attr('src','/SNS/Tpl/default2/Public/img_Map/db_menu_1_a.gif'); 
		$("#hotMap").attr('src','/SNS/Tpl/default2/Public/img_Map/db_menu_2_b.gif');
		//$("#MyMap").attr('src',"/SNS/Tpl/default2/Public/img_Map/db_menu_3_a.gif");
		getMapList('tab_all',13);
	}else if(type == 'newMap'){
		$("#newMap").attr('src','/SNS/Tpl/default2/Public/img_Map/db_menu_1_b.gif'); 
		$("#hotMap").attr('src','/SNS/Tpl/default2/Public/img_Map/db_menu_2_a.gif');
		//$("#MyMap").attr('src',"/SNS/Tpl/default2/Public/img_Map/db_menu_3_a.gif");
		getMapList('tab_all',13);
	}
	
}

function getMyMap(){
		$("#cxv_bx").html(
			'<table width="95%" border="0" cellspacing="0" cellpadding="0" style="margin-left:10px;padding-right:10px;line-height:22px;">'+
		'<tr><td width="40%"><A HREF="/index/Map/rule" target="_blank">'+
			'<br/></A></td><td width="10%"><A HREF="/index/Map/joins" target="_blank"><img src="/SNS/Tpl/default2/Public/img_Map/cansai.gif" border="0"></A></td><td width="50%">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A HREF="/index/Map/landMark" target="_blank"><img src="/SNS/Tpl/default2/Public/img_Map/toupiao.gif" border="0"></A>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<A HREF="/index/Map/help2" target="_blank"><img src="/SNS/Tpl/default2/Public/img_Map/btn_help.gif" border="0"></A></td></tr>'+
   	  '<tr><td colspan="3"><p>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;smart City Map城市地标评选活动已在13个城市火热展开。无论是主题酒吧、画廊，还是艺术工坊，只要你的地标与众不同，就有机会成为smart City Map的至IN大热门，每个城市得票最多的20个地标更可获得丰厚奖品。</p></td></tr>'+
          '<tr><td colspan="3"><span style="color:#FFA041; font-weight: bold;padding-left:30px;">奖项设置：</span></p></td></tr>'+
			'</table><table width="80%" cellspacing="0" cellpadding="0" style="margin-left:20px;" >'+
            '<tr><td width="20%" style="padding-bottom:5px; padding-left: 20px;"><img src="/SNS/Tpl/default2/Public/img_Map/fBOBBIBROWN.jpg" border="0"></td><td colspan="2" valign="top" align="left" width="80%"><B>参与幸运奖：</B><br />著名彩妆品牌“BOBBI BROWN”提供的彩妆产品。共50份，在所有参与上传地标的参赛者中随机抽取。</td></tr>  '+     
            '<tr><td width="30%" style="padding-bottom:5px; padding-left: 20px;"><img src="/SNS/Tpl/default2/Public/img_Map/smart_car_shouye.jpg" border="0"></td><td colspan="2" valign="top"><B>smart城市达人奖：</B><br />1:18比例制作的smart精美车模一辆。共13辆，每个城市得票最多的参赛者将获得一辆。</td></tr>  '+     
            '<tr><td width="30%" style="padding-bottom:5px; padding-left: 20px;"><img src="/SNS/Tpl/default2/Public/img_Map/fxiechen.jpg" border="0"></td><td colspan="2" valign="top"><B>最IN推荐优胜奖：</B><br />价值200元携程旅行券一张。共260张，每个城市中得票数最多的前20名的参与者将获得一张。</td></tr>  '+     
            '<tr><td width="30%" style="padding-bottom:5px; padding-left: 20px;"><img src="/SNS/Tpl/default2/Public/img_Map/fxiechen.jpg" border="0"></td><td colspan="2" valign="top"><B>投票幸运奖：</B><br />价值100元携程旅行券一张。共520张，每个城市的每个最IN地标都将产生2名幸运投票奖获得者。</td></tr>  '+     
		    '<tr><td width="30%" style="padding-bottom:5px; padding-left: 20px;"><img src="/SNS/Tpl/default2/Public/img_Map/fshirt02.jpg" border="0"></td><td colspan="2" valign="top"><B>smart fortwo幸运奖：</B><br />smart精美T-shirt, 每个城市每周两名幸运者（男女各一款），将从所有参与smart City Map活动的用户中随机抽取。</td></tr>  '+     
	   		'<tr><td colspan="3"><p>&nbsp;&nbsp;&nbsp;&nbsp; 凡参与此次活动的注册用户将获赠一辆在“我的smart”抢车位游戏中使用的特别定制版smart小车。</p></td></tr></table>'+
			'<table width="95%" cellspacing="0" cellpadding="0" style="margin-left:20px;" ><tr><td colspan="3" align="right"><a href="/index/Map/rule" target="_blank"><img src="/SNS/Tpl/default2/Public/img_Map/more.gif" border="0" /></a></td></tr></table>');
}
//获取新建的Map的Id
function getInfo(){
	var id = $("#newMapInsertIdx").val();
	//return outShare("{$Think.config.SITE_HOST}/SS/Map/content/"+id);
	return outShare(site_host+"/content/"+id);
}
function getMapId(){
	var id = $("#newMapInsertId").val();
	doFaveAll(id);
}
function returnLocationId(location){
	switch (location)
	{
	case 'tab_bj':locationId = 0;
		break;
	case 'tab_sh':locationId = 1;
		break;
	case 'tab_gz':locationId = 2;
		break;
	case 'tab_sy':locationId = 3;
		break;
	case 'tab_dl':locationId = 4;
		break;
	case 'tab_wx':locationId = 5;
		break;
	case 'tab_wz':locationId = 6;
		break;
	case 'tab_sz':locationId = 7;
		break;
	case 'tab_hz':locationId = 8;
		break;
	case 'tab_cd':locationId = 9;
		break;
	case 'tab_cq':locationId = 10;
		break;
	case 'tab_xm':locationId = 11;
		break;
	case 'tab_nj':locationId = 12;
		break;
	default : locationId = 'tab_all';
		break;
	}
	return locationId;
}
//ajax调用获得Map列表
function getMapList(location,area){
	//alert(theType);
	$("a#tab_all").removeClass('sgetfoc');
	$("a#tab_bj").removeClass('sgetfoc');
	$("a#tab_sh").removeClass('sgetfoc');
	$("a#tab_gz").removeClass('sgetfoc');
	$("a#tab_sy").removeClass('sgetfoc');
	$("a#tab_dl").removeClass('sgetfoc');
	$("a#tab_wx").removeClass('sgetfoc');
	$("a#tab_wz").removeClass('sgetfoc');
	$("a#tab_sz").removeClass('sgetfoc');
	$("a#tab_hz").removeClass('sgetfoc');
	$("a#tab_cd").removeClass('sgetfoc');
	$("a#tab_cq").removeClass('sgetfoc');
	$("a#tab_xm").removeClass('sgetfoc');
	$("a#tab_nj").removeClass('sgetfoc');
	$("a#"+location).addClass('sgetfoc');
	/*
	switch (location)
	{
		case 'tab_bj':location = 0;
			break;
		case 'tab_sh':location = 1;
			break;
		case 'tab_gz':location = 2;
			break;
		default:location = 'tab_all';
			break;
	}
	*/
	location = returnLocationId(location);
	$.ajax({
		type: "POST",
		url: APP+"/Map/getLocationMap",
		data:   "location="+location+"&type="+theType,
		success: function(msg){
			$("#cxv_bx").html(msg);
			if(area!=13){
				$("#moreTag").attr('href',APP+"/Map/landMark/L/"+area);
			}else{
				$("#moreTag").attr('href',APP+"/Map/landMark/");
			}
		} 
	});
}


/*坐标跳向查看详细页面*/
function goContent(){
	var mapId = $('#markerInfo input:eq(0)').val();
	window.location=APP+"/Map/content/id/"+mapId;
}
/** 公用获得所有列表信息-start*/
//得到收藏的title，并且赋值给收藏弹出层
function getListInfo(title,id){
	var mapTitle = title;
		var mapId     = id;
	$("#newMapInsertId").val(mapId);
}
//Map的四个页面的Ajax调用结束
/********************************
	google map api
 ********************************/

/********************************
  map.openInfoWindow(map.getCenter(),
                           document.createTextNode("Hello, world"));

**********************************/
var markers;
var map;
var flashcontent;
var centers =[
	{'name':'中国', 'pt':[34.089,103.799],'zoom':4},
    {'name':'北京', 'pt':[39.917,116.397],'zoom':10},
    {'name':'上海', 'pt':[31.227,121.473],'zoom':10},
    {'name':'广州', 'pt':[23.138,113.264],'zoom':10},
	{'name':'沈阳', 'pt':[41.808,123.431],'zoom':12},
    {'name':'大连', 'pt':[38.913,121.615],'zoom':12},
    {'name':'无锡', 'pt':[31.579,120.301],'zoom':13},
    {'name':'温州', 'pt':[27.987,120.654],'zoom':12},
	{'name':'深圳', 'pt':[22.544,114.057],'zoom':12},
    {'name':'杭州', 'pt':[30.225,120.096],'zoom':12},
    {'name':'成都', 'pt':[30.656,104.066],'zoom':12},
    {'name':'重庆', 'pt':[29.534,106.511],'zoom':12},
	{'name':'厦门', 'pt':[24.483,118.136],'zoom':12},
    {'name':'南京', 'pt':[32.053,118.767],'zoom':12} 
];
function closewindow(){ 
	map.clearOverlays();
	//$('#placelist').hide();
	//if($('#content_show').length>0){
		//$('#map_canvas').hide();
		//$('#content_show').show();	
	/*由cate标记 坐标打完之后转向页面，还是层的隐藏或显示*/
	//}else if($('input[@name=cate]').length>0){
		//mapId = $('#newMapInsertId').val();
		//window.location = APP+'/Map/content/id/'+mapId;
	//}else{
		//$('#map_canvas').empty();
		//$('#map_canvas').html(flashcontent);
	//}else{
		mapId = $('#newMapInsertId').val();
		window.location = APP+'/Map/content/id/'+mapId;
	//}
}
function dosubmit(lat,lng,mapId,address,icon){
	$.post(APP+"/Map/addMarker",{mapId:mapId,lat:lat,lng:lng,address:address,icon:icon},function(txt){
		if(add ==true){
			if(txt == '1'){
				alert('添加坐标成功');
			}else{
				alert('添加坐标失败');
			}
		}else{
			if(txt == '1'){
				alert('修改坐标成功');
			}else{
				alert('修改坐标失败');
			}	
		}
	});
	return;
}
function getloc(marker,mapId,icon,onlyshow){
	var latlng = marker.getPoint() ; 
	geocoder = new GClientGeocoder();
	geocoder.getLocations(latlng,function(response) 
	{
		if(!response || response.Status.code != 200)
		{
			return false;
		}
		else
		{
			var address = response.Placemark[0].address;
			var lat = latlng.lat();
		    var lng = latlng.lng();
			//var divstr = "<div class='jxensetzhouyu'>lat:"+lat+"，lng:"+lng+"<br/>地址："+address+"</div>"+ "，<br>缩放级别为：" + map.getZoom();
			var divstr = "<div class='jxensetzhouyu'>地址："+address+"</div>";
			if(onlyshow == true){
				 divstr +="<div><input onclick=\"dosubmit("+lat+","+lng+","+mapId+",'"+address+"','"+icon+"');closewindow();\" class='fb-yes' type='button'  value='确定' ></div>";
			}
            marker.openInfoWindowHtml(divstr);
		}
	});
}
function getIcon(iconImg){
	var icon = new GIcon();
    icon.image = iconImg;
    icon.iconAnchor = new GPoint(16, 16);
    icon.infoWindowAnchor = new GPoint(16, 0);
    icon.iconSize = new GSize(21, 21);
    //icon.shadow = "images/sun"+ IMAGES[i] + "-shadow.png";
    icon.shadowSize = new GSize(59, 32);
    //ICONS[i] = icon;
	//return ICONS[i];
	return icon;
}
function showMarkerInfo(marker,markerInfo){
	
	//var cTime = new Date(parseInt(markerInfo.cTime) * 1000).toLocaleString().replace(/年|月/g, " - ").replace(/日/g, " "); 
	var describes="";
	$('#markerInfo h3').html("<a href='javascript:goContent();'>"+markerInfo.title+"</a>");
	if(markerInfo.cover !=''){
		$('#markerInfo table p:eq(0)').html("<img onclick='javascript:goContent();' style='cursor:pointer' src='/Public/Thumb/?w=191&h=120&t=c&url="+markerInfo.cover+"'/>");	
	}
	$('#markerInfo table p:eq(0)').html("<img onclick='javascript:goContent();' style='cursor:pointer' src='/Public/Thumb/?w=191&h=120&t=c&url="+markerInfo.cover+"'/>");	
	if(markerInfo.describe.length>50){
		//describes=markerInfo.describe.substring(0,50)+"...";
		describes=markerInfo.describe.substring(0,50);
	}else{
		describes=markerInfo.describe;	
	}	
	$('#markerInfo table p:eq(1)').html("<a href='javascript:goContent();'>"+describes+"</a>");	
	$('#markerInfo table p:eq(2)').find('span').eq(0).html(markerInfo.readCount);
	$('#markerInfo table p:eq(2)').find('span').eq(1).html(markerInfo.cTime);
	$('#markerInfo table p:eq(2)').find('a').eq(0).attr('href',APP+"/Map/content/id/"+markerInfo.id);
	$('#markerInfo table p:eq(3)').find('a').eq(0).attr('onclick',"vote("+markerInfo.id+")");
	$('#markerInfo input:eq(0)').val(markerInfo.id);
	$('#markerInfo a[@alt=fShare_o]').attr("rel",APP+"/Share/map/id/"+markerInfo.id);
	$('#userspace').attr("href","http://www.openyourmind.cn/SS/space/"+markerInfo.userId);
	$('#userspace').html(markerInfo.username);
	$("#newMapInsertId").val(markerInfo.id);
	var html=$('#markerInfo').html();
	//alert(markerInfo.title);
	//GEvent.addListener(marker, 'click', function(markerInfo) {
		//alert(markerInfo.title);
		//alert(markerInfo.cover);
        //showMarkerInfo(marker,markerInfo);
    //});
	marker.openInfoWindowHtml(html);
	
}
function  getMarkerById(mapId){
	$.post(APP+"/Map/getMarkerById",{mapId:mapId},function(txt){
		if(txt == '-1'){
			alert('该坐标不存在或已删除');
			return false;
		}else{
			var markerInfo = $.evalJSON(txt);
			if(markerInfo.icon == ''){
				markerInfo.icon = 'http://map.openyourmind.cn/SNS/Tpl/default2/Public/img_Map/x_ico015.jpg';
			}
			return markerInfo;
		}
	});
}
function createMarker(markerobj) {
	var point = new GLatLng(parseFloat(markerobj.lat),parseFloat(markerobj.lng));
	var newmarker = new GMarker(point, getIcon(markerobj.icon));
	GEvent.addListener(newmarker, 'click', function(){
		$.post(APP+"/Map/getMarkerById",{mapId:markerobj.id},function(txt){
			if(txt == '-1'){
				alert('该坐标不存在或已删除');
				return false;
			}else{
				var markerInfo = $.evalJSON(txt);
				if(markerInfo.icon == ''){
					markerInfo.icon = 'http://map.openyourmind.cn/SNS/Tpl/default2/Public/img_Map/x_ico015.jpg';
				}
				showMarkerInfo(newmarker,markerInfo);
			}
		});
	});
    return newmarker;
}
function positionMarker(mapId,centerobj,icon){
	var pt = centerobj.pt;
	var lat = pt[0];
	var lng = pt[1];
	var point = new GLatLng(lat,lng);
	var newmarker = new GMarker(point, {draggable: true, icon: getIcon(icon)});
	GEvent.addListener(newmarker, "dragstart", function() {
		map.closeInfoWindow();
	});
	GEvent.addListener(newmarker, "dragend", function(){
		getloc(newmarker,mapId,icon,true);
	});
	GEvent.addListener(newmarker, "click", function(){
		//var div='<div>';
		///div +='<p>拖动icon定位坐标点</p><p>如果要中止，请点击取消按钮</p>';
		//div +='<p><input type="button"  value="取消" class="bnt_yellow_mp" style="margin-left:5px;"  onclick="closewindow();"/></p>';
		//div +='</div>';
		//newmarker.openInfoWindowHtml(div);
		getloc(newmarker,mapId,icon,true);
	});
	return newmarker;
}
function getMarkerxml(url){
	GDownloadUrl(url, function(data){
		return data;	
	});
}

function transferToMarkers(citynum){
	var url = APP+"/Map/getMarkerxml";
	var params = getParam('city',citynum-1);
	GDownloadUrl(url+params, function(data){
		var xml = GXml.parse(data);
		var markers_xml= xml.documentElement.getElementsByTagName("marker");
		for (var i = 0; i < markers_xml.length; i++) {
			var icon = markers_xml[i].getAttribute("icon");
			if(icon == ''){
				icon = 'http://map.openyourmind.cn/SNS/Tpl/default2/Public/img_Map/x_ico015.jpg';
			}else{
				icon = 'http://map.openyourmind.cn/SNS/Tpl/default2/Public/img_Map/x_ico'+icon+'.jpg';	
			}
			var markerobj= {'id':markers_xml[i].getAttribute("id"),
							'lat':markers_xml[i].getAttribute("lat"),
							'lng':markers_xml[i].getAttribute("lng"),
							//'userId':markers_xml[i].getAttribute("userId"),
							//'title':markers_xml[i].getAttribute("title"),
							//'address':markers_xml[i].getAttribute("location"),
							//'describe':	markers_xml[i].getAttribute("describe"),
							'icon':icon
							//'cover':markers_xml[i].getAttribute("cover"),
							//'cTime':markers_xml[i].getAttribute("cTime"),
							//'readCount': markers_xml[i].getAttribute("readCount"),
							//'username': markers_xml[i].getAttribute("username")
							};
			//markers.push(createMarker(point, name, address, icon));
			map.addOverlay(createMarker(markerobj));
		}	
	});	
}
function showmap(centerobj){
	add = true;
	if (GBrowserIsCompatible()) 
	{
       	flashcontent= $('#map_canvas').html();
		$('#content_show').hide();
		$('#map_canvas').show();
		map = new GMap2(document.getElementById('map_canvas'));
		var pt = centerobj.pt;
		var lat = pt[0];
		var lng = pt[1];
        var point = new GLatLng(lat,lng);
        map.setCenter(point, centerobj.zoom);
		map.addControl(new GLargeMapControl());
	}
}
function getParam(type,citynum){
	switch(type)
	{
		case 'bound':
			var bounds = map.getBounds();
			var southWest = bounds.getSouthWest();
			var northEast = bounds.getNorthEast();
			var lngSpan = northEast.lng() - southWest.lng();
			var latSpan = northEast.lat() - southWest.lat();
			var params= "/lat/"+southWest.lat()+"-"+latSpan+"/lng/"+southWest.lng()+"-"+lngSpan;
			break;
		case 'city':
			var params= "/area/"+citynum;
			break;
	}
	return params;
}


/************************************
		google map search		
************************************/
//<![CDATA[
    // Create our "tiny" marker icon

	google.load('search', '1');
    // Our global state
    var gLocalSearch;
    //var gMap;
    var gSelectedResults = [];
    var gCurrentResults = [];
    var gSearchForm;
 
    // Create our "tiny" marker icon
    var gSmallIcon = null;
 
 
   
 
    // Called when Local Search results are returned, we clear the old
    // results and load the new ones.
    function OnLocalSearch() {
      if (!gLocalSearch.results){ return ; }
 
      // Clear the map and the old search well
      for (var i = 0; i < gCurrentResults.length; i++) {
        if (!gCurrentResults[i].selected()) {
          map.removeOverlay(gCurrentResults[i].marker());
        }
      }
 
      gCurrentResults = [];
	  // move the map to the first result
      var first = gLocalSearch.results[0];
	  map.clearOverlays();
	  var mapId	= $("#newMapInsertId").val();
	  var icon_img = $(".icons_show").find('img').eq(0).attr('src');
	  var centerobj={'pt':[first.lat,first.lng]};
	  var newmarker =  positionMarker(mapId,centerobj,icon_img);
	  map.addOverlay(newmarker);
      for (var j = 1; j < gLocalSearch.results.length; j++) {
        gCurrentResults.push(new LocalResult(gLocalSearch.results[j]));
      }
 
 
      map.panTo(new GLatLng(first.lat, first.lng));
    }
 
    // Cancel the form submission, executing an AJAX Search API search.
    function CaptureForm(searchForm) {
      gLocalSearch.execute(searchForm.input.value);
      return false;
    }
 
 
 
    // A class representing a single Local Search result returned by the
    // Google AJAX Search API.
    function LocalResult(result) {
      this.result_ = result;
      this.resultNode_ = this.unselectedHtml();
      map.addOverlay(this.marker(gSmallIcon));
    }
 
    // Returns the GMap marker for this result, creating it with the given
    // icon if it has not already been created.
    LocalResult.prototype.marker = function(opt_icon) {
      if (this.marker_){ return this.marker_;}
      var marker = new GMarker(new GLatLng(parseFloat(this.result_.lat),
                                         parseFloat(this.result_.lng)),
                               opt_icon);
	  

      GEvent.bind(marker, "click", this, function() {
        marker.openInfoWindow(this.selected() ? this.selectedHtml() :
                                                this.unselectedHtml());
      });
      this.marker_ = marker;
      return marker;
    };
 
    // "Saves" this result if it has not already been saved
    LocalResult.prototype.select = function() {
      if (!this.selected()) {
        this.selected_ = true;
 
        // Remove the old marker and add the new marker
        map.removeOverlay(this.marker());
        this.marker_ = null;
        map.addOverlay(this.marker(G_DEFAULT_ICON));
 
        // Add our result to the saved set
        document.getElementById("selected").appendChild(this.selectedHtml());
 
        // Remove the old search result from the search well
        this.resultNode_.parentNode.removeChild(this.resultNode_);
      }
    };
 
    // Returns the HTML we display for a result before it has been "saved"
    LocalResult.prototype.unselectedHtml = function() {
      var container = document.createElement("div");
      container.className = "unselected";
      container.appendChild(this.result_.html.cloneNode(true));
      
      return container;
    };
 
    // Returns the HTML we display for a result after it has been "saved"
    LocalResult.prototype.selectedHtml = function() {
      return this.result_.html.cloneNode(true);
    };
 
    // Returns true if this result is currently "saved"
    LocalResult.prototype.selected = function() {
      return this.selected_;
    };

	 // Set up the map and the local searcher.
    function OnLoad() {
	  //var google = new Object();
	  
	  $('#placelist').show();
      gSmallIcon = new GIcon();
      gSmallIcon.image = "http://labs.google.com/ridefinder/images/mm_20_yellow.png";
      gSmallIcon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
      gSmallIcon.iconSize = new GSize(12, 20);
      gSmallIcon.shadowSize = new GSize(22, 20);
      gSmallIcon.iconAnchor = new GPoint(6, 20);
      gSmallIcon.infoWindowAnchor = new GPoint(5, 1);
      
      gSearchForm = new google.search.SearchForm(false, document.getElementById("searchform"));
      gSearchForm.setOnSubmitCallback(null, CaptureForm);
      gSearchForm.input.focus();
 
      // Initialize the map
	  $('#placelist').show();
 	  map.clearOverlays();

      // Initialize the local searcher
      gLocalSearch = new google.search.LocalSearch();
      gLocalSearch.setCenterPoint(map);
      gLocalSearch.setSearchCompleteCallback(null, OnLocalSearch);
 
    }
 
    //]]>
 function showSingleMarker(mapId){
	$.post(APP+"/Map/getMarkerById",{mapId:mapId},function(txt){
		if(txt == '-1'){
			alert('该坐标不存在或已删除');
			return false;
		}else{
			var mInfo = $.evalJSON(txt);
			if(mInfo.icon == ''){
				mInfo.icon = 'http://map.openyourmind.cn/SNS/Tpl/default2/Public/img_Map/x_ico015.jpg';
			}
		}
		var ToCenter = {'pt':[mInfo.lat,mInfo.lng],'zoom':14};
		showmap(ToCenter);
		var newmarker = createMarker(mInfo);
		map.addOverlay(newmarker);
		showMarkerInfo(newmarker,mInfo);
	});
}

function toDomarker()
{
	var mapId	= $("#newMapInsertId").val();
	var icon = $(".icons_show").find('img').eq(0).attr('src');
	$('#facebox').fadeOut();
	var center = centers[parseInt($('#areaId').val())+1];
	showmap(center);
	OnLoad();
	map.clearOverlays();
	var marker = positionMarker(mapId,center,icon);	
	map.addOverlay(marker);
}
function toeditmarker(mapId,lat,lng)
{
	var icon = $(".icons_show").find('img').eq(0).attr('src');
	$('#m_icon').attr('src',icon);
	setTimeout(function(){ 
			$('#facebox').fadeOut();	
	},1000);
	if($('#content_show').length>0){
		$('#content_show').hide();
		$('#map_canvas').show();	
	}
	var center = centers[1];
	if(lat !='' || lng !=''){
		center = {'name':name,'pt':[lat.toFixed(3),lng.toFixed(3)],'zoom':10};
	}else{
		center = centers[parseInt($('#areaId').val())+1]; 
	}
	showmap(center);
	OnLoad();
	var marker = positionMarker(mapId,center,icon);
	map.addOverlay(marker);
}
function showcityMarkers(citynum){
	showmap(centers[citynum]);
	transferToMarkers(citynum) ;		
}
function  showMarkersType(mapId,city){
	if(mapId){
		showSingleMarker(mapId);
		return;
	}
	showcityMarkers(city);
}
function showNewMarker(){
	var	ran		=	Math.random()*1000;
	$.post(APP+"/Map/getnewmarker",{ran:ran},function(txt){
		var newid = parseInt(txt);
		if(newid==0 || newid == null ){
			return false;;
		}else{
			showSingleMarker(newid);
		}			
	});	
}
$(document).ready(function(){
	var city = $('#city').val();
	if(city !='-2' && (typeof city) !='undefined'){
		city = parseInt(city); 
		showcityMarkers(city);
		$('.cityem span').removeClass('emcolor');
		$('.cityem span:eq('+(0+parseInt(city))+')').addClass('emcolor');
		//$('.cityem:eq('+(1+city)+')').attr('color','#FFA041');
	}
	if($('input[@name=contentmapId]').length>0){
		var contentmapId = 	$('input[@name=contentmapId]').val();
		if(contentmapId !='' && (typeof contentmapId) !='undefined'){
			contentmapId = parseInt(contentmapId); 
			showSingleMarker(contentmapId);
		}
	}
	$(".hidenext").toggle(function(){
			var div = $(this).parents("td").parents("tr").parents("table").parents("div").next('div').eq(0).hide();
			$(this).attr('src','/SNS/Tpl/default2/Public/img_Map/show.gif');
	},function(){
			var div = $(this).parents("td").parents("tr").parents("table").parents("div").next('div').eq(0).show();
			$(this).attr('src','/SNS/Tpl/default2/Public/img_Map/small.gif');
	});
});
function vote(id){
	
	$.post(APP+"/Map/voteOnNet",{id:id},function(txt){
		if(txt==-2){
			alert('请您登录以后再投票！');
		}else if(txt==-3){
			alert('请选择你要投票的地标！');
		}else if(txt==-4){
			alert('抱歉，您不能给自己投票！');
		}else	if(txt!=-1){
			$("#voteNum"+id).html('<strong>票数:</strong>'+txt);
			alert("投票成功！")
		}else{
			alert("抱歉，请您24小时后再给当前用户投票！");
		}
	});
}

/**
取得userId
*/

function setUserId(id,name,face)
{
	$("#hiddenUserId").val(id);	
	$("#faceboxContent").html('确定加'+name+'为好友么？');
	$("#userface").html('<img src="'+face+'" width="96" />');
}

/**
 * 加为好友
 *
 */	 
 function addFriend(id){
	var selectList = $('#facebox #selectList option:selected').val();
	var  ran=Math.random();
	$("#facebox .content").html('<div class="loading">&nbsp;</div>');
	$.post(APP+'/Friend/newadd',{id:id,selectList:selectList,ran:ran},function(txt){
	    if(txt=='1'){
			$("#facebox .content").html('<div class="center">成功发送好友请求！</div>');
		}
		else
		if(txt=='0'){
			$("#facebox .content").html('<div class="center">你已经发过请求了，而对方还没有处理！</div>');
		}
		else
		if(txt=='-1'){
			$("#facebox .content").html('<div class="center">对方已经在你的好友名单中！</div>');
		}
		else
		if(txt=='-2'){
			$("#facebox .content").html('<div class="center">不能加自己为好友！</div>');
		}
		setTimeout(function(){$.facebox.close();},2000);
	});
}

/**
 * 添加好友列表
 *
 */	 
 function addFriendList(){
	var name = ($('#facebox #friendListName').val());
	var	ran		=	Math.random();

	//$("#facebox .content").html('<div class="loading">&nbsp;</div>');
	if(!name){
		alert("名称不能为空！");return;
	}
	
	$.post(APP+'/Friend/doAddFriendList',{name:name,ran:ran},function(flid){
	    if(flid == '1'){
			$("#facebox #selectList").append("<option value='"+flid+"' selected='true'>"+name+"</option>"); 
			$('#facebox .errorFriendList').text('');
		}
		else if(flid == '-1')
		{
			//$("#facebox .content").html('<h2 style="padding:20px;" onclick="$.facebox.close()">已经存在！！单击关闭。</h2>');
			$('#facebox .errorFriendList').text('该分组已经存在');
		}
		else
		{
			$("#facebox .content").html('<h2 style="padding:20px;" onclick="$.facebox.close()">添加失败！！单击关闭。</h2>');
		}
	});
}

/**
 * 发送好友请求时添加好友列表
 */
 function addFriendListNew(){
	var name = ($('#facebox #friendListName').val());
	var	ran		=	Math.random();

	//$("#facebox .content").html('<div class="loading">&nbsp;</div>');
	
	$.post(APP+'/Friend/doAddFriendList',{name:name,ran:ran},function(flid){
	    if(flid){
			//$("#facebox .content").html('<h2 style="padding:20px;" onclick="$.facebox.close()">添加成功！</h2>');
			//$("#facebox .selectList").append('<option value="" selected>'+name+'</option>');
			//$("<option value='1'>1111</option>").appendTo("#facebox #selectList");
			$("#facebox #selectList").append("<option value='"+flid+"' selected='true'>"+name+"</option>"); 
			//setTimeout(function(){$.facebox.close();},1000);
		}
		else
		{
			$("#facebox .content").html('<h2 style="padding:20px;" onclick="$.facebox.close()">添加失败！！单击关闭。</h2>');
		}
	});
}

