var starOff = new Image(16, 16);
starOff.src = "/images/icon_staroff.gif";
var starOn = new Image(16, 16);
starOn.src = "/images/icon_staron.gif";
var joinEvent = new Image(200, 34);
joinEvent.src="/images/bt_illbethere.gif";
var leaveEvent = new Image(200, 34);
leaveEvent.src = "/images/bt_illbethere.gif";
var MAX_COMMENT_LINES = 10;
var active = 1;
var score = 0;
var contributionId = 0;
var showingUploadForm = 0;
var newwin;
var W3CDOM = (document.createElement && document.getElementsByTagName);

function clearField(field, formName)
{
	var txtElement = getElementFromName(field, formName);
	
	if (txtElement.value == field)
		txtElement.value = "";

	return false;
}
function resetFieldMessage(field, formName)
{
	var txtElement = getElementFromName(field, formName);
	
	if (txtElement.value.length == 0)
		txtElement.value = field;
	
	return false;
}
function getElementFromName(field, formName)
{	
	if (formName == null)
		formName = "galleryUploadForm";
	
	var txtElement;
	if (field == 'full name')
		txtElement = document[formName].fullName;
	else if (field == 'email')
		txtElement = document[formName].email;
	else if (field == 'enter a comment')
		txtElement = document[formName].comment;
	else if (field == 'address')
		txtElement = document[formName].address;
	else if (field == 'postcode')
		txtElement = document[formName].postcode;
	else if (field == 'phone number')
		txtElement = document[formName].phoneNumber;
	else if (field == 'image/video title')
		txtElement = document[formName].galleryItemTitle;
	else if (field == 'image/video description')
		txtElement = document[formName].galleryItemDescription;
	
	return txtElement;
}



function drawRatingPanel(thisScore, isActive, thisContributionId){
	var panel = document.getElementById('ratingStars');
	active = isActive;
	score = thisScore;
	contributionId = thisContributionId;
	panel.innerHTML = "";
	if (!W3CDOM) return;
	for (var i=1; i<=5; i++)
		panel.appendChild(drawRatingStar(i, score, active));
}

function addEvent(obj, evType, fn){ 
 if (obj.addEventListener){ 
   obj.addEventListener(evType, fn, false); 
   return true; 
 } else if (obj.attachEvent){ 
   var r = obj.attachEvent("on"+evType, fn); 
   return r; 
 } else { 
   return false; 
 } 
}

function launchwin(winurl,winname,winfeatures)
{
	newwin = window.open(winurl,winname,winfeatures);
	if(javascript_version > 1.0){
 		setTimeout('newwin.focus();',250);
	}
}

function drawRatingStar(starScore, score, active){
	var star = document.createElement('img');
	star.name = '_' + starScore;
	star.id = '_' + starScore;
	star.alt = score;

	if (active){
		star.src = starOff.src;
		star.onmouseover = overStar;
		star.onclick = sendRating;
	}
	else if (score >= starScore){
		star.src = starOn.src;
		star.onclick = setActive;
	}
	else{
		star.src= starOff.src;
		star.onclick = setActive;
	}
	return star;
}

function getAverageRating(){
	new Ajax.Request('/actions/gallery/contribution.do', {parameters: 'ajax=true&method=getAverageRating&contributionId=' +contributionId, onSuccess:drawAvRating})
}

function drawAvRating(t)
{
	var panel = document.getElementById('averageRatingPanel');
	panel.innerHTML = "";
	var score = Number(t.responseText);
	while(panel.hasChildNodes() == true)
		panel.removeChild(panel.childNodes[0]);
	for (var i=1; i<=score; i++)
		panel.appendChild(drawAvRatingStar(i))
}

function drawAvRatingStar(starScore, score){
	var star = document.createElement('img');
	star.style.paddingRight = '3px';
	star.alt = score;
	star.src = starOn.src;
	return star;
}

function setActive(){
	var messageElement = document.getElementById('rateMessage');
	messageElement.innerHTML = "Rate this beast";
	drawRatingPanel(score, 1, contributionId);
}

function highlightPanel(){
	var div = document.getElementById('ratingStars');
	div.style.backgroundColor = '#C8DBFC';
}

function overStar(event){
	var image;
	var MAX_STARS = 5;
	if (active == 0)
		return;
	var star = new Number(this.name.substring(1));
	var div = document.getElementById('ratingStars');
	//div.style.backgroundColor = '#C8DBFC';
	for(var i=1; i<=star; i++){
		image = document.getElementById('_' + i);
		image.src = starOn.src;
	}
	if (star < MAX_STARS){
		for (var i=star+1; i<=MAX_STARS;i++){
			image = document.getElementById('_' + i);
			image.src = starOff.src;
		}
	}
}

