//------------------------------------------------------------------------------------------
//advanced controls for adding competition questions

function competitionTools(){
	if(document.getElementById('competitionControls') && document.getElementById('duoPagedata')){
		var toolbar=document.getElementById('competitionControls');
		toolbar.innerHTML='<div class="competionAddButton"><a onclick="javascript:void(competitionAddQuestion())">add question</a></div>';		
		var total=0;
		var formArea=document.getElementById('competitionAdd');
		var val='';
		var html='<div id="competitionAddInner">'
		while(document.getElementById('compquestion'+total)){
			val=document.getElementById('compquestion'+total).innerHTML;
			html+='<div id="quesinput'+total+'"><a onclick="compQuestionRemove(\'quesinput'+total+'\')">x</a><input onkeyup="competitionCreateForm()" onblur="competitionCreateForm()" type="text"  value="'+val+'" /></div>';
			total++;
		}
		html+="</div>";
		formArea.innerHTML=html;
		var competitionArea=document.getElementById('pages|html|p_3');
		competitionArea.setAttribute('contentEditable',false);
		document.getElementById('compQuestions').style.display="none";
	}
}

function competitionAddQuestion(){
	var formArea=document.getElementById('competitionAddInner');
	var inputs=formArea.getElementsByTagName('INPUT');
	var total=inputs.length+1;
	formArea.innerHTML+='<div id="quesinput'+total+'"><a onclick="compQuestionRemove(\'quesinput'+total+'\')">x</a><input onkeyup="competitionCreateForm()" onblur="competitionCreateForm()"  type="text" value="'+total+'. your question here" /></div>';
}

function compQuestionRemove(id){
	//alert(id);return;
	var ques=document.getElementById(id);
	ques.parentNode.removeChild(ques);//outerHTML='';
	competitionCreateForm();
}

function competitionCreateForm(){
	var formArea=document.getElementById('competitionAdd');
	var competitionArea=document.getElementById('pages|html|p_3');
	var inputs=formArea.getElementsByTagName('INPUT');
	var html='';
	var qcount=0;
	for(var i=0;i<inputs.length;i++){
		if(inputs[i].value.length>0){
			html+='<div><label id="compquestion'+qcount+'">'+inputs[i].value+'</label><input class="fullWidth" name="answer'+qcount+'" /></div>';	
			qcount++;
		}		
	}
	competitionArea.innerHTML=html;
}

//apply for competition
function competitionValidateAndSend(){
	
	//check user info form - the question answers are optional
	var form=document.getElementById('competform'); 	
	var field='';
	var errorcount=0;
	var question='';
	var formFields=form.getElementsByTagName('INPUT');
	for(var i=0;i<formFields.length;i++){
		field=formFields[i];
		if(field.value.length<1 && field.name!="telephone" && field.name!="country"){
			field.style.border="1px solid red";
			errorcount++;
		}else{
			field.style.border="1px solid #cccccc";
		}
	}	
	if(errorcount>0){
		alert('You must complete the form fields marked in red. \nPlease complete these and try again.');	
	}else{
		//submit all form data
		formFields=form.elements;
		var savingData='';
		for(var i=0;i<formFields.length;i++){
			field=formFields[i];
			if(field.name){
				savingData+=field.name+"="+field.value+"&";
			}
		}
		//add q & a's
		formFields=document.getElementsByTagName('input');		
		for(var i=0;i<formFields.length;i++){
			field=formFields[i];
			if(field.name.substr(0,6)=="answer"){
				question=field.parentNode.previousSibling.previousSibling.innerHTML.replace('\n','');
				if(whichBrs()=="ie"){
					question=field.parentNode.previousSibling.innerHTML.replace(/[\n\r\t]*/,'');
				}else{
					question=field.parentNode.previousSibling.previousSibling.innerHTML.replace(/[\n\r\t]*/,'');	
				}
				savingData+=question+"="+field.value+"&";
			}
		}
		var myConn = new XHConn();
		myConn.connect("/competition.php", "POST", savingData, competitionRedirect);	
	}
}


var validcaptcha = false;

