var map;
var z = [];
var markers = [];
var geomarkers = [];
var polygon;
var padding = 0.24;
var ZOOM_IN_LIMIT = 17;
var ZOOM_OUT_LIMIT = 5;
var ua;
var rpp = 100;
var markerNum = 100
var lock = 0;
var pzoom;
var iconword1 = "candlenight";
var iconword2 = "#candlenight";
var iconword3 = "キャンドルナイト";
var iconword4 = "candle night";

//////////////Window resize 関数////////////////
$(function(){
	$(window).resize(function(){
			$('#sidebar').css('height' ,$(window).height()-$('#header').outerHeight({border:true}));
			$('#map').css('height',$(window).height()-$('#header').outerHeight({border:true}));
			$('#map').css('width' ,$(window).width()-$('#sidebar').outerWidth({border:true}));
	});
});

//////////////ロード関数////////////////
function load() {
	if(navigator.userAgent.indexOf("iPhone") != -1 || navigator.userAgent.indexOf("iPod") != -1){
		ua="iphone";
		padding = 0.10;
		rpp = 30;
		markerNum = 25;
		$('#sidebar').css("display","none");
		$('#sidebar').css("width","0");
		$('#header').css("height","30px");
		$('#header img').css("height","30px");
		$('#header img').css("width","163px");
		$('.plink').css("display","none");
		$('.gps').css("display","block");
		$('#header').css("display","block");
	}else{
		$('#header').css("display","block");
	}
	var param = get_param();
	var query = param['q'];
	if(!query) query = "";
	query = decodeURIComponent(query);
	document.forms[1].query.value = query;

	$('#sidebar').css('height' ,$(window).height()-$('#header').outerHeight({border:true}));
	$('#map').css('height',$(window).height()-$('#header').outerHeight({border:true}));
	$('#map').css('width' ,$(window).width()-$('#sidebar').outerWidth({border:true}));
	
	var lat   = param['lat'];
	var lng   = param['lng'];
	if(!(lat && lng)){
		if(google.loader.ClientLocation == null){
			lat = "35.658724";
			lng = "139.701369";
		}else{
			var lat = google.loader.ClientLocation.latitude;
			var lng = google.loader.ClientLocation.longitude;
			var region = google.loader.ClientLocation.address.region;
			var city = google.loader.ClientLocation.address.city;
			document.forms[1].address.value = region+city;
		}
	}
	var zoom  = parseInt(param['zoom']);
	if(!zoom) zoom = 14;
	pzoom = zoom;
	
	showPermaLink(lat,lng,zoom);
	
	if (GBrowserIsCompatible()) {
		//地図を作成
		map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(lat,lng),zoom);
        map.addControl(new GMapTypeControl());
		map.enableScrollWheelZoom();	
	
		if(param["mode"]=="satellite") map.setMapType(G_SATELLITE_MAP);
		if(ua!="iphone"){
			map.addControl(new GSmallMapControl());
		}
		setMarker(lat,lng,zoom,query,rpp);
		if(query == iconword1 | query == iconword2 | query == iconword3 | query == iconword4){		//iconcustom
			showCandlebg();									//iconcustom

//			markerNum = 200;									//iconcustom
//			rpp = 200;										//iconcustom
		}													//iconcustom
		GEvent.addListener(map,"zoomend",function(oz,nz) {
		  if (nz>ZOOM_IN_LIMIT) map.setZoom(oz);
		  if (nz<ZOOM_OUT_LIMIT) map.setZoom(oz);
		});
		
		GEvent.addListener(map,"move",function() {
			var center = map.getCenter();
			query = document.forms[1].query.value;
			showPermaLink(center.y,center.x,map.getZoom());
			if(query == iconword1 | query == iconword2 | query == iconword3 | query == iconword4){		//iconcustom
				if(polygon) map.removeOverlay(polygon);						//iconcustom
				showCandlebg();									//iconcustom
			}													//iconcustom
		});
		
		GEvent.addListener(map, 'moveend', function() {  //移動した後の処理 
//				if(polygon)map.removeOverlay(polygon);
//				showArea();
			if(!lock){
				var sw = map.fromContainerPixelToLatLng(new GPoint(parseInt(map.getSize().width*(1-padding)),parseInt(map.getSize().height*padding)));
				var ne = map.fromContainerPixelToLatLng(new GPoint(parseInt(map.getSize().width*padding),parseInt(map.getSize().height*(1-padding))));
	
				var center = map.getCenter();
				var zoom = map.getZoom();
	
				var area = new GLatLngBounds(ne,sw);
				var count = 0;
				for (var i=0; i<markers.length; i++) {
					if (area.containsLatLng(markers[i].getPoint())){
						count++;
					}
				}
				for (var i=0; i<geomarkers.length; i++) {
					if (area.containsLatLng(geomarkers[i].getPoint())){
						count++;
					}
				}
				//エリア内にマーカーなし＆ズームレベル変更
				if((count==0 ||pzoom!=zoom) && zoom<=ZOOM_IN_LIMIT &&zoom>=ZOOM_OUT_LIMIT){
					map.clearOverlays();
					lat = center.y;
					lng = center.x;
					setMarker(lat,lng,zoom,query,rpp);
				}
			}
		});

		if(ua!="iphone"){
			GEvent.addListener(map,'click', function() {	//iconcustom
				map.closeInfoWindow();						//iconcustom
			});												//iconcustom
		}
	}
}