function fadePanel(event){
	var newEl=event.relatedTarget||event.toElement;
	if(newEl.tagName == "IMG")
		return true;
	new Effect.Highlight('ratingStars', {startcolor:'#C8DBFC', endcolor:'#FFFFFF', restorecolor:'#FFFFFF'});
	if (active == 1)
		drawRatingPanel(0, 1, contributionId);
}

function sendRating(event){
	if (active == 0)
		return;
	score = new Number(this.name.substring(1));
	active = 0;
		
	new Ajax.Request('/actions/gallery/contribution.do', {parameters: 'ajax=true&method=rateItem&contributionId=' +contributionId+ '&rating='+score, onLoading:indicateLoadingIcon, onSuccess:ratingSuccess, onFailure:ratingFailure})
}

function postComment(){
	
	/*
	if (document.getElementById('commentLoadingIcon')){
		var img = document.getElementById('commentLoadingIcon');
		img.style.cursor = 'wait';
		if (img.style.display=='none')
			img.style.display='inline';
		else
			img.style.display='none';
	}
	*/
	addComment();
	return false;
}

function indicateLoadingIcon(){
	var messageElement = document.getElementById('rateMessage');
	
	/*
	messageElement.innerHTML = "Saving Rating";
	if (document.getElementById('loadingIcon')){
		var img = document.getElementById('loadingIcon');
		img.style.cursor = 'wait';
		if (img.style.display=='none')
			img.style.display='inline';
		else
			img.style.display='none';
	}
	*/
}

function hideIcon(){
	if (document.getElementById('loadingIcon')){
		var img = document.getElementById('loadingIcon');
		img.style.cursor = 'auto';
		img.style.display='none';
	}
}

function addComment(){

	var fullName = "";
	var email = "";
	
	if (document.commentForm.fullName != 'undefined' && document.commentForm.email != 'undefined') {
		fullName = encodeURIComponent(document.commentForm.fullName.value);
		email = encodeURIComponent(document.commentForm.email.value);
	}

	var id = encodeURIComponent(document.commentForm.contributionId.value);
	var comment = encodeURIComponent(document.commentForm.comment.value);

	if (document.commentForm.fullName.value.length == 0 || document.commentForm.fullName.value == "full name" || document.commentForm.email.value.length == 0 || document.commentForm.email.value == "email" || document.commentForm.comment.value.length == 0 || document.commentForm.comment.value == "enter a comment")
	{
		alert('Please fill out all the fields');
	}
	else
		new Ajax.Request( '/actions/gallery/contribution.do', {parameters: 'ajax=true&method=addComment&contributionId=' +id+ '&comment=' + comment + '&fullName=' + fullName + '&email=' + email, onSuccess:commentSuccess, onFailure:reportFailure})
	
}

