function f_clientWidth() {
	return f_filterResults (
		window.innerWidth ? window.innerWidth : 0,
		document.documentElement ? document.documentElement.clientWidth : 0,
		document.body ? document.body.clientWidth : 0
	);
};

function f_clientHeight() {
	return f_filterResults (
		window.innerHeight ? window.innerHeight : 0,
		document.documentElement ? document.documentElement.clientHeight : 0,
		document.body ? document.body.clientHeight : 0
	);
};

function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
};

function scrollFix(){
	if($("mapCanvas")){
		$("mapCanvas").style.height = f_clientHeight()-140 + "px";
		$("mapCanvas").style.width = f_clientWidth()-340 + "px";
	}
};

function scrollFix_map(){
	if($("mapCanvas")){
		$("mapCanvas").style.height = f_clientHeight()-((mapData['numPhotos']) ? 280 : 200) + "px";
		$("mapCanvas").style.width = f_clientWidth()-340 + "px";
	}
};

function scrollFixIframe(){
	if($("mapCanvas")){
		$("mapCanvas").style.height = f_clientHeight() - 100 + "px";
	}
};

function getScroll(){
	if (document.documentElement && document.documentElement.scrollTop){
		theTop = document.documentElement.scrollTop;
	} else if (document.body){
		theTop = document.body.scrollTop
	} else{
		theTop = window.pageYOffset;
	}
	return theTop;
};

function addMarkerType(init){
	if(markerTypeCounterFirstRun == 0){
		markerTypeCounter = markerTypeCounter + init - 1;
		markerTypeCounterFirstRun = 1;
	}
	
	if(markerTypeCounter <= maxMarkerTypes){
		newdiv = document.createElement('div');
		newdiv.innerHTML = '<img src="' + theIcons[markerTypeCounter+1] +' " align="absmiddle" /><input type="text" name="markerTypes[]" style="width:88%" />';
		$("additionalMarkerTypes").appendChild(newdiv);
		
		if(markerTypeCounter == maxMarkerTypes-1){
			$("additionalMarkerTypesButton").style.display = "none";
		} 
		markerTypeCounter = markerTypeCounter+1;
	} else{
		addLayer(
			lang[30] + '. (' + maxMarkerTypes + ')<br><a href="javascript:removeOverlay();">' + lang[7] + '</a>',
			300,
			0
		);
	}
};

function validateLoginRegister(){
	if(e == "" || p == ""){
		return false;
	} else{
		return true;
	}
};

function loadLogin(e,c){
	if(!c) c = 0;
	addLayer(
		'<div class="att"><h2>' + lang[40] + '</h2>' + lang[38] + '</div><br>' + htmlText["loginForm"],
		300,
		c
	);
	if(e != undefined) $("loginEmail").value = e;
};

function doLogin(){
	a = "login";
	e = $("loginEmail").value;
	p = $("loginPassword").value;

	if(validateLoginRegister(e,p)){	
		addLayer(
			'<div class="wait">' + lang[34] + '</div>',
			300,
			1
		);
		
		function completeAjax(request){
			if(request.responseText == 1){
				newLoc = document.location.href.replace(/\?memberOnly=1/,"");
				document.location = newLoc + ((newLoc.indexOf("?") != -1) ? "&" : "?") + "justLoggedIn=1";
			} else{
				addLayer(
					'<div class="error"><h2>' + lang[40] + '</h2>' + lang[35] + '</div><br>' + htmlText["loginForm"],
					300,
					1
				);
				$("loginEmail").value = e;
			}
		}

		var req = new Ajax.Request(gatewayURL, {   
			method: 'post',   
			parameters: 'a=' + a + '&e=' + e + "&p=" + p,
			onComplete: completeAjax
		});
		
	} else{
		addLayer(
			'<div class="error">' + lang[63] + '<div id="markerWinAction"><a href="javascript:loadLogin(\'' + e + '\',1)">' + lang[65] + '</a></div></div>',
			300,
			1
		);
	}
};

function loadRegister(email,c){
	s = (userId == null) ? htmlText["registerForm"] : htmlText["updateAccountForm"];
	t = (userId == null) ? lang[41] : lang[46];
	b = (userId == null) ? lang[39] : lang[48];
	if(!c) c = 0;
	
	addLayer(
		'<div class="att"><h2>' + t + '</h2>' + b + '</div><br>' + s,
		300,
		c
	);
	
	if(email){
		$("registerEmail").value = e;
	} else if(userEmail != ""){
		$("registerEmail").value = userEmail;
		$("registerPassword").value = userPassword;
	} 
};