//////////////マーカー表示関数////////////////
function setMarker(lat,lng,zoom,query,rpp){
	if($("#loading")){$("#loading").remove();}  
	$("#map").append('<div id="loading" style="position:absolute; top:'+parseInt(map.getSize().height-15)/2+'px; left:'+parseInt(map.getSize().width-128)/2+'px; z-index:100"><img src="/img/loading2.gif" /></div>');  

	$(document).ready(function(){
		var zzPoint = map.fromContainerPixelToLatLng(new GPoint(0,0));
		var zhPoint = map.fromContainerPixelToLatLng(new GPoint(0,parseInt(map.getSize().height)));
		var r = parseInt(zhPoint.distanceFrom(zzPoint)/2/1000);
		if(query == iconword1 | query == iconword2 | query == iconword3 | query == iconword4) r=parseInt(r*1.3);			//iconcustom
		if(r==0)r=1;
		if(document.forms[1].query.value){
			var q = document.forms[1].query.value;
		}else{
			var q = "*";
		}
		twurl = "http://search.twitter.com/search.json?q="+ encodeURIComponent(q) +"&rpp="+rpp+"&geocode=" + lat + "%2C" + lng + "%2C" + r + "km&callback=?";
		$.getJSON(twurl,function(data){
			map.clearOverlays();//何故かここでマーカーが再描画されるのでクリアする。
			if(query == iconword1 | query == iconword2 | query == iconword3 | query == iconword4){							//iconcustom
				if(polygon)map.removeOverlay(polygon);						//iconcustom
				showCandlebg();									//iconcustom
			}													//iconcustom
			if(data.results.length>0){
				markers = [];
				geomarkers = [];
				var pgeoNum=0;
				var lat = "";
				var lng = "";
				var uniqueResult=[];
				var uuid=[];
				$.each(data.results, function(i,item){ 

					//DEL:指定によるユーザ削除
					var matchObj = new RegExp("DEL:" + item.from_user,"i");
					var del = item.text.match(matchObj);
					if(del){
						for(var m=0;m<uniqueResult.length;m++){
							if(uniqueResult[m]){
								if(uniqueResult[m].from_user_id == item.from_user_id){
									uniqueResult.splice(m,1);
									m--;
								}
							}
						}
						uuid.push(item.from_user_id);
					}

					//UUの場合uniqueResultにpush
					var n;
					var uu = true;
					for(var n=0;n<uuid.length;n++){
						if(uuid[n]==item.from_user_id){
							uu = false;
						}
					}
					if(uu && uniqueResult.length<=markerNum){
						uuid.push(item.from_user_id);
						uniqueResult.push(item);
					}
				});

				var pointnum=0;
				$.each(uniqueResult, function(i,item){ //マーカー繰り返し処理
					latlng = false;
					if(item.location){
						if(item.location.match(/(-*\d{1,2}\.\d{4,15}),[ ]*(-*\d{1,3}\.\d{4,15})/i)){
							lat = (Math.round(RegExp.$1*10000-Math.random()*10+5))/10000;
							lng = (Math.round(RegExp.$2*10000-Math.random()*10+5))/10000;
							latlng = true;
						}else{
							if(pointnum<20){
								var geocoder = new GClientGeocoder();
								geocoder.getLatLng(item.location,function(point){
									if(point){
										lat = (Math.round(point.lat()*10000-Math.random()*40+20))/10000;
										lng = (Math.round(point.lng()*10000-Math.random()*40+20))/10000;
										geomarker = makeMarker(item,i,lat,lng,1);
										geomarkers.push(makeMarker(item,i,lat,lng));
										showMarker(null,geomarker,zoom);
									}
								});
								pointnum++;
							}
						}
					}
					
					if(latlng){
						markers.push(makeMarker(item,i,lat,lng));
					}
				});
				showMarker(markers,null,zoom);
				if($("#loading")){$("#loading").remove();}
			}else{
				alert("この地点では、指定された条件の投稿はありませんでした。");
				if($("#loading")){$("#loading").remove();}
			}
		});
	});
	pzoom = map.getZoom();
}