var commentSuccess = function(t){	
	var commentBlock = document.getElementById('newCommentBlock');
	var newComment = drawCommentBlock(t);
	commentBlock.appendChild(newComment);
	document.commentForm.comment.value = '';
	/*
	if (document.getElementById('commentLoadingIcon')){
		var img = document.getElementById('commentLoadingIcon');
		img.style.cursor = 'auto';
		img.style.display='none';
	}
	*/
	
	//new Effect.SlideDown(newComment); //crashes IE6
	document.location.reload();
}
/**
Renders the newly added comment block after the xml is returned.
*/
var drawCommentBlock = function(t){
	var fullName = getNodeValue(t.responseXML, 'fullName');
	var contributorId = getNodeValue(t.responseXML, 'contributorId');	
	
	//<div class=publicComment></div>
	var newComment = document.createElement('div');
	newComment.className = 'publicComment';
	newComment.style.display = 'none'; // keep it hidden for now..

	var childDiv = document.createElement('div');
	
	//<div class=publicComment><h2></h2></div>	
	var header = document.createElement('h2');

	//<div class=publicComment><h2><small></small></h2></div>
	var hdrTextSize = document.createElement('small');
	
	//<div class=publicComment><h2><small>name says:</small></h2></div>
	var headerText = document.createTextNode(fullName + ' says:');
	hdrTextSize.appendChild(headerText);
	header.appendChild(hdrTextSize);
	//newComment.appendChild(header);
	
	//should now have <div class=publicComment><h2><small>name says:</small></h2></div>
	
	var comment = document.createElement('p');
	var strings = getNodeValue(t.responseXML, 'comment').split('\n');
	var commentArray = new Array(strings.length);
	var brArray = new Array(strings.length);
	for (var i=0;i<strings.length; i++){	
		commentArray[i] = document.createTextNode(strings[i]);
		comment.appendChild(commentArray[i]);
		brArray[i] = document.createElement('br');
		comment.appendChild(brArray[i]);
	}
	
	
	//should now have <div class=publicComment><h2><small>name says:</small></h2><p>comment</p></div>
	
	/*
	var offsensiveSpan = document.createElement('span');
	offsensiveSpan.className = 'offensiveComment';
	
	var offensiveText = document.createTextNode('Flag this comment as ');
		
	var offensiveLink = document.createElement('link');
	offensiveLink.href = '/actions/gallery/contribution.do?method=reportItem&amp;contributionId=<%=comment.getContributionId()%>';
	offensiveLink.onClick = 'report(); return false;';
	var offensiveLinkText = document.createTextNode('offensive');
	offensiveLink.appendChild(offensiveLinkText);
	
	offsensiveSpan.appendChild(offensiveText);
	offsensiveSpan.appendChild(offensiveLink)
	*/
	
	childDiv.appendChild(header);
	childDiv.appendChild(comment);		
	//childDiv.appendChild(offsensiveSpan);
	
	newComment.appendChild(childDiv);

	return newComment
}
var getNodeValue = function(tree, el){
    return tree.getElementsByTagName(el)[0].firstChild.nodeValue;
}
var ratingSuccess = function(t){
	document.getElementById('rateMessage').innerHTML='Your rating';
	hideIcon();
	drawRatingPanel(score, 0, contributionId);
	getAverageRating();
	fadePanel();
}
var ratingFailure = function(t){
	hideIcon();
	alert('Sorry, an error occurred while processing your request.\nPlease try again later.');
}
var reportFailure = function(t){
	alert("Sorry, your request could not be processed.\nPlease try again later.");
}
function unhighlightImage(){
	if (showingUploadForm == 1)
		return;
	var element = document.getElementById('avatarContainer');
	element.style.border = '5px solid #FFFFFF';
	element.style.backgroundColor = '#FFFFFF';
}
function highlightImage(){
	var element = document.getElementById('avatarContainer');
	element.style.border = '5px solid #C8DBFB';
	element.style.backgroundColor = '#C8DBFB';
	element.title = 'Click to upload a new file.';
}
function showUploadForm()
{
	var uploadElement = document.getElementById('uploadAvatarPanel');
	uploadElement.style.display = 'block';
	showingUploadForm = 1;
}
/*
function initFileUploads() {
	if (!W3CDOM) return;
	var fakeFileUpload = document.createElement('div');
	fakeFileUpload.className = 'fakefile';
	fakeFileUpload.appendChild(document.createElement('input'));
	var image = document.createElement('img');
	image.src='/images/gallery/bt_browse.gif';
	fakeFileUpload.appendChild(image);
	var x = document.getElementsByTagName('input');
	for (var i=0;i<x.length;i++) {
		if (x[i].type != 'file') continue;
		if (x[i].parentNode.className != 'fileinputs') continue;
		x[i].className = 'file hidden';
		var clone = fakeFileUpload.cloneNode(true);
		x[i].parentNode.appendChild(clone);
		x[i].relatedElement = clone.getElementsByTagName('input')[0];
		x[i].onchange = x[i].onmouseout = function () {
			this.relatedElement.value = this.value;
		}
	}
}*/
function hasAjax(){
	if (new ActiveXObject('Msxml2.XMLHTTP') != undefined)
		return true;
	if (new ActiveXObject('Microsoft.XMLHTTP') != undefined)
		return true;
    if  (new XMLHttpRequest() != undefined)
    	return true;
    return false;
}
/* Upload form validation */
var termsConditionsNotAccepted = function(){
	return showUploadError('Please make sure you have read and agree with the terms and conditions of entry.');
}
var noFilesSelected = function(){
	return showUploadError('Please select at least one file to upload.');
}
var showUploadError = function(errorText){
	var p = document.getElementById('uploadError');
	p.innerHTML = errorText;
	var panel = document.getElementById('uploadErrorPanel');
	//panel.style.display = 'block';
	new Effect.Appear(panel);
	return false;
}

/* Form file upload progress */
/*
function refreshProgress(){
    UploadMonitor.getUploadInfo(updateProgress);
}
function updateProgress(uploadInfo){
    if (uploadInfo.inProgress){
        var fileIndex = uploadInfo.fileIndex;
        var progressPercent = Math.ceil((uploadInfo.bytesRead / uploadInfo.totalSize) * 100);
        document.getElementById('progressBarBoxContent').style.width = parseInt(progressPercent * 4.39) + 'px';
        window.setTimeout('refreshProgress()', 1000);
    }
    return true;
}
function startProgress(){
    document.getElementById('progressBar').style.display = 'block';
    // wait a little while to make sure the upload has started ..
    window.setTimeout("refreshProgress()", 1500);
    return true;
}
function hideProgressBar(){
    document.getElementById('progressBar').style.display = 'none';
}
function UploadMonitor() { }
      UploadMonitor._path = '';
      UploadMonitor.getUploadInfo = function(callback) {
      DWREngine._execute(UploadMonitor._path, 'UploadMonitor', 'getUploadInfo', callback);
}
*/
function trim(s){
   	while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r'))
   	 { s = s.substring(1,s.length); }
 	while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r'))
   	 { s = s.substring(0,s.length-1); } 
   	return s;
}