/**
* this value tells us if captchajax is on execution or not
*/
var divValue=false;

/**
 * This object allows some customization;
 */
var captchasettings=new Object();
captchasettings.overlay={};
captchasettings.panel={};
captchasettings.aux={};
captchasettings.questionText={};
captchasettings.buttonLabels={};



/**
* class name is a litte bit weird to avoid js framework's conflicts
* that's why i didnt call it simply Ajax
*/
captchAjax = function ()
{
	this._init ();
}



/**
* _init sets all nueva_clase attributes to their default value. Make sure to call
* this method within your class constructor
*/
captchAjax.prototype._init = function ()
{
	/**
	 * lets get a xhr instance
	 */
	if (window.XMLHttpRequest)
  	{// Mozilla, Safari, ...
		this.httpRequest=new XMLHttpRequest();
		if (this.httpRequest.overrideMimeType)
		{
			this.httpRequest.overrideMimeType('text/xml');
			// See note below about this line
		}
	}

	else if (window.ActiveXObject)
	{// IE
		try
		{
			this.httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e)
		{
			try
			{
				this.httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch (e)
			{
				//
			}
		}
	}
	if (!this.httpRequest)
	{
		alert('Giving up :( Cannot create an XMLHTTP instance');
		return false;
	}

}







/**
* function getRequest sends a XMLHttpResponseText using GET method
* @param url
*/
captchAjax.prototype.getRequest = function (url)
{

   	this.httpRequest.open('GET', url, false);
   	this.httpRequest.send('');
}




/**
* function addDOMElement
*
* this is a callback function called after a new captcha  was generated.
* It generates an absolute DIV on the fly, draws captcha image
* and then executes errCallback in case of error, or continues with the form
* submition on success.
*
* @param HTML imagecode needed for fetching de captchaimage
*
*/
function addDOMElement(HTML)
{


	/**
	 * Default text data
	 * These values gets overriden on customization
	 */

	var pleaseText="Are you human?";
	var sendLABEL="Send";
	var resetLABEL="Reset";

	/**
	 * try to replace default buttons labels with your customized values
	 */
	if( typeof captchasettings.buttonLabels!="undefined")
	{
		if(typeof captchasettings.buttonLabels.send!="undefined")
		{
			sendLABEL=captchasettings.buttonLabels.send;
		}
		if(typeof captchasettings.buttonLabels.reset!="undefined")
		{
			resetLABEL=captchasettings.buttonLabels.reset;
		}
	}

	/**
	 * try to replace pleaseText value with your customized data
	 */
	if( typeof captchasettings.questionText!="undefined")
	{
		if(typeof captchasettings.questionText.text!="undefined")
		{
			pleaseText=captchasettings.questionText.text;
		}
	}


	var divOverlay = document.createElement('div');
	divOverlay.id="divOverlay";
	var divstyle="position: absolute;left: 0px; top: 0px;width: 100%;height: "+document.body.scrollHeight+"px;z-index: 1000;";


	var am_i_ie = new RegExp("MSIE");
	var i_am_ie = am_i_ie.test(navigator.appVersion);


	divOverlay.setAttribute('style',divstyle);

	document.body.appendChild(divOverlay);
	if( typeof captchasettings.overlay!="undefined")
	{
		if(typeof captchasettings.overlay.opacity!="undefined")
		{
			if( i_am_ie)
			{
				/* IE uses non standard filter rules*/
				document.getElementById("divOverlay").style["filter"]="alpha(opacity="+parseFloat(captchasettings.overlay.opacity)*100+")";
			}
			else
			{
				var am_i_khtml = new RegExp("KHTML");
				var i_am_khtml = am_i_khtml.test(navigator.appVersion);
				if(i_am_khtml)
				{
					/* khtml 3.5.x opacity is ignored, on 4.x should be fixed */
					document.getElementById("divOverlay").style["-khtml-opacity"]=parseFloat(captchasettings.overlay.opacity);
				}
				else
				{
					/* opera, firefox, else */
					document.getElementById("divOverlay").style["opacity"]=parseFloat(captchasettings.overlay.opacity);
				}
			}

		}
		if(typeof captchasettings.overlay.backgroundColor!="undefined")
		{
			document.getElementById("divOverlay").style["backgroundColor"]=captchasettings.overlay.backgroundColor;
		}
	}

	var am_i_ie6 = new RegExp("MSIE 6.0");
	var i_am_ie6 = am_i_ie6.test(navigator.appVersion);

	var divcombo2=document.createElement('div');
	divcombo2.setAttribute('class', 'jqmWindow');

	if( typeof captchasettings.panel!="undefined")
	{
		if(typeof captchasettings.panel.border!="undefined")
		{
			divcombo2.style['border']=captchasettings.panel.border;
		}
		if(typeof captchasettings.panel.backgroundColor!="undefined")
		{
			divcombo2.style['backgroundColor']=captchasettings.panel.backgroundColor;
		}
	}
	divcombo2.id="combo2";



	if( i_am_ie6)
	{
		/* For the bloody IE6 selects box bug*/
		var ifrm= document.createElement('iframe');
		ifrm.id="IFrame";
		ifrm.setAttribute('style', 'position: absolute; display: block; filter: mask(); background-color: #ffffff; ');
		ifrm.style['visibility']="visible";
		document.body.appendChild(ifrm);
	}
	document.body.appendChild(divcombo2);


	if(HTML!='Service error')
	{
		var captchaIMG= new Image(120,60);
		captchaIMG.src="/modules/captcha/?mode=image&code="+HTML;
		captchaIMG.setAttribute('style', 'border:1px;padding:10px;');
		//document.wapush.appendChild(captchaIMG);
		var divChild=document.createElement('div');
		divChild.id="dchild";
		divChild.setAttribute('style',' margin-bottom: 3px; margin-top: 5px;');
		var input_captcha=document.createElement('input');
		input_captcha.type="text";
		input_captcha.id="captcha";
		input_captcha.name="captcha";
		input_captcha.setAttribute('size','10');
		input_captcha.setAttribute('style', 'margin-left:8px;padding:1px;width:120px');

		var input_code=document.createElement('input');
		input_code.type="hidden";
		input_code.id="code";
		input_code.name="code";
		input_code.value=HTML;

		/* tried before to implement document.createElement  + appendChild for this two buttons but IE doesnt like the onclick property created on the fly */
		/* however innerHTML approach seems to works on every tested browser */
		var enviarBTN="<INPUT id='check' onclick='validateCaptcha()' type='submit' value='"+sendLABEL+"'>";
		var resetBTN="<INPUT type='button' id='resetbtn' onclick='resetPage()'  value='"+resetLABEL+"'>";




		var ffamily="Franklin Gothic Medium, tahoma";
		var fcolor="#F5822A";
		var fsize="18px"
		if( typeof captchasettings.questionText!="undefined")
		{
			if(typeof captchasettings.questionText.fontFamily!="undefined")
			{
				ffamily=captchasettings.questionText.fontFamily;
			}
			if(typeof captchasettings.questionText.fontColor!="undefined")
			{
				fcolor=captchasettings.questionText.fontColor;
			}
			if(typeof captchasettings.questionText.fontSize!="undefined")
			{
				fsize=captchasettings.questionText.fontSize;
			}
		}
		document.getElementById('combo2').innerHTML="<span style='font-family:"+ffamily+";font-weight:bold;color:"+fcolor+";font-size:"+fsize+";margin-left:0;'>"+pleaseText+"</span>";


		document.getElementById('combo2').innerHTML+= '<br /><br />';
		document.getElementById('combo2').appendChild(captchaIMG);


		var atext="Enter the characters as seen on the image (case insensitive)";
		var afamily="arial";
		var acolor="#000";
		var asize="14px";
		var borderLeft="1px solid #C0C0C0";
		if( typeof captchasettings.aux!="undefined")
		{
			if(typeof captchasettings.aux.fontFamily!="undefined")
			{
				afamily=captchasettings.aux.fontFamily;
			}
			if(typeof captchasettings.aux.fontColor!="undefined")
			{
				acolor=captchasettings.aux.fontColor;
			}
			if(typeof captchasettings.aux.fontSize!="undefined")
			{
				asize=captchasettings.aux.fontSize;
			}
			if(typeof captchasettings.aux.text!="undefined")
			{
				atext=captchasettings.aux.text;
			}
			if(typeof captchasettings.aux.borderLeft!="undefined")
			{
				borderLeft=captchasettings.aux.borderLeft;
			}
		}

		var aux = document.createElement('div');
		aux.setAttribute('style', 'position:absolute; width:276px; padding-left:8px;right:8px;top:78px; border-left: '+borderLeft+';');
		aux.id="aux";




		aux.innerHTML="<span style='color:"+acolor+";font-size:"+asize+";font-family:"+afamily+"'>"+atext+"</span>";
		document.getElementById('combo2').appendChild(aux);

		document.getElementById('combo2').appendChild(divChild);
		document.getElementById('dchild').appendChild(input_captcha);
		document.getElementById('dchild').appendChild(input_code);

		document.getElementById('dchild').innerHTML+=enviarBTN+"&nbsp;";
		document.getElementById('dchild').innerHTML+=resetBTN;
		document.getElementById('combo2').innerHTML+="<br/>";

	}
	else
	{
		var errText=document.createTextNode(HTML + '<br /><br />');
		document.getElementById('combo2').appendChild(errText);
	}




	divValue=true;


}


function useCaptcha(btn)
{
	captchasettings.form=btn.form;

	var getcaptcha=new captchAjax();
var seed = new Date();
seed = "&"+seed.getTime();
	getcaptcha.getRequest('/modules/captcha/?mode=new&long=5'+seed);
	if (getcaptcha.httpRequest.readyState == 4)
   		{
   			if (getcaptcha.httpRequest.status == 200)
   			{
   				addDOMElement(getcaptcha.httpRequest.responseText);
   			}
			else
			{
				alert('There was a problem with the request.');
			}
		}
}


function validateCaptcha()
{

	var verifyCaptcha=new captchAjax();
	var code=document.getElementById('code').value;
	var captcha=document.getElementById('captcha').value;
	var seed = new Date();
	seed = "?"+seed.getTime();
	verifyCaptcha.getRequest('/modules/captcha/'+seed+'&mode=verify&code='+code+'&captcha='+captcha);
	var am_i_konqueror = new RegExp("KHTML/3.5");
	var i_am_konqueror = am_i_konqueror.test(navigator.appVersion);
	if(i_am_konqueror)
	{
		/* konqueror seems to use  eval function */
		eval("var konqFix1="+verifyCaptcha.httpRequest.readyState+"");
		eval("var konqFix2="+verifyCaptcha.httpRequest.status+"");
		eval("var konqFix3="+verifyCaptcha.httpRequest.responseText+"");
	}
	if (verifyCaptcha.httpRequest.readyState == 4||( i_am_konqueror==true && konqFix1==4))
	{

		if (verifyCaptcha.httpRequest.status == 200||( i_am_konqueror==true && konqFix2==200))
		{
			if(verifyCaptcha.httpRequest.responseText==1||( i_am_konqueror==true && konqFix3==1))
			{
				
				//resetPage();
				okCallback();
				currentElement = document.createElement("input");
				currentElement.setAttribute("type", "hidden");
				currentElement.setAttribute("name", "code");
				currentElement.setAttribute("id", "code");
				currentElement.setAttribute("value", code);
				captchasettings.form.appendChild(currentElement);
    			captchasettings.form.submit();
				
    		}

			else{
    			resetPage();
    			/** as far as it goes, by default is an empty function
    			 */
    			errCallback();

    		}
    	}
  		else
  		{
  			alert('There was a problem with the request.');
  		}
   	}
   	divValue=false;
}


function resetPage()
{
	if(divValue==true)
	{
		document.getElementById('divOverlay').parentNode.removeChild(document.getElementById('divOverlay'));
		var am_i_ie6 = new RegExp("MSIE 6.0");
		var i_am_ie6 = am_i_ie6.test(navigator.appVersion);

		if( i_am_ie6)
		{
			document.getElementById('IFrame').parentNode.removeChild(document.getElementById('IFrame'));
		}
		document.getElementById('combo2').parentNode.removeChild(document.getElementById('combo2'));
		divValue=false;
	}

}


window.onresize=function()
{
	if(divValue==true)
	{
	 //	document.getElementById('divOverlay').style['width']= document.body.scrollWidth+"px";
	 	document.getElementById('divOverlay').style['height']= document.body.scrollHeight+"px";
		var am_i_ie6 = new RegExp("MSIE 6.0");
		var i_am_ie6 = am_i_ie6.test(navigator.appVersion);
		if( i_am_ie6)
		{
			document.getElementById('IFrame').style['width']= document.body.scrollWidth+"px";
			document.getElementById('IFrame').style['height']= document.body.scrollHeight+"px";

		}
	}

}

 function errCallback(){
 /* empty function , overwrite if needed on your own html file*/
 }

 function okCallback(){
 /* empty function , overwrite if needed on your own html file*/
 }
