
// PoliticsWeb v4.0
// Copyright Michael Dent
// www.politicsweb.co.uk

// 1. Menu
// 2. Ajax framework
// 3. Comments
// 4. Show/hide full post
// 5. Lookup postcode
// 6. General


// 1. Menu

$(function() {
	var disappear;
	$('#menu a')
		.mouseover(function () {
			clearTimeout(disappear);
			menuId = $(this).attr('id');
			submenu = menuId.replace('menu','sub');
			$('.submenu').css('display', 'none');
			$('#' + submenu).css('display', 'block');
			position = $('#' + menuId).position();
			$('#' + submenu).css('left',position.left);
		})
		.mouseout(function () {
			menuId = $(this).attr('id');
			submenu = menuId.replace('menu','sub');
			disappear = setTimeout(function () { $('#' + submenu).css('display', 'none'); },400);
		});
	$('.submenu')
		.mouseover(function () { 
			submenu = $(this).attr('id');
			menuId = submenu.replace('sub','menu');
			$('#' + menuId).trigger('mouseover');
		})
		.mouseout(function () {
			submenu = $(this).attr('id');
			menuId = submenu.replace('sub','menu');
			$('#' + menuId).trigger('mouseout');
		});
});


// 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,details) {
	el = document.getElementById('post-' + reference);
	html  = '<form onsubmit="ajaxComment(\'' + reference + '\',\'' + details + '\'); return false;">';
	prefill = '';
	if (isAdmin) prefill = siteTitle;
	html += 'Name:<br /><input type="text" id="comment-name" value="' + prefill + '" /><br /><br />Comment:<br /><textarea id="comment"></textarea><br /><br />';
	if (userEmailAuthentication) {
		html += 'Email (not public):<br /><input type="text" id="comment-email" /><br /><br />';
	} else {
		html += '<input type="hidden" id="comment-email" value="n/a" />';
	}
	if (userPostcodeLookup) {
		html += 'Postcode (not public):<br /><input type="text" id="comment-postcode" /><br /><br />';
	} else {
		html += '<input type="hidden" id="comment-postcode" value="n/a" />';
	}
	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,details) {
	theReference = reference;
	theDetails = details;
	if (userPostcodeLookup) {
		lookupPostcode(document.getElementById('comment-postcode').value,'commentConstituencyReceived');
	} else {
		doAjaxComment();
	}
}

function commentConstituencyReceived(r) {
	document.getElementById('comment-postcode').value = r.name;
	doAjaxComment();
}

function doAjaxComment() {
	reference = theReference;
	details = theDetails;
	name = document.getElementById('comment-name').value;
	comment = document.getElementById('comment').value;
	email = document.getElementById('comment-email').value;
	postcode = document.getElementById('comment-postcode').value;
	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 + '\',\'' + details + '\');">Post a comment</a>';
			} else if (xmlHttp.responseText == 'approval') {
				alert('Your comment has been received and saved, and will appear on the website shortly subject to approval.');
				el = document.getElementById('post-' + reference);
				el.innerHTML = '<a href="javascript:postComment(\'' + reference + '\',\'' + details + '\');">Post a comment</a>'
			} else if (xmlHttp.responseText == 'email') {
				alert('Thank you for your comment. Please click the link in your email to confirm your email address.');
				el = document.getElementById('post-' + reference);
				el.innerHTML = '<a href="javascript:postComment(\'' + reference + '\',\'' + details + '\');">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 + '\',\'' + details + '\');">Post a comment</a>'
			} else if (xmlHttp.responseText == 'sitetitle') {
				alert('Please do not post a comment with a name containing \'' + siteTitle + '\'.');
				el = document.getElementById('post-' + reference);
				el.innerHTML = '<a href="javascript:postComment(\'' + reference + '\',\'' + details + '\');">Post a comment</a>'
			} else {
				alert(xmlHttp.responseText);
			}
		}
	};
	comment = comment.replace('&','###');
	vars = 'url=' + window.location + '&reference=' + reference + '&details=' + details + '&name=' + name + '&comment=' + comment + '&email=' + email + '&postcode=' + postcode;
	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';
}