function doRegister(){
	a = (userId == null) ? "register" : "updateAccount";
	t = (userId == null) ? lang[41] : lang[46];
	e = $("registerEmail").value;
	p = $("registerPassword").value;
	
	if(validateLoginRegister(e,p)){
		addLayer(
			'<div class="wait">' + ((a == "updateAccount") ? lang[67] : lang[34]) + '</div>',
			300,
			1
		);
		
		function completeAjax(request){
			if(request.responseText == 1){
				newLoc = document.location.href.replace(/\?memberOnly=1/,"");
				if(a == "updateAccount"){
					document.location = newLoc + ((newLoc.indexOf("?") != -1) ? "&" : "?") + "justUpdated=1";
				} else{
					document.location = newLoc + ((newLoc.indexOf("?") != -1) ? "&" : "?") + "justRegistered=1";
				}
			} else if(request.responseText == 2){
				addLayer(
					'<div class="error"><h2>' + t + '</h2>' + lang[44] + '</div><br>' + htmlText["registerForm"],
					300,
					1
				);
				$("loginEmail").value = originalEmail;
			} else if(request.responseText == 3){
				addLayer(
					'<div class="error"><h2>' + t + '</h2>' + lang[45] + '</div><br>' + htmlText["registerForm"],
					300,
					1
				);
				$("loginEmail").value = e;
			}
		}
		
		var req = new Ajax.Request(gatewayURL, {   
			method: 'post',   
			parameters: 'a=' + a + '&e=' + e + "&p=" + p,
			onComplete: completeAjax
		});	
	} else{
		addLayer(
			'<div class="error">' + lang[64] + '<div id="markerWinAction"><a href="javascript:loadRegister(\'' + e + '\',1)">' + lang[65] + '</a></div></div>',
			300,
			1
		);
	}
};

function loadDeleteMap(){
	addLayer(
		'<div class="att"><h2>' + lang[86] + '</h2>' + lang[87] + ': \"' + mapData['name'] + '\" ?<div id="markerWinAction"><a href="javascript:doDeleteMap();">Yes</a> | <a href="javascript:removeOverlay();">No</a></div></div>',
		300,
		0
	);
};

function doDeleteMap(){
	
	function completeAjax(request){
		addLayer(
			'<div class="ok">' + lang[88] + '</div>',
			300,
			1
		);
		ot = setTimeout("document.location.href='/'",2000);
	}
		
	
	var req = new Ajax.Request(gatewayURL, {   
		method: 'post',   
		parameters: 'a=deleteMap&mapId=' + mapData['id'],
		onComplete: completeAjax
	});	
}