function makeMarker(item,i,lat,lng,geo){
	if(document.forms[1].query.value) var query=document.forms[1].query.value;		//iconcustom
	var content = [];
	item.text = item.text.replace(/(http:\/\/[\x21-\x7e]+)/gi, "<a href=\"$1\" target=\"_blank\">$1</a>");
	item.text = item.text.replace(/@([\w]+)(\s*)/gi,"@<a href=\"http://twitter.com/$1\" target=\"_blank\">$1</a>$2");
	var link = '<a href="http://twitter.com/' + item.from_user + '" target="_blank">' + item.from_user + '</a>';
	var brain = '<a href="http://nounai.tweetmap.info/?uid=' + item.from_user + '" target="_blank"><img src="/img/brain.png" width="16" height="16" border="0" class="balloon-brain" /></a>';
	if(geo) link += '@' + item.location;
	var date = new Date(item.created_at);
	date = niceTime(date);

	content[i]  = '<div class="balloon"><img src="' + item.profile_image_url + '" style="float:left;width:40px;height:40px;margin: 0 10px 5px 0;">';
	content[i] += '<div class="text">' + item.text + "<br />" + brain + link +" "+ date.toLocaleString()  +'</div></div>';
	var icon = new GIcon();
	icon.image = item.profile_image_url;
	
	icon.iconSize = new GSize( 48, 48 );	// 画像の大きさ
	icon.shadowSize = new GSize( 64, 64 );	// 影画像の大きさ
	icon.iconAnchor = new GPoint( 24, 63 );	// 画像の「基準点」
	icon.infoWindowAnchor = new GPoint(43, 25);

	if(query == iconword1 | query == iconword2 | query == iconword3 | query == iconword4){		//iconcustom
		icon.iconSize = new GSize( 30, 33 );			//iconcustom
		icon.shadowSize = new GSize( 32, 32 );			//iconcustom
		icon.iconAnchor = new GPoint( 15, 16 );			//iconcustom
		icon.infoWindowAnchor = new GPoint(20, 22);		//iconcustom
	}		//iconcustom

	
	if(geo){
		icon.shadow = "/img/shadow2.png";
	}else{
		icon.shadow = "/img/shadow.png";
	}

	if(query == iconword1 | query == iconword2 | query == iconword3 | query == iconword4){		//iconcustom
		icon.shadow = null;		//iconcustom
		icon.image = "/img/candle3.png";		//iconcustom
	}		//iconcustom
	
	var marker = new GMarker(new GLatLng(lat,lng),icon);
	if(ua=="iphone"){
		GEvent.addListener(marker,'click', function() {
			this.openInfoWindowHtml(content[i]);
		});	
	}else{
		GEvent.addListener(marker,'mouseover', function() {
			this.openInfoWindowHtml(content[i]);
			if(query == iconword1 | query == iconword2 | query == iconword3 | query == iconword4){		//iconcustom
//				$(".gmnoprint").css("display","block");		//iconcustom
			}		//iconcustom
		});	
	}
	
	return marker;
}

