
// PoliticsWeb v3.0
// Copyright Michael Dent
// michael@politicsweb.co.uk

// 1. Menu
// 2. Ajax framework
// 3. Comments
// 4. Show/hide full post


// 1. Menu

function openMenu(id) {
	if (document.getElementById('sub-' + id).style.left == '') {
		document.getElementById('sub-' + id).style.left = findPosX(document.getElementById('menu-' + id)) + 'px';
	}
	document.getElementById('sub-' + id).style.display = 'block';
	document.getElementById('menu-' + id).classid += ' cur';
	if (typeof closetimer != 'undefined') {
		if (typeof lastopened != 'undefined') {
			if (lastopened == id) clearTimeout(closetimer);
		}
	}
	lastopened = id;
}

function closeMenu(id) {
	closetimer = setTimeout("document.getElementById('sub-" + id + "').style.display='';oldclass=document.getElementById('menu-" + id + "').classid;newclass=oldclass.replace(/cur/g,'');document.getElementById('menu-" + id + "').classid=newclass;", 100);
}

function findPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while(1) {
			curleft += obj.offsetLeft;
			if(!obj.offsetParent) break;
			obj = obj.offsetParent;
		}
	} else if (obj.x) {
		curleft += obj.x;
	}
	return curleft;
}


// 2. Ajax framework

function createAjax(page) {
	xmlHttp = ((window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP.3.0"));
	xmlHttp.open("POST", page, true);
	xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
}


// 3. Comments

function comments(reference) {
	el = document.getElementById(reference);
	el2 = document.getElementById('post-' + reference);
	if (el.style.display == 'block') {
		el.style.display = '';
		el2.style.display = '';
	} else {
		el.style.display = 'block';
		el2.style.display = 'block';
	}
}

function postComment(reference) {
	el = document.getElementById('post-' + reference);
	html  = '<form onsubmit="ajaxComment(\'' + reference + '\',document.getElementById(\'comment-name\').value,document.getElementById(\'comment\').value); return false;">';
	html += 'Name:<br /><input type="text" id="comment-name" /><br /><br />Comment:<br /><textarea id="comment"></textarea><br /><br />';
	html += '<input type="submit" value="Post comment" id="btn-post"></form>';
	el.innerHTML = html;
	document.getElementById('comment-name').focus();
}

function deleteComment(id) {
	createAjax("/calls/comment.php");
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			if (xmlHttp.responseText == 'success') {
				child = document.getElementById('comment-' + id);
				parent = child.parentNode;
				parent.removeChild(child);
			}
		}
	};
	vars = 'delete=' + id;
	xmlHttp.send(vars);
}

function ajaxComment(reference,name,comment) {
	document.getElementById('btn-post').disabled = true;
	createAjax("/calls/comment.php");
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			if (xmlHttp.responseText == 'success') {
				document.getElementById(reference).innerHTML += '<p>' + comment + '<br />- <strong>' + name + '</strong></p>';
				el = document.getElementById('post-' + reference);
				el.innerHTML = '<a href="javascript:postComment(\'' + reference + '\');">Post a comment</a>';
			} else if (xmlHttp.responseText == 'approval') {
				alert('Your comment has been received and saved, and will appear on the website shortly.');
				el = document.getElementById('post-' + reference);
				el.innerHTML = '<a href="javascript:postComment(\'' + reference + '\');">Post a comment</a>'
			} else if (xmlHttp.responseText == 'politicsweb') {
				alert('Please do not post a comment with a name containing \'PoliticsWeb\'.');
				el = document.getElementById('post-' + reference);
				el.innerHTML = '<a href="javascript:postComment(\'' + reference + '\');">Post a comment</a>'
			} else {
				alert(xmlHttp.responseText);
			}
		}
	};
	vars = 'url=' + window.location + '&reference=' + reference + '&name=' + name + '&comment=' + comment;
	xmlHttp.send(vars);
}


// 4. Show/hide full post

function fullPost(id) {
	document.getElementById('short-post-' + id).style.display = 'none';
	document.getElementById('full-post-' + id).style.display = 'block';
}

function shortPost(id) {
	document.getElementById('full-post-' + id).style.display = 'none';
	document.getElementById('short-post-' + id).style.display = 'block';
}