function addToSite(){
	thisUrl = document.location.href.replace(/\/maps\//,"/mymaps/");
	code = '&lt;iframe src=&quot;' + thisUrl + '&quot; width=&quot;400&quot; height=&quot;400&quot; align=&quot;left&quot; hspace=&quot;20&quot; scrolling=&quot;no&quot; style=&quot;border:0px;&quot; frameborder=&quot;#&quot;&gt;&lt;/iframe&gt;';
	addLayer(
		'<div class="att">' + lang[69] + "<textarea style='width:100%; height:100px;'>" + code + '</textarea><div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[7] + '</a></div></div>',
		300,
		0
	);
};

function copyURL(uType,langId){
	thisUrl = getURL(uType);
	addLayer(
		'<div class="att">' + lang[langId] + "<br><textarea style='width:100%; height:60px;' onFocus='this.select()'>" + thisUrl + '</textarea><div id="markerWinAction"><a href="javascript:removeOverlay();">' + lang[7] + '</a></div></div>',
		300,
		0
	);
};

function getURL(uType){
	thisUrl = "";
	if(uType == "marker"){
		thisUrl = "http://www.mapmotive.com/maps/" + mapData["identifier"] + "?" + 
		"la=" + map.getCenter().lat() +
		"&ln=" + map.getCenter().lng() +
		"&z="  + map.getZoom() +
		"&ma=" + linkToMarker;
	} else if(uType == "view"){
		thisUrl = "http://www.mapmotive.com/maps/" + mapData["identifier"] + "?" + 
		"la=" + map.getCenter().lat() +
		"&ln=" + map.getCenter().lng() +
		"&z="  + map.getZoom();
	} else if(uType == "page"){
		thisUrl = "http://www.mapmotive.com/maps/" + mapData["identifier"] + "/";
	}
	
	return thisUrl;
};

function remainingChar(obj,maxChar){
	return maxChar - obj.value.length; 
};

function fieldMaxChar(fieldObject,labelObj,maxChar){
	r = remainingChar(fieldObject,maxChar);
	if(r > 0){
		labelObj.innerHTML = remainingChar(fieldObject,maxChar) + ' ' + lang[76];
		labelObj.style.color = '#888888';
	} else{
		labelObj.innerHTML = lang[75];
		labelObj.style.color = 'red';
		fieldObject.value = fieldObject.value.substr(0,maxChar);
	}
};

function editMap(newMapName){
	$("mapInfoNormal").style.display = "none";
	$("mapInfoEdit").style.display = "";
	$('mapNameTitle').innerHTML = newMapName;
};

function url2Links(text) {
	var exp = /(\b(https?|ftp|file|www)(:\/\/)?[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
	return text.replace(exp,"<a href='http://$1'>$1</a>").replace("http://http://","http://"); 
};

function fb2(){
	thisUrl = getURL('marker');
	window.open('http://www.facebook.com/sharer.php?u=' + escape(thisUrl) + '&t=','Facebook','height=300,width=450');
};

function switchProvider(a){
	var b;
	var c;
	var d;
	
	$('panoramioOptions').style.display='none';
	$('flickrOptions').style.display='none';
	$('youtubeOptions').style.display='none';
	
	if(a == "getFlickr"){
		b = "flickrOptions";
		c = "flickrOptionsBut";
		d = "flickrUse";
		$('panoramioOptionsBut').style.borderBottom = '#999999 solid 1px';
		$('flickrOptionsBut').style.borderBottom = '#EFEFEF solid 1px';
		$('youtubeOptionsBut').style.borderBottom = '#999999 solid 1px';
		
		$('panoramioOptionsBut').style.backgroundColor = ($('panoramioUse').checked) ? '#EAFFD5' : '#CCCCCC';
		$('flickrOptionsBut').style.backgroundColor = ($('flickrUse').checked) ? '#C1FF84' : '#EFEFEF';
		$('youtubeOptionsBut').style.backgroundColor = ($('youtubeUse').checked) ? '#EAFFD5' : '#CCCCCC';
	} else if(a == "getPanoramio"){
		b = "panoramioOptions";
		c = "panoramioOptionsBut";
		d = "panoramioUse";
		$('panoramioOptionsBut').style.borderBottom = '#EFEFEF solid 1px';
		$('flickrOptionsBut').style.borderBottom = '#999999 solid 1px';
		$('youtubeOptionsBut').style.borderBottom = '#999999 solid 1px';
		
		$('panoramioOptionsBut').style.backgroundColor = ($('panoramioUse').checked) ? '#C1FF84' : '#EFEFEF';
		$('flickrOptionsBut').style.backgroundColor = ($('flickrUse').checked) ? '#EAFFD5' : '#CCCCCC';
		$('youtubeOptionsBut').style.backgroundColor = ($('youtubeUse').checked) ? '#EAFFD5' : '#CCCCCC';
	} else if(a == "getYoutube"){
		b = "youtubeOptions";
		c = "youtubeOptionsBut";
		d = "youtubeUse";
		$('panoramioOptionsBut').style.borderBottom = '#999999 solid 1px';
		$('flickrOptionsBut').style.borderBottom = '#999999 solid 1px';
		$('youtubeOptionsBut').style.borderBottom = '#EFEFEF solid 1px';
		
		$('panoramioOptionsBut').style.backgroundColor = ($('panoramioUse').checked) ? '#EAFFD5' : '#CCCCCC';
		$('flickrOptionsBut').style.backgroundColor = ($('flickrUse').checked) ? '#EAFFD5' : '#CCCCCC';
		$('youtubeOptionsBut').style.backgroundColor = ($('youtubeUse').checked) ? '#C1FF84' : '#EFEFEF';
	}

	$(b).style.display='';
	$(c).style.backgroundColor = ($(d).checked) ? '#C1FF84' : '#EFEFEF';
	$(c).style.borderBottom = ($(d).checked) ? '#C1FF84 solid 1px' : '#EFEFEF solid 1px';
	
	providerChooser = a;
}

function showHelp(h){
	var help = {};
	help["contextual"] = '<b>Contextual search option</b><br>When checked, only images and photos in the current view of the map will be returned. If not checked, it will search in the entire world.';
	help["alltags"] = '<b>Use all tags</b><br>When selected, only images and videos matching all these tags will be returned.  Separate tags with commas.';
	help["flickr"] = '<b>Link Account</b><br />Specify from which Flickr account to pull images from. Images in that account need to be set as public in Flickr.<br><br><b>Finding your Flickr Account ID</b><br />Use IDgettr (www.idgettr.com), all you need is the URL of your photo stream in Flickr.';
	help["panoramio"] = '<b>Link Account</b><br />Specify from which Panoramio account to pull images from. <br><br><b>Finding your Paqnoramio Account ID</b><br />Login to Panoramio. Follow the link (top right) to "your photos"; in the URL of this page, your user ID is http://www.panoramio.com/user/[ID HERE].';

	$("helpDiv").innerHTML = help[h];
	AssignPosition($('helpDiv'));
}


var cX = 0; var cY = 0; var rX = 0; var rY = 0;
function UpdateCursorPosition(e){
	cX = e.pageX; cY = e.pageY;
}
function UpdateCursorPositionDocAll(e){ 
	cX = event.clientX; cY = event.clientY;
}

if(document.all) { document.onmousemove = UpdateCursorPositionDocAll; }
else { document.onmousemove = UpdateCursorPosition; }

function AssignPosition(d) {
	if(self.pageYOffset) {
		rX = self.pageXOffset;
		rY = self.pageYOffset;
	} else if(document.documentElement && document.documentElement.scrollTop) {
		rX = document.documentElement.scrollLeft;
		rY = document.documentElement.scrollTop;
	} else if(document.body) {
		rX = document.body.scrollLeft;
		rY = document.body.scrollTop;
	}
	if(document.all) {
		cX += rX; 
		cY += rY;
	}
	d.style.left = (cX+10) + "px";
	d.style.top = (cY-10) + "px";
	d.style.display = "";
}

function constrain(str,n){ 
  if(str.length > n){  
    var s = str.substr(0, n);
    var words = s.split(' '); 
    words[words.length-1] = '';
    str = words.join(' ') + '&hellip;'
  }
	return str;
}

function shortenString(string, maxlen, del) {  	
	string = string.toString();	
	if (!del) { del='...' }	
	if (string.length > maxlen) {
		string = string.substr(0, maxlen) + del;     	
	}  	
	return string; 
}  

function addPhotosToRandomMap(){
	//find current
	var findIndex = 0;
	var allItems = [];
	var y = 0;
	var pType = ["flickr","panoramio"];
	var html = '';
	var t;
	
	pType.each(function(e){
		for(i in markers){
			if(i.indexOf(e) != -1){
				t = new GLatLng(markers[i].lat,markers[i].lng);
				t = t.distanceFrom(map.getCenter());
				allItems[y] = {};
				allItems[y].id = i;
				allItems[y].date = markers[i].date; 
				allItems[y].thumb = markers[i].thumb; 
				allItems[y].distCenter = t; 
				y = y + 1;
				//alert(markers[i].thumb);
			}
		}
	});

	function sortDate(a,b){
		return (a.date - b.date);
	}
	function sortDist(a,b){
		return (a.distCenter - b.distCenter);
	}
	allItems.sort(sortDist);
	
	y = 0;
	allItems.each(function(i){
		html = html + "<a target=\"_top\" href=\"" + $('mapLink').href + "\"><img onmouseover=\"quickView('" + i.id + "')\" onmouseout=\"$('mapCanvas').removeChild($('quickView"+i.id+"'));\" src=\"" + i.thumb + "\" border=\"0\" /></a>";
		y = y + 1;
		if(y > 10) $break;
	});
	
	$('mapPhotos').innerHTML = html;
	
}

function addPhotosToMap(){
	//find current
	var findIndex = 0;
	var allItems = [];
	var y = 0;
	var pType = [mapData["flickrs"],mapData["panoramios"]];
	var html = '';
	var t;
	
	pType.each(function(e){
		for(i in e){
			t = new GLatLng(markers[i].lat,markers[i].lng);
			t = t.distanceFrom(map.getCenter());
			
			//if(newMarker.lat() > mapData["mapNELat"] || newMarker.lat() < mapData["mapSWLat"] || newMarker.lng() < mapData["mapSWLng"] || newMarker.lng() > mapData["mapNELng"]){
				allItems[y] = {};
				allItems[y].id = i;
				allItems[y].date = markers[i].date; 
				allItems[y].thumb = markers[i].thumb; 
				allItems[y].distCenter = t; 
				y = y + 1;
				
				//alert(markers[i].thumb);
			//}
		}
	});

	function sortDate(a,b){
		return (a.date - b.date);
	}
	function sortDist(a,b){
		return (a.distCenter - b.distCenter);
	}
	allItems.sort(sortDist);
	
	h = 0;
	allItems.each(function(i){
		html = html + "<img onclick=\"openPhoto('" + i.id + "');\" onmouseover=\"quickView('" + i.id + "')\" onmouseout=\"$('mapCanvas').removeChild($('quickView"+i.id+"'));\" src=\"" + i.thumb + "\" border=\"0\" />";
		h = h +1;
		if(h > 15) $break;
	});
	
	$('mapPhotos').innerHTML = html;
	
}

