String.prototype.startsWith = function( s ) { return this.indexOf( s ) == 0; }

function getRequest() {
	var request;
	try {
		request = new XMLHttpRequest();
	} catch( e ) {
		try {
			request = new ActiveXObject( 'Msxml2.XMLHTTP' );
		} catch( e ) {
			try {
				request = new ActiveXObject( 'Microsoft.XMLHTTP' );
			} catch( e ) {
				request = null;
			}
		}
	}
	return request;
}

/*
 * Counts the amount of characters in a text area and prevents
 * it from exceeding a maximum amount.
 */
function countTextArea( textArea, maxLength ) {
	var count = textArea.value.length;
	var charsLeft = maxLength - count;
	if( charsLeft >= 0 )
		updateTextAreaCounter( charsLeft, 'sigtextcount' );
	else
		textArea.value = textArea.value.substring( 0, maxLength );
}

/*
 * Updates the text area counter.
 */
function updateTextAreaCounter( charsLeft, counterName ) {
	var counter = document.getElementById( counterName );
	counter.innerHTML = charsLeft;
}

/*
 * Casts a vote on a guide.
 */
function voteGuide( guide_id, vote_value ) {
	request = getRequest();
	if( request != null ) {
		voteLinksDiv = document.getElementById( 'votelinks' );
		voteLoaderDiv = document.getElementById( 'voteloader' );
		try {
			url = 'rosta.php';
			parameters = 'id=' + guide_id + '&type=g&value=' + vote_value;
			request.onreadystatechange = function() {
				if( request.readyState == 4 || request.readyState == 'complete' ) {
					if( request.status == 200 ) {
						response = request.responseText;
						if( response.startsWith( 'vote_ok' ) ) {
							counts = response.split( '|' );
							voteScore = document.createTextNode( counts[1] + ' ja, ' + counts[2] + ' nej' );
							voteLinksDiv.innerHTML = null;
							voteLinksDiv.appendChild( voteScore );
						}
						voteLoaderDiv.style.display = 'none';
						voteLinksDiv.style.display = 'block';
					}
				}
			};
			request.open( 'post', url, true );
			request.setRequestHeader( 'Content-type', 'application/x-www-form-urlencoded' );
			request.setRequestHeader( 'Content-length', parameters.length );
			request.setRequestHeader( 'Connection', 'close' );
			request.overrideMimeType( 'text/html' );
			request.send( parameters );
		} catch( e ) {
			alert( 'Exception: ' + e );
		}
		voteLoaderImage = document.getElementById( 'loaderimage' );
		color = vote_value == 'ja' ? 'g' : ( vote_value == 'nej' ? 'r' : '' );
		voteLoaderImage.setAttribute( 'src', 'images/gfx/loader_' + color + '.gif' );
		voteLinksDiv.style.display = 'none';
		voteLoaderDiv.style.display = 'block';
	}
}