function pollVote(id) {
	document.getElementById('btn-vote').disabled = true;
	vote = -1;
	button = document.poll.choice;
	for (i=0; i < button.length; i++) {
		if (button[i].checked) vote = i+1;
	}
	email = document.getElementById('email').value;
	address = document.getElementById('address').value;
	if (vote == -1 || email == '' || address == '')  {
		alert('Please choose an option and fill out both fields');
		document.getElementById('btn-vote').disabled = false;
		return false;
	}
	createAjax("/calls/module.php?x=poll");
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			document.getElementById("poll").innerHTML = xmlHttp.responseText;
		}
	};
	vars = 'id=' + id + '&vote=' + vote + '&email=' + email + '&address=' + address;
	xmlHttp.send(vars);
}

function sendUserMap() {
	createAjax("/calls/module.php?x=map");
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			if (xmlHttp.responseText == 'success') {
				window.location.reload();
			} else if (xmlHttp.responseText == 'approval') {
				alert('Your map post has been received and saved, and will appear on the website shortly.');
				window.location.reload();
			} else {
				alert(xmlHttp.responseText);
			}
		}
	};
	els = document.getElementById('add-issue').elements;
	vars = '';
	for (var i = 0; i < els.length; i++) {
		if (els[i].name != '') vars += els[i].name + "=" + els[i].value + '&';
	}
	vars = vars.slice(0,(vars.length-1)); 
	xmlHttp.send(vars);
}

function deleteMapPost(id) {
	createAjax("/calls/module.php?x=map");
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			if (xmlHttp.responseText == 'success') {
				window.location.reload();
			}
		}
	};
	vars = 'delete=' + id;
	xmlHttp.send(vars);
}

function setIcons() {
	icons = new Array();
	icons['blue-marker'] = new GIcon();
	icons['blue-marker'].image = "/images/marker.png";
	icons['blue-marker'].iconSize = new GSize(20, 34);
	icons['blue-marker'].iconAnchor = new GPoint(9, 34);
	icons['red-exclamation'] = new GIcon();
	icons['red-exclamation'].image = "/images/exclamation.png";
	icons['red-exclamation'].iconSize = new GSize(32, 32);
	icons['red-exclamation'].iconAnchor = new GPoint(9, 34);
}

function addMarker() {
	window.onmousemove = mouseFollower;
	document.getElementById("add-marker-img").style.opacity = '0.3';
	document.getElementById("add-marker-img").style.filter = 'alpha(opacity=30)';
	img = new Image();
	img.src = '/images/marker-ticked.png';
	GEvent.addListener(gmap, "click", function(overlay, latlng) {
		if (document.getElementById("location").value == '') {
			markericon = icons['blue-marker'];
			mymarker = new GMarker(latlng,markericon);
			gmap.addOverlay(mymarker);
			document.getElementById('mouse-follower').style.display = '';
			window.onmousemove = '';
			document.getElementById("location").value = latlng;
			document.getElementById("add-marker-img").onclick = '';
			document.getElementById("add-marker-img").src = '/images/marker-ticked.png';
			document.getElementById("add-marker-img").style.opacity = '';
			document.getElementById("add-marker-img").style.filter = '';
		}
	});
}

function addMarkerAdmin() {
	div = document.getElementById('map');
	div.style.position = 'absolute';
	div.style.top = '0';
	div.style.left = '0';
	div.style.width = '100%';
	div.style.height = '500px';
	div.style.zIndex = '8';
	document.getElementById('icon').style.visibility = 'hidden';
	load();
	window.onmousemove = mouseFollower;
	document.getElementById("add-marker-img").style.opacity = '0.3';
	document.getElementById("add-marker-img").style.filter = 'alpha(opacity=30)';
	img = new Image();
	img.src = '/images/marker-ticked.png';
	GEvent.addListener(gmap, "click", function(overlay, latlng) {
		if (document.getElementById("location").value == '') {
			markericon = icons['blue-marker'];
			mymarker = new GMarker(latlng,markericon);
			gmap.addOverlay(mymarker);
			document.getElementById('mouse-follower').style.display = '';
			window.onmousemove = '';
			document.getElementById("location").value = latlng;
			document.getElementById("add-marker-img").onclick = '';
			document.getElementById("add-marker-img").src = '/images/marker-ticked.png';
			document.getElementById("add-marker-img").style.opacity = '';
			document.getElementById("add-marker-img").style.filter = '';
			setTimeout("document.getElementById('map').style.display = 'none';",500);
			setTimeout("document.getElementById('icon').style.visibility = '';",500);
		}
	});
}