function competitionValidateAndSendTest(){
	
	//check user info form - the question answers are optional
	var form=document.getElementById('competform'); 	
	var field='';
	var errorcount=0;
	var question='';

	var qVal
	var answerInputs = getElementsByClassName(document,'fullWidth');
	for(var x=0;x<answerInputs.length;x++){
		qVal = answerInputs[x].value;
		if(qVal.length < 1){
			answerInputs[x].style.border = "1px solid #f00";
			errorcount++;
		} else {
			answerInputs[x].style.border = "1px solid #cccccc";
		}
	}

	var formFields=form.getElementsByTagName('INPUT');
	var formTextArea = document.getElementById('comp_address');
	for(var i=0;i<formFields.length;i++){
		field=formFields[i];
		if(field.value.length<1){
			field.style.border="1px solid red";
			errorcount++;
		}else{
			field.style.border="1px solid #cccccc";
		}
	}
	if(formTextArea.value.length<1) {
		formTextArea.style.border = "1px solid #f00";
		errorcount++;
	} else {
		formTextArea.style.border = "1px solid #cccccc";
	}
	if(errorcount>0){
		alert('You must complete the form fields marked in red. \nPlease complete these and try again.');	
	}else{
		
		if(!validcaptcha){
			competitionCaptcha();
		} else {
			//submit all form data
			formFields=form.elements;
			var savingData='';
			for(var i=0;i<formFields.length;i++){
				field=formFields[i];
				if(field.name){
					savingData+=field.name+"="+field.value+"&";
				}
			}
			//add q & a's
			formFields=document.getElementsByTagName('input');		
			for(var i=0;i<formFields.length;i++){
				field=formFields[i];
				if(field.name.substr(0,6)=="answer"){
					
					if(document.getElementById(('compquestion'+field.name.replace('answer','')))){
						question=document.getElementById(('compquestion'+field.name.replace('answer',''))).innerHTML;
						question=question.replace(/[^a-z0-9-_ ]+/ig,'');	
					}else{
						question=field.parentNode.previousSibling.previousSibling.innerHTML.replace('\n','');
						if(whichBrs()=="ie"){
							question=field.parentNode.previousSibling.innerHTML.replace(/[^a-z0-9-_ ]+/ig,'');
						}else{
							question=field.parentNode.previousSibling.previousSibling.innerHTML.replace(/[^a-z0-9-_ ]+/ig,'');	
						}
					}
					
					savingData+=question+"="+field.value+"&";
				}
			}
			var myConn = new XHConn();
			myConn.connect("/duocms/competition/submit/", "POST", savingData, competitionRedirect);	
		}
//		alert(savingData);

	}
}

function competitionCaptcha(){
	var savingData = "captcha_code="+document.getElementById('captcha_code').value;
	var myConn = new XHConn();
	myConn.connect("/site-resources/secureimage/captchacheck.php","POST",savingData,captchaDone);	
}

function captchaDone(data){
	if(data.responseText == "1"){
		validcaptcha = true;
		competitionValidateAndSendTest();
	} else {
		document.getElementById('captchaFeedback').innerHTML = "Captcha code incorrect. Please try again.";
	}
}

function competitionRedirect(data){
	window.location.href=data.responseText;	
}


//============================================================================================
/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08        **
 ** Code licensed under Creative Commons Attribution-ShareAlike License      **
 ** http://creativecommons.org/licenses/by-sa/2.0/                           **/
if(document.getElementById('statusbar')){
	var oldStatusBackground=document.getElementById('statusbar').style.backgroundImage;
}
function XHConn()
{
  var xmlhttp, bComplete = false;
  try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
  catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
  catch (e) { try { xmlhttp = new XMLHttpRequest(); }
  catch (e) { xmlhttp = false; }}}
  if (!xmlhttp) return null;
  this.connect = function(sURL, sMethod, sVars, fnDone)
  {
    if (!xmlhttp) return false;
    bComplete = false;
    sMethod = sMethod.toUpperCase();

    try {
    	//before load, set statusbar to loading icon
    	if(document.getElementById('statusbar')){
    		document.getElementById('statusbar').style.backgroundImage="url(/duocms-resources/icons/loading2.gif)";
    	}
    		
      if (sMethod == "GET")
      {
        xmlhttp.open(sMethod, sURL+"?"+sVars, true);
        sVars = "";
      }
      else
      {
        xmlhttp.open(sMethod, sURL, true);
        xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
        xmlhttp.setRequestHeader("Content-Type",
          "application/x-www-form-urlencoded");
      }
      xmlhttp.onreadystatechange = function(){
        if (xmlhttp.readyState == 4 && !bComplete){
        	//after loaded set statusbar back to old background
        	if(document.getElementById('statusbar') && oldStatusBackground){
	    		document.getElementById('statusbar').style.backgroundImage=oldStatusBackground;
    		}else if(document.getElementById('statusbar')){
    			document.getElementById('statusbar').style.backgroundImage='';
    		}
        	
          bComplete = true;
          fnDone(xmlhttp);
        }};
      xmlhttp.send(sVars);
    }
    catch(z) { return false; }
    return true;
  };
  return this;
}
