var totalMessages = 0;
var lastQuoteLinkBlock = true;
var selection = '';

function QuoteText(num)
{
	if (selection == '')
	{
		selection = false;
	}
	if (!selection && num == totalMessages && lastQuoteLinkBlock)
	{
		document.getElementById('message_li_' + num).innerHTML += '<br /><br /><span class="sm" style="color: #990000">' + _text['QUOTE_MSG'] + '</span>';
		lastQuoteLinkBlock = false;
		return true;
	}
	if (!selection)
	{
		var mText = document.getElementById('message_text_' + num).innerHTML;
		mText = mText.replace(/<\/?em[^>]*>/ig, '').replace(/<\/?u>/ig, '').replace(/<\/?a[^>]*>/ig, '').replace(/<\/?span[^>]*>/ig, '');
		mText = mText.replace(/&gt;/ig, '>').replace(/&lt;/ig, '<').replace(/&quote;/ig, '"').replace(/&amp;/ig, '&');
		var mTextArray = mText.split(/<br\s*\/?>\s*/i);
	}
	else
	{
		var mTextArray = selection.toString().split('\n');
		for (var i = 0; i < mTextArray.length; ++i)
		{
			mTextArray[i] = mTextArray[i].replace(/\r/g, '');
		}
	}
	var mText2 = '';
	for (var i = 0; i < mTextArray.length; ++i)
	{
		mText2 += '> ' + mTextArray[i] + '\r\n';
	}
	if (document.f1.x9ett)
	{
		var insertText = 'Цитата (' + document.getElementById('message_author_' + num).innerHTML + ', ' + document.getElementById('message_date_' + num).innerHTML + '):\r\n' + mText2 + '\r\n';
		if (document.f1.x9ett.value == '')
		{
			document.f1.x9ett.value = insertText;
		}
		else
		{
			document.f1.x9ett.value += '\r\n' + insertText;
		}
		document.f1.x9ett.focus();
	}
}

function catchSelection()
{
	if (document.getSelection)
	{
		selection = document.getSelection();
	}
	else if (window.getSelection)
	{
		selection = window.getSelection().toString();
	}
	else if (document.selection)
	{
		selection = document.selection.createRange().text;
	}
}

function vote(pid, val)
{
	if (val != 0 && val != 1)
	{
		alert('Hacking attempt detected.');
		return;
	}

	$('rating').className = 'loading';

	JsHttpRequest.query(
		'/ajax.php?ajax-action=photo-vote',
		{ 'pid' : pid, 'val' : val, 'type' : 'b' },
		function (result, errors)
		{
			if (errors) alert('Error catched: \n' + errors);
			if (result)
			{
				var divs, signs, txt = '', cnt, rating = 0;
				divs = new Array('votes_pro', 'votes_con');
				signs = new Array('+', '&ndash;');

				for (var i = 0; i < 2; i++)
				{
					if (result[i] && result[i].length != 0)
					{
						txt += '<div style="padding:3px 5px" class="s' + (i == 0 ? 2 : 5) + '">';

						for (aid in result[i])
						{
							txt += '[' + signs[i] + '] <a style="color:black" href="http://fotobus.msk.ru/author/' + aid + '/">' + result[i][aid] + '</a><br />';

							if (i == 0)
								 rating++;
							else rating--;
						}

						txt += '</div><br />';
					}
				}

				$('votes').innerHTML = txt;

				if (rating > 0) $('rating').innerHTML = '+' + rating; else
				if (rating < 0) $('rating').innerHTML = '&ndash;' + parseInt(-rating);
						   else $('rating').innerHTML = '0';

				$('b1').className = (result[2][1] == 1) ? '' : 's2';
    			$('b0').className = (result[2][0] == 1) ? '' : 's5';
			}
			else $('b'+val).className = '';

			$('b1').value = _text['VOTE_B1'];
			$('b0').value = _text['VOTE_B0'];

			$('rating').className = '';
		},
		true
	);
}