function createMarker(lat,lng,id,icon) {
	latlng = new GLatLng(lat,lng);
	markericon = icons[icon];
	mymarker = new GMarker(latlng,markericon);
	GEvent.addListener(mymarker, "click", function() {
		window.location.href = '#' + id;
		document.getElementById('map-post-' + id).style.backgroundColor = '#fffde5';
		setTimeout("document.getElementById('map-post-" + id + "').style.backgroundColor = ''",800);
	});
	gmap.addOverlay(mymarker);
}

function mouseFollower(e) {
	document.getElementById('mouse-follower').style.display = 'block';
	img = document.getElementById('mouse-follower');
	var mouseX = 0;
	var mouseY = 0;
	if (!e) var e = window.event;
	if (e.pageX || e.pageY) 	{
		mouseX = e.pageX;
		mouseY = e.pageY;
	}
	else if (e.clientX || e.clientY) 	{
		mouseX = e.clientX + document.body.scrollLeft
			+ document.documentElement.scrollLeft;
		mouseY = e.clientY + document.body.scrollTop
			+ document.documentElement.scrollTop;
	}
	mouseX -= 10;
	mouseY -= 34;
	img.style.left = mouseX + 'px';
	img.style.top = mouseY + 'px';
}



function populateTags() {
	document.getElementById('tags').innerHTML = '';
	tags = document.getElementById('param1').value.split('/');
	for (i=0; i<tags.length; i++) {
		parts = tags[i].split('###');
		if (parts[1] != null) {
			display = parts[0] + ' (' + parts[1] + ')';
		} else {
			display = parts[0];
		}
		if (display != '') document.getElementById('tags').innerHTML += '<div>' + display + '<a href="javascript:deleteTag(' + i + ');"><img src="http://files.politicsweb.co.uk/icn-delete.png" /></a></div><br />';
	}
}

function deleteTag(num) {
	tags = document.getElementById('param1').value.split('/');
	tags.splice(num,1);
	if (tags[0] == '') tags.splice(0,1);
	tags = tags.join('/');
	document.getElementById('param1').value = tags;
	populateTags();
}

function addTag() {
	loadPopup('<form onsubmit="doAddTag();return false;"><p>Tag:<br /><input type="text" id="add-tag" /></p><p>Label (optional):<br /><input type="text" id="add-tag-label" /></p><p><input type="submit" value="Add tag" /></p></form>');
	stylePopup(218,165);
	document.getElementById('add-tag').focus();
}

function doAddTag() {
	toAdd = document.getElementById('add-tag').value;
	if (document.getElementById('add-tag-label').value != '') toAdd += '###' + document.getElementById('add-tag-label').value;
	tags = document.getElementById('param1').value.split('/');
	tags.push(toAdd);
	if (tags[0] == '') tags.splice(0,1);
	tags = tags.join('/');
	document.getElementById('param1').value = tags;
	populateTags();
	closePopup();
}





function submitForm() {
	createAjax("/calls/module.php?x=form");
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			if (xmlHttp.responseText == 'success') {
				document.getElementById('page-form').innerHTML = '<p><strong>Thank you giving us your information - we have received your message and will be in touch shortly.</strong></p>'; 
			} else {
				document.getElementById('page-form').innerHTML = xmlHttp.responseText;
			}
		}
	};
	els = document.getElementById('page-form').elements;
	fields = [];
	for (i=0;i<els.length;i++) {
		if (els[i].type == 'checkbox') {
			if (els[i].checked) {
				existed = false;
				for (j=0;j<fields.length;j++) {
					if (fields[j][0] == els[i].name) {
						value = fields[j][1];
						value = value.slice(0,(value.length-2)); 
						value += ',' + els[i].value + '}}';
						fields[j][1] = value;
						existed = true;
					}
				}
				if (!existed) {
					fields.push([els[i].name,'{{'+els[i].value+'}}']);
				}
			}
		} else {
			fields.push([els[i].name,els[i].value]);
		}
	}
	vars = '';
	for (i=0;i<fields.length;i++) {
		vars += fields[i][0] + '=' + fields[i][1] + '&';
	}
	vars = vars.slice(0,(vars.length-1)); 
	xmlHttp.send(vars);
}