// 5. Lookup postcode

function lookupPostcode(pc,callback) {
	var s = document.createElement('script');
	var url = 'http://www.theyworkforyou.com/api/getConstituency?key=BXJpE7BgtQM6DXMS84C2eGDn&callback=' + callback + '&postcode=' + pc;
	s.setAttribute('src', url);
	s.setAttribute('type', 'text/javascript');
	document.getElementsByTagName('head')[0].appendChild(s);
}


// 6. General

function isNumeric(input) {
	return (input - 0) == input && input.length > 0;
}


function submitForm(formid) {
	theFormId = formid;
	if (userPostcodeLookup && document.getElementById('postcode_lookup') != undefined) {
		els = document.getElementById('form'+formid).elements;
		for (i=0;i<els.length;i++) {
			if (els[i].name == 'field' + document.getElementById('postcode_lookup').value) {
				pc = els[i].value;
			}
		}
		lookupPostcode(pc,'formConstituencyReceived');
	} else {
		doSubmitForm();
	}
}

function formConstituencyReceived(r) {
	document.getElementById('postcode_lookup').value = r.name;
	doSubmitForm();
}

function doSubmitForm() {
	formid = theFormId;
	createAjax("/calls/module.php?x=form");
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			responseText = xmlHttp.responseText;
			if (responseText == 'security') {
				alert('Sorry, you filled the security form out incorrectly. Please check your answer and try again.');
			} else if (responseText == 'verify') {
				alert('As this is your first submission on this website, we\'ve sent a confirmation email to your email address.\n\nPlease click the link in that email, and then return to this page and resubmit this form.');
			} else if (responseText.substr(0,13) == 'JAVASCRIPT---') {
				responseText = responseText.replace('JAVASCRIPT---','');
				eval(responseText);
			} else {
				thisForm.innerHTML = responseText;
			}
		}
	};
	thisForm = document.getElementById('form'+formid);
	els = thisForm.elements;
	fields = [];
	for (i=0;i<els.length;i++) {
		if (els[i].name != 'postcode_lookup') {
			if (els[i].type == 'checkbox' || els[i].type == 'radio') {
				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 {
				theClass = els[i].className;
				if (els[i].value == '' && theClass.indexOf('required') != -1) {
					alert('Please fill in all required fields');
					els[i].focus();
					return false;
				}
				fields.push([els[i].name,els[i].value]);
			}
		}
	}
	vars = '';
	for (i=0;i<fields.length;i++) {
		vars += fields[i][0] + '=' + encodeURIComponent(fields[i][1]) + '&';
	}
	if (userPostcodeLookup && document.getElementById('postcode_lookup') != undefined) vars += 'postcode_lookup=' + document.getElementById('postcode_lookup').value + '&';
	vars = vars.slice(0,(vars.length-1)); 
	xmlHttp.send(vars);
}

function renameField(fieldName,fieldId) {
	loadPopup('<form onsubmit="doRenameField(\'' + fieldId + '\');return false;"><p>Rename field <strong>' + fieldName + '</strong>:</p><p><input type="text" value="' + fieldName + '" id="rename-field" /></p><p><input type="submit" value="Rename field" /></p></form>');
	stylePopup(220,123);
	document.getElementById('rename-field').select();
}

function doRenameField(fieldId) {
	newName = document.getElementById('rename-field').value;
	if (newName != null) {
		loadPopup('<p id="loading"><img src="http://files.politicsweb.co.uk/loading.gif" /></p>');
		stylePopup(50,50);
		createAjax("/calls/module.php?x=form");
		xmlHttp.onreadystatechange = function() {
			if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
				closePopup();
				window.location.reload();
			}
		};
		xmlHttp.send('rename-field=' + newName + '&field=' + fieldId);
	}
}

function editOptions(fieldId,fieldName,options) {
	loadPopup('<form onsubmit="doEditOptions(\'' + fieldId + '\');return false;"><p>Edit options for <strong>' + fieldName + '</strong> (put each option on a new line):</p><p><textarea id="edit-options" style="width:350px;height:200px;">' + options.replace(/,/g,'\n') + '</textarea></p><p><input type="submit" value="Update" /></p></form>');
	stylePopup(390,300);
	document.getElementById('edit-options').focus();
}

function doEditOptions(fieldId) {
	newOptions = document.getElementById('edit-options').value;
	loadPopup('<p id="loading"><img src="http://files.politicsweb.co.uk/loading.gif" /></p>');
	stylePopup(50,50);
	createAjax("/calls/module.php?x=form");
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			closePopup();
			window.location.reload();
		}
	};
	xmlHttp.send('edit-options=' + newOptions + '&field=' + fieldId);
}

if (typeof($) != 'undefined') {
	$(function () {
		$('.pw_interface').each(function () { parseInterfaceData($(this)); });
	})
}

function pollVote(id) {
	thePollId = id;
	if (document.getElementById('check_constituency').value != '') {
		lookupPostcode(document.getElementById('postcode').value,'pollConstituencyReceived');
	} else {
		doPollVote();
	}
}

function pollConstituencyReceived(r) {
	if (r.name == document.getElementById('check_constituency').value) {
		doPollVote();
	} else {
		alert('Sorry, we can only accept votes from postcodes in the ' + document.getElementById('check_constituency').value + ' constituency');
	}
}

function doPollVote() {
	id = thePollId;
	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 createFader() {	
	jQuery(function() {
		var fadeCounter = 0;
		var div = jQuery('.imagefader');
		
		if (typeof(fadeOptions.dimensions) != 'undefined') 
			div.css({ 'width': fadeOptions.dimensions[0], 'height': fadeOptions.dimensions[1] })
		
		for (var i = 0; i < fadeOptions.imagearray.length; i++) 
		{
			var img = jQuery('<a></a>')
				.attr('id', 'fadeimage-' + i)
				.addClass('fadeimage')
				.css({ 'width': div.width(), 'height': div.height() })
				.css('background-image', 'url(' + fadeOptions.imagearray[i][0] + ')');
				
			if (fadeOptions.imagearray[i][1] != null && fadeOptions.imagearray[i][1] != '') 
			{
				var txt = jQuery('<div></div>')
					.html(fadeOptions.imagearray[i][1])
					.css({ 'opacity': 0.7, 'width': div.width() - 8 })
					.addClass('fadetext');
				img.append(txt);
			}
			
			if (fadeOptions.imagearray[i][2] != null && fadeOptions.imagearray[i][2] != '') img.attr('href', fadeOptions.imagearray[i][2]);
			
			div.append(img);
		}
		
		loadImage();
		setInterval(loadImage, fadeOptions.pause);
		
		function loadImage() 
		{
			div.children('.fadeimage').eq(fadeCounter++ % fadeOptions.imagearray.length)
				.stop()
				.css({ 'display': 'none', 'z-index': fadeCounter })
				.fadeIn(fadeOptions.fade);
		}
	});
}

function editCaption(i) {
	$('#submit-'+i).css('display', 'inline');
	$('#caption-'+i).css('border', '1px solid #cccccc');
	$('#caption-'+i).prop('readonly', false);
	$('#link-'+i).css('border', '1px solid #cccccc');
	$('#link-'+i).prop('readonly', false);
	
	$('#caption-'+i).focus();
}

function sendPayPalForm() {
	
	var frm = document.getElementById('paypal-form');
	var els = frm.elements;
	var vars = '';
	
	if (document.getElementById('a3-other').checked && (document.getElementById('a3-other-value') == '' || isNumeric(document.getElementById('a3-other-value')) == false)) {
		alert('Please enter a valid subscription amount');
		document.getElementById('a3-other-value').focus();
		return false;
	}
	
	if (document.getElementById('validate-form').value == 'yes') {
		
		for (i=0;i<els.length;i++) {
			if (els[i].name != '') {
				if (els[i].value == '' && els[i].name != 'company' && els[i].name != 'amount' && els[i].name != 'invoice') {
					alert('Please ensure that all fields are filled in');
					return false;
				}
				if (els[i].type == 'radio') {
					if (els[i].checked == true) vars += els[i].name + "=" + els[i].value + '&';
				} else {
					if (els[i].name != '') vars += els[i].name + "=" + els[i].value + '&';
				}
			}
		}
		
		createAjax("/calls/module.php?x=paypal");
		xmlHttp.onreadystatechange=function() {
			if (xmlHttp.readyState==4 && xmlHttp.status==200) {
				document.getElementById('paypal-form-invoice').value = xmlHttp.responseText;
				frm.submit();
			}
		}
		
		vars = vars.slice(0,(vars.length-1)); 
		xmlHttp.send(vars);
		document.getElementById('paypal-started').innerHTML = '<p><em>Please wait...</em></p>';
		document.getElementById('paypal-started').style.display = 'block';
		document.getElementById('paypal-form').style.visibility = 'hidden';
		return false;
	
	}
	
}

function updateAmount(amount) {
	document.getElementById('paypal-amount').value = amount;
}

if (typeof($) != 'undefined') {
	$(function () {
		$('.pw_interface').each(function () { parseInterfaceData($(this)); });
	})
}



function seeOlder(content,show,increment,more) {
	createAjax("/calls/module.php?x=downloads");
	more = more-increment;
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			document.getElementById('see-older').innerHTML = xmlHttp.responseText;
			document.getElementById('see-older-link').href = 'javascript:seeOlder(' + content + ',' + newshow + ',' + increment + ',' + more + ');';
			seeOlderLink = document.getElementById('see-older-link').innerHTML;
			oldMore = more+increment;
			seeOlderLink = seeOlderLink.replace('(' + oldMore + ' more)','(' + more + ' more)');
			document.getElementById('see-older-link').innerHTML = seeOlderLink;
			document.getElementById('see-older-link').style.display = '';
			document.getElementById('see-older-loading').style.display = '';
			if (more < 1) document.getElementById('see-older-link').style.display = 'none';
		}
	};
	xmlHttp.send('content=' + content + '&show=' + show + '&initial=' + increment);
	newshow = show+increment;
	document.getElementById('see-older-link').style.display = 'none';
	document.getElementById('see-older-loading').style.display = 'block';
}

