function addEvent(obj, evType, fn)
{
	if (obj.addEventListener) {
		obj.addEventListener(evType, fn, true);
		return true;
	} else if (obj.attachEvent) {
		var r = obj.attachEvent("on"+evType, fn);
		return r;
	} else {
		return false;
	}
}
/**
 * Loads a new freecap image
 */
function captchaLoadNew ()
{
	
	if (!document.getElementById) return false;
	
	// extract image name from image source (i.e. cut off ?randomness)
	current_img = document.getElementById("captcha-img");
	thesrc = current_img.src;
	thesrc = thesrc.substring(0,thesrc.lastIndexOf(".")+4);
	
	var imgWidth  = current_img.width;
	var imgHeight = current_img.height;
	
	// convert the wrapper to a 'fixed container' with the appropriate dimensions
	var wrap = document.getElementById("captcha-wrap");
	wrap.style.width   = imgWidth+'px';
	wrap.style.height  = imgHeight+'px';
	wrap.style.display = 'block';
	wrap.style.textAlign = 'center';	
	// create loading img
	loading_img = new Image();
	loading_img.src = 'http://'+window.location.hostname+'/reviews/assets/icons/loading.gif';
	// create new captcha image
	target_img = new Image();
    target_img.src = thesrc+"?"+Math.round(Math.random()*100000);
	
	// show the loading gif
	current_img.src = loading_img.src;
	
	// make loading img appear more vertically aligned.
	// remember to remove this when changed
	current_img.style.marginTop = '20px'; 
	
	// set timerid here
	timer_id = ''; 
	
	captchaReplaceImg();
}

function captchaReplaceImg ()
{		
	// if the image has not been loaded, set time interval and load the target_img
	// if it has already been loaded, check if a timer exists and:
	// clear it and load the target_img if it does, or just load the target_img if it doesn't.
	
	if (!imgLoaded(target_img) )
	{	
		if (timer_id == '') {
			timer_id = window.setInterval("captchaReplaceImg()", 500);
		}
	} else {
		current_img.style.marginTop = '0px';
		current_img.src = target_img.src;		
		
		if (timer_id != '') {
			clearInterval(timer_id);			
		}
	}
}

function imgLoaded(img)
{
    // IE only
    if (!img.complete) {
		return false;
	}

    // Other browsers
    if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
		return false;
	}

    return true;
}

/**
 * Replaces the captcha reload text/description with a trigger link.
 */
function captchaAddTrigger () 
{
	//alert('test');
	if (!document.getElementById) return false;
	
	var txt_elm = document.getElementById('captcha-reload');
	var txt_elm_id = 'captcha-reload';
	var txt = "If you cannot read the word, you can load a <a href=\"#\" onClick=\"this.blur();captchaLoadNew();return false;\" title=\"Load new word\">new one</a>.";
	
	if (txt_elm) {
		txt_elm.innerHTML = txt;
	}
	
}
if(document.getElementById)
{
	addEvent(window, 'load', captchaAddTrigger);
}