function vote_auth(pid, pro)
{
	if (pro != 0 && pro != 1) return false;

	var cls1 = $('k1_'+pid).className;
	var cls0 = $('k0_'+pid).className;

	var press_btn = $('k'+pro+'_'+pid);
	var other_btn = $('k'+Number(!pro)+'_'+pid);

	press_btn.className = (press_btn.className == 'voted_press') ? 'vote_k'+pro : 'voted_press';
	other_btn.className = 'vote_k'+Number(!pro);

	$('loader'+pid).style.display = 'inline';

	JsHttpRequest.query(
		'/ajax.php?ajax-action=auth-vote',
		{ 'pid' : pid, 'pro' : pro },
		function (result, errors)
		{
			if (errors) alert(errors);
			if (result)
			{
				if (result[0] != '')
					 $('star'+pid).innerHTML = '<img src="/img/star_' + result[0] + '.png" alt="" />';
				else $('star'+pid).innerHTML = '';
			}

			$('k1_'+pid).className = result ? (result[1][1] ? 'voted' : 'vote_k1') : cls1;
			$('k0_'+pid).className = result ? (result[1][0] ? 'voted' : 'vote_k0') : cls0;

			hideId('loader'+pid);
		},
		true
	);

	return false;
}


var map, k = 0, markers = new Array();


function showInfoWindow(html)
{
	$('pfm').innerHTML = html;
	$('pfm_frame').style.display = 'block';
}


function hideInfoWindow()
{
	if ($('pfm_frame') && $('pfm_frame').style.display != 'none')
	{
		$('pfm_frame').style.display = 'none';
		$('pfm').innerHTML = '';
	}
}


function initialize()
{
	var center = new google.maps.LatLng(lat, lng);
	var myOptions = {
		zoom: 14,
		center: center,
		mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
		mapTypeId: google.maps.MapTypeId.HYBRID,
		scrollwheel: false,
		streetViewControl: false
	}

	map = new google.maps.Map(document.getElementById('map_canvas'), myOptions);

	google.maps.event.addListener(
		map,
		'dragend',
		function() { refreshMarkers(); }
	);

	google.maps.event.addListener(
		map,
		'zoom_changed',
		function() { refreshMarkers(); }
	);

	google.maps.event.addListenerOnce(
		map,
		'bounds_changed',
		function() { refreshMarkers(); }
	);

	addCenterphotoMarker();
}

function addMarker(i, z)
{
	var center = new google.maps.LatLng(z['lat'], z['lng']);

	markers[i] = new google.maps.Marker({
		position: center,
		map: map,
		icon: '/img/foto_'+z['heading']+'.png'
	});

	google.maps.event.addListener(
		markers[i],
		'click',
		function()
		{
			JsHttpRequest.query(
				'/ajax.php?ajax-action=get-photo-data',
				{ 'pid' : z['pid'] },
				function (result, errors)
				{
					if (errors) showInfoWindow(errors);
					if (result) showInfoWindow(result);
				},
			false);
		}
	);
}

function addCenterphotoMarker()
{
	var center = new google.maps.LatLng(lat, lng);

	var marker = new google.maps.Marker({
		position: center,
		map:map,
		icon: '/img/foto_'+heading+'.png'
	});

	google.maps.event.addListener(
		marker,
		'click',
		function() { showInfoWindow('<b>'+_text['P_CURRENT']+'</b>'); }
	);

	var markicon = new google.maps.MarkerImage(
		'/img/central_mark.png',
		new google.maps.Size(16, 16),
		new google.maps.Point(0, 0),
		new google.maps.Point(8, 8)
	);

	var centerRedMark = new google.maps.Marker({
		position: center,
		map: map,
		icon: markicon,
		zIndex: marker.getZIndex()-1
	});
}


function refreshMarkers()
{
	var bounds = map.getBounds();
	var southWest = bounds.getSouthWest();
	var northEast = bounds.getNorthEast();

	JsHttpRequest.query(
		'/ajax.php?ajax-action=get-photos-around',
		{
			'pid': pid,
			'NElat': northEast.lat(),
			'NElng': northEast.lng(),
			'SWlat': southWest.lat(),
			'SWlng': southWest.lng()
		},
		function (result, errors)
		{
			k++;
			if (errors)
			{
				$('pfm').innerHTML = errors;
				$('pfm').style.display = 'block';
			}

   			if (result)
			{
				for (var i = 0; i < markers.length; i++)
					markers[i].setMap(null);
				markers.length = 0;

				for (var i = 0; i < result.length; i++)
					addMarker(i, result[i]);
			}
		},
		false
	);
}

document.onclick = function(e)
{
	e = e || window.event;
	E = e.target || e.srcElement;
	if (E.id != 'pfm' && E.parentNode.id != 'pfm' && E.parentNode.parentNode.parentNode.parentNode.id != 'map_canvas')
		hideInfoWindow();
}

function showMap()
{
	$('map').style.display = 'block';
	$('showmap').style.display = 'none';
	initialize();
}