priceAdult = new Array();
priceConcession = new Array();
priceChild = new Array();

function buyTickets(id) {
	document.getElementById('choose-tickets-'+id).style.display = 'block';
	document.getElementById('total-price-'+id).style.display = 'block';
	document.getElementById('buy-button-'+id).style.display = 'block';
}

function addTicket(id,type) {
	document.getElementById('tickets_'+type+'_'+id).innerHTML++;
	recalculateTotal(id);
}

function subtractTicket(id,type) {
	if (document.getElementById('tickets_'+type+'_'+id).innerHTML > 0) {
		document.getElementById('tickets_'+type+'_'+id).innerHTML--;
		recalculateTotal(id);
	}
}

function recalculateTotal(id) {
	totalPrice = document.getElementById('tickets_adult_'+id).innerHTML * priceAdult[id];
	if (priceChild[id] != 0) totalPrice += document.getElementById('tickets_child_'+id).innerHTML * priceChild[id];
	if (priceConcession[id] != 0) totalPrice += document.getElementById('tickets_concession_'+id).innerHTML * priceConcession[id];
	document.getElementById('total-price-'+id).innerHTML = 'Total: <span>&pound;' + totalPrice + '</span>';	
	
}

function showPayPal(id) {
	document.getElementById('choose-tickets-'+id).style.display = '';
	document.getElementById('buy-button-'+id).style.display = '';
	document.getElementById('events-paypal-form-'+id).style.display = 'block';
	document.getElementById('paypal-amount-'+id).value = totalPrice;
	description = document.getElementById('tickets_adult_'+id).innerHTML + ' adult ticket(s)';
	if (priceChild[id] != 0) description += ', ' + document.getElementById('tickets_child_'+id).innerHTML + ' child ticket(s)';
	if (priceConcession[id] != 0) description += ', ' + document.getElementById('tickets_concession_'+id).innerHTML + ' concession ticket(s)';
	document.getElementById('paypal-description-'+id).value = description;
}

function sendEventsPayPalForm() {
	createAjax("/calls/module.php?x=events");
	els = document.getElementById('events-paypal-form').elements;
	vars = '';
	for (var i = 0; i < els.length; i++) {
		if (els[i].value == '') {
			alert('Please ensure that all fields are filled in');
			return false;
		}
		if (els[i].name != '') vars += els[i].name + "=" + els[i].value + '&';
	}
	vars = vars.slice(0,(vars.length-1)); 
	vars += '&tickets=' + description;
	xmlHttp.send(vars);
	return true;
}

function newsletterSubscribe() {
	createAjax("/calls/module.php?x=newsletter");
	xmlHttp.onreadystatechange = function() {
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			if (xmlHttp.responseText == 'success') {
				document.getElementById('newsletter-subscribe').innerHTML = '<strong>Thank you!</strong> You have been successfully subscribed to the newsletter.';
			} else {
				alert(xmlHttp.responseText);
			}
		}
	};
	els = document.getElementById('newsletter-subscribe').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 unsubscribePerson(id) {
	createAjax("/calls/module.php?x=newsletter");
	xmlHttp.onreadystatechange = function() { 
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
			document.getElementById('p' + xmlHttp.responseText).parentNode.removeChild(document.getElementById('p' + xmlHttp.responseText));
		}
	};
	vars = 'delete=' + id;
	xmlHttp.send(vars);
}

function startSend() {
	emailsRemaining = totalEmails;
	readyToFinish = false;
	document.getElementById('send-newsletter-button').style.display = 'none';
	document.getElementById('sending-newsletter').style.display = 'block';
	sendMessage(1);
}

function sendMessage(sendNum) {
	if (emailsRemaining == 0) readyToFinish = true;
	updateRemaining();
	createAjax("/calls/module.php?x=newsletter");
	xmlHttp.onreadystatechange = function() { 
		if (xmlHttp.readyState == 4 && xmlHttp.status == 200 && readyToFinish) sendingComplete();
	};
	markAsSent = (readyToFinish && (document.getElementById('move-to-sent') == undefined || document.getElementById('move-to-sent').checked == 1)) ? 1 : 0;
	vars = 'do-send=' + newsletterId + '&send-to=' + sendTo + '&send-to-list=' + sendToList + '&send-to-ward=' + sendToWard + '&send-num=' + sendNum + '&mark-as-sent=' + markAsSent;
	xmlHttp.send(vars);
	if (!readyToFinish) {
		sendNum++;
		setTimeout("sendMessage("+sendNum+")",1000);
		emailsRemaining--;
	}
}

function updateRemaining() {
	minsRemaining = Math.floor(emailsRemaining/60);
	secsRemaining = Math.floor(emailsRemaining-(minsRemaining*60));
	document.getElementById('time-remaining').innerHTML = minsRemaining + ' mins ' + secsRemaining + ' secs remaining';
	barWidth = Math.floor((1-(emailsRemaining/totalEmails))*400);
	document.getElementById('bar-inner').style.width = barWidth + 'px';
	if (barWidth > 22) {
		percentage = Math.floor((1-(emailsRemaining/totalEmails))*100);
		document.getElementById('bar-inner').innerHTML = percentage + '%';
	}
}

function sendingComplete() {
	document.getElementById('sending-newsletter').style.display = '';
	document.getElementById('newsletter-sent').style.display = 'block';
}

//Settings

userEmailAuthentication = false;
userPostcodeLookup = true;
isAdmin = false;
siteTitle = 'Ealing Conservatives';