function showMarker(markers,marker,zoom){
	manager = new GMarkerManager(map);
	if(markers)manager.addMarkers(markers,zoom,zoom);
	if(marker)manager.addMarker(marker,zoom,zoom);
	manager.refresh();
	var query = document.forms[1].query.value;
	if(query == iconword1 | query == iconword2 | query == iconword3 | query == iconword4){		//iconcustom
//		$(".gmnoprint").css("display","none");		//iconcustom
		$(".gmnoprint").css("opacity","0.8");		//iconcustom
		$(".gmnoprint").css("filter: Alpha","opacity=80");		//iconcustom
	}		//iconcustom
}

//////////////hitエリア用ポリゴン表示関数////////////////
function showArea(){
	var points = [];
	points[0] = map.fromContainerPixelToLatLng(new GPoint(parseInt(map.getSize().width*padding),parseInt(map.getSize().height*padding)));
	points[1] = map.fromContainerPixelToLatLng(new GPoint(parseInt(map.getSize().width*(1-padding)),parseInt(map.getSize().height*padding)));
	points[2] = map.fromContainerPixelToLatLng(new GPoint(parseInt(map.getSize().width*(1-padding)),parseInt(map.getSize().height*(1-padding))));
	points[3] = map.fromContainerPixelToLatLng(new GPoint(parseInt(map.getSize().width*padding),parseInt(map.getSize().height*(1-padding))));
	points[4] = map.fromContainerPixelToLatLng(new GPoint(parseInt(map.getSize().width*padding),parseInt(map.getSize().height*padding)));
	polygon = new GPolygon(points, '#ff0000', 2, 0.3, '#FF0000', 0.05);
	map.addOverlay(polygon);
}
//////////////キャンドル用関数群////////////////iconcustom///
function showCandlebg(){
	var points = [];
	points[0] = map.fromContainerPixelToLatLng(new GPoint(0,0));
	points[1] = map.fromContainerPixelToLatLng(new GPoint(map.getSize().width , 0));
	points[2] = map.fromContainerPixelToLatLng(new GPoint(map.getSize().width , map.getSize().height));
	points[3] = map.fromContainerPixelToLatLng(new GPoint(0 , map.getSize().height));
	points[4] = map.fromContainerPixelToLatLng(new GPoint(0,0));
	polygon = new GPolygon(points, '#000000', 0, 0, '#000000', 0.8);
	map.addOverlay(polygon);
}
//////////////フォーム関連関数////////////////
function addAddressToMap(response) {
	if (!response || response.Status.code == 620) {
		alert("住所検索利用回数の制限を超えました。しばらく時間をおいてからご利用ください。");
	}else if (!response || response.Status.code == 500) {
		alert("住所指定検索が利用できません。手動で移動やズームを行ってください。");
	}else if (!response || response.Status.code != 200) {
		alert("住所の場所を特定できませんでした。"+response.Status.code);
	} else {
		var place = response.Placemark[0];
		var zoom =  new Array(5,6,10,12,14,14,15,15,15,15);
		var i = response.Placemark[0].AddressDetails.Accuracy;
		lock = 1;
		map.clearOverlays();
		map.setCenter(new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]),zoom[i]);
		lock = 0;
		var center = map.getCenter();
		var lat = center.y;
		var lng = center.x;
		var query = document.forms[1].query.value;
		setMarker(lat,lng,zoom[i],query,rpp);

	}
}
function showLocation() {
	var geocoder = new GClientGeocoder();
	var address
	if(document.forms[1].address.value){
		address = document.forms[1].address.value;
	}else{
		if((navigator.language&&navigator.language.indexOf('ja')>-1)||(navigator.browserLanguage&&navigator.browserLanguage.indexOf('ja')>-1)){
			address = "日本";
		}else{
			address = "N.Y.";
		}
		document.forms[1].address.value = address;
	}
	geocoder.getLocations(address, addAddressToMap);
}
function findLocation(address) {
	document.forms[1].address.value = address;
	showLocation();
}

function showPermaLink(lat,lng,zoom){
	lat = Math.round(lat*100000)/100000;
	lng = Math.round(lng*100000)/100000;
	var queryparam ="";
	if(document.forms[1].query.value){
		queryparam = "&q=" + encodeURIComponent(document.forms[1].query.value);
	}
	var mode= "";
	if(map){
		if(map.getMapTypes()[1]==map.getCurrentMapType()){
			mode = "&mode=satellite";
		}
	}
	document.forms[0].purl.value = "http://tweetmap.info/?lat=" + lat +"&lng=" + lng + "&zoom=" + zoom + mode + queryparam;
	return false;
}

function tweetUrl(){
	var url = "http://twitter.com/home?status=" + encodeURIComponent(document.forms[0].purl.value + " #twmap");
	window.open(url);}

//////////////GETパラメータ取得関数////////////////
//sample param['lat'] //
function get_param(){
	q = location.search.slice(1).split('&');
	h = new Array();
	for (var i=0 , c=q.length ; i < c ; i++) {
		var s = q[i].split('=');
		h[s[0]] = s[1];
	}
	return h;
}

//////////////iPhone緯度経度取得関数////////////////
function getGPS(){
	navigator.geolocation.getCurrentPosition( locupdate, handleError );
}
function locupdate(pos) { 
	map.setCenter(new GLatLng(pos.coords.latitude,pos.coords.longitude),14);
}
function handleError(a) {
    alert("GPS情報を取得できませんでした。");
}

//////////////Twitter投稿関連////////////////
function updateTweet(){
	var tweetview  = '<div class="tweet-view" style="position:absolute;top:0;left:0; z-index:100;width:100%;height:100%; background-color:#000;filter:alpha(opacity=70);-moz-opacity: 0.7;opacity:0.7;"></div>';
		tweetview += '<div class="tweet-box" style="position:absolute; z-index:101;width:100%;height:100%;">';
		tweetview += '<div class="tweet-submit" style="text-align:right;padding:5px 10px; margin:50px auto 0 auto; width:250px; height:auto;background-color:#fff;">';
		tweetview += '<div class="close" style="width:100%;margin:0 0 10px 0;">[<a href="javascript:void(clearTweetview());" >CLOSE</a>]</div>';
		tweetview += '<form class="tweet-form">';
		tweetview += '<textarea type="text" name="status" style="width:240px" /></text>';
		tweetview += '<input type="button" onclick="void(profileUpdate());" value="プロフィールの現在地を更新" />';
		tweetview += '<input type="button" onclick="void(post(this.form));" value="投稿" />';
		tweetview += '</form>';
		tweetview += '</div>';
		tweetview += '</div>';
	$("body").append(tweetview);  
}
function clearTweetview(){
	$('.tweet-view').remove();
	$('.tweet-box').remove();
}
function post(f) {
	if(f.status.value){
		TwitterAPI.statuses.update(f.status.value);
		$('.tweet-form').remove();
		$(".tweet-submit").append('<div class="submit-finished">投稿が完了しました。</div>'); 
	}else{
		alert("テキストを入力してください。");
	}
}
function profileUpdate(){
	navigator.geolocation.getCurrentPosition(updateLatlng, handleError );
}
function updateLatlng(pos){
	if(pos){
		var latlng = "TweetMap: " + Math.round(pos.coords.latitude*100000)/100000 + "," +  Math.round(pos.coords.longitude*100000)/100000;
		TwitterAPI.account.update_location(latlng);
		alert("現在地情報をアップデートします。");
	}else{
		alert("現在地情報をアップデートできませんでした。");
	}
}
