function LepRegistration(){
}
/**
* Error message container
*/
LepRegistration.errorMessage = new Array();
/**
* Error message Elemnts
*/
LepRegistration.errorElements = new Array();
/**
* List of children indexed by option
*/
LepRegistration.optionChildren = new Array();
/**
* Option to Question index map
*/
LepRegistration.optionQuestion = new Array();
/**
* Container of questions
*/
LepRegistration.questions = new Array();
/**
* Currently selected parent options
*/
LepRegistration.selectedOptions = new Array();

LepRegistration.jsonService = '';
LepRegistration.additionalCheck = {'email':new Array(),'password':new Array(),'other':new Array(),'location':new Array(),'tandc':false};
LepRegistration.checkedLocations = new Array();
LepRegistration.locationSpecific = new Array();
LepRegistration.onLoadEvents = new Array();
LepRegistration.displayedQuestions = new Array();
LepRegistration.currentElement = null;
LepRegistration.currentQuestionCode = null;
LepRegistration.currentText = null;

LepRegistration.doAccountCheck = false;
LepRegistration.tmp = {};


LepRegistration.showRequiredText = function()
{
    $('span.form-required').each(function(){
        this.innerHTML='Required';
    });
}

/*
*	Option Type definition
*/
LepRegistration.Option = function(id,text){
	var id;
	var text;
		
	this.id=id;
	this.text=text;
}


LepRegistration.toggleContinue = function()
{
    var form = document.getElementById('lep-registration-form');
    var page = form.current_page.value;
    var id='';
    var show=false;
	for (var i in this.questions[page])
	{
	    id=this.questions[page][i].id
	    if (this.displayedQuestions[id] 
	       && this.questions[page][i].mandatory 
	       && this.questions[page][i].children.length
	       )
	    {
           var element = form[i];
 		   if ((this.questions[page][i].type=='select' && !element.value) ||
 		       (this.questions[page][i].type=='radio' && !this.checkNodeList(element)))
	       {
			 show=false;
		   }
		   else
		   {
			 show=true;
		   }
	    }
	}
	
	if (show)
	{
        $('#containerTandc').show();
	    $('#continue-button').show();
	}
	else
	{
        $('#containerTandc').hide();
	    $('#continue-button').hide();
	}
}

/*
*	Question Type definition
*/
LepRegistration.Question = function(id,text,mandatory,type,hasParents) { 
		var id;
		var text;
		var mandatory;
		var type;
		var options;
		var children;
		var hasParents;
		
		this.id=id;
		this.text=text;
		this.mandatory=mandatory;
		this.type=type;
		this.options=new Array();
		this.children=new Array();
		this.hasParents=hasParents;
		
		this.addOption = function(id,text)
		{
		    LepRegistration.optionQuestion[id]=this.id;
			this.options.push(new LepRegistration.Option(id,text));
		}
		
		this.addChild = function(id)
		{
		    this.children.push(id);
		}
}
/**
*	Retrieve a question by question type
*/
LepRegistration.getQuestionsByType = function(type,page){
	var questions = new Array();
	if (!page){
		for (var page in this.questions){
			res=LepRegistration.getQuestionsByType(type,page);
			if (res.length>0){
				questions=questions.concat(res);		
			}
		}
	}
	
	if (!this.questions[page]){
		return questions;
	}
	
	for (var i in this.questions[page]){
		if (this.questions[page][i].type==type){
			questions.push(this.questions[page][i]);
		}
	}
	return questions;
}
/**
*	Hide show location-specific questions
*/
LepRegistration.processlocationSpecific = function(option){
	for (var i in LepRegistration.locationSpecific){
		if (LepRegistration.locationSpecific[i]==option){
			$('#location-'+LepRegistration.locationSpecific[i]).hide();
			//$('#location-'+LepRegistration.locationSpecific[i]).attr({'style':'display:none;'});
		}else{
			$('#location-'+LepRegistration.locationSpecific[i]).show();
			//$('#location-'+LepRegistration.locationSpecific[i]).attr({'style':'display:block;'});
		}
	}
	
}
/*
* Checks if a given value exists in an array 
*/
LepRegistration.inArray = function(val,arr){	
	for (var i in arr){
		if (arr[i]==val){
			return i;		
		}
	}
	return false;
}
/**
* Navigates back through a multi-step form	
*/
LepRegistration.goBack = function(form){
	form.go_back.value=1;
	return true;
}
/**
* Checks a node list to see if a value is selected
*/
LepRegistration.checkNodeList = function(formEl){
	for (var i=0;i<formEl.length;i++){
		if (formEl[i].checked){
			return formEl[i].value;
		}
	}
	return false;
}
/**
*	Submit form handler
*/
LepRegistration.submitForm = function(form,finished){
	
	var fieldPrefix = 'edit-';
	var page = form.current_page.value;
	var container = document.getElementById('lep-registration');
	//Reset all errors
	this.resetErrors();
	
	//If an existing error message div is already present remove it
	if (document.getElementById('lep_error_messages')){
		container.removeChild(document.getElementById('lep_error_messages'));
	}
	

	for (var i in this.questions[page]){
		//if the container is hidden (ie. The question isn't showing), then don't continue;
		if (document.getElementById('container'+i).style.display=='none')continue;
		if (this.questions[page][i].mandatory==0)continue;
		
		var element = document.getElementById(fieldPrefix+i);
		switch(this.questions[page][i].type){
			case 'slider':
				if (!element.value){
					this.error(this.questions[page][i].text+' is required.',document.getElementById('slider-'+i),this.questions[page][i].id,false);
				}
			break;
			case 'password':
			case 'text':
			case 'location':
    			if (!element.value){
					this.error(this.questions[page][i].text+' is required.',element,this.questions[page][i].id,false);
				}
            break;
			case 'select':
				if (!element.value){
					this.error(this.questions[page][i].text+' is required.',document.getElementById('container'+i),this.questions[page][i].id,false);
				}
			break;
			case 'radio':
				//Standard Drupal radios have no Ids
				var element = form[i];
				if (!this.checkNodeList(element)){
					this.error(this.questions[page][i].text+' is required.',document.getElementById('group-'+i),this.questions[page][i].id,false);
				}
			break;
			case 'location-specific':
				var element = form[i];
				if (!this.checkNodeList(element)){
					this.error(this.questions[page][i].text+' is required.',document.getElementById('group-'+i),this.questions[page][i].id,false);
				}
				var locationElement=form['other-'+i];
				if (!locationElement.value){
					this.error('A suburb or postcode is required for "'+this.questions[page][i].text+'".',locationElement,this.questions[page][i].id,true);
				}
			break;
			case 'location-multiple':
				var selected=false;
				for (var x in this.questions[page][i].options){
					var optionId=this.questions[page][i].options[x].id;
					if (document.getElementById(fieldPrefix+optionId).checked){
						selected=true;
						break;
					}
				}
				if (!selected){
					this.error(this.questions[page][i].text+' is required.',document.getElementById('group-'+i),this.questions[page][i].id,false);
				}
			break;
			case 'multi-multi':
				var selected=false;
				for (var x in this.questions[page][i].options){
					var optionId=this.questions[page][i].options[x].id;
					if (document.getElementById(fieldPrefix+optionId).checked){
						selected=true;
						break;
					}
				}
				
				if (!selected){
					this.error(this.questions[page][i].text+' is required.',document.getElementById('group-'+i),this.questions[page][i].id,false);
				}
			break;
			
			case 'checkbox':
				var selected=false;
				for (var x in this.questions[page][i].options){
					var optionId=this.questions[page][i].options[x].id;
					if (document.getElementById(fieldPrefix+i+'-'+optionId).checked){
						selected=true;
						break;
					}
				}
				
				if (!selected){
					this.error(this.questions[page][i].text+' is required.',document.getElementById('group-'+i),this.questions[page][i].id,false);
				}
			break;
			default:
				//alert(this.questions[page][i].type);
				//return false;
			break;
		}
	}
	
	
	//Check Multi-Multi
	/*var multiMulti=LepRegistration.getQuestionsByType('multi-multi',page);
	for (var i in multiMulti){
		for (var x in multiMulti[i].options){
			var selectElement=document.getElementById('multi-'+optionId);
			if (selectElement==null){
				continue;
			}
			var optionId=multiMulti[i].options[x].id;
			if (document.getElementById(fieldPrefix+optionId).checked
				&& selectElement.disabled==false 
				&& !document.getElementById('multi-'+optionId).value){
				this.error(this.questions[page][multiMulti[i].id].text+' is required.',document.getElementById('multi-'+optionId));
			}
		}	
	}*/

	//Location-multiple check
	//For each selected option type check that a location has been entered
	/*var locationMulti=LepRegistration.getQuestionsByType('location-multiple',page);
	for (var i in locationMulti){
		for (var x in locationMulti[i].options){
			var optionId=locationMulti[i].options[x].id;
			if (document.getElementById(fieldPrefix+optionId).checked
				&& !document.getElementById('other-'+optionId).value){
				this.error('A location for each selected option is required for "'+this.questions[page][locationMulti[i].id].text+'".',document.getElementById('other-'+optionId));
			}
		}	
	}*/
	
	//Check "Other" fields
	/*for (var i=0;i<this.additionalCheck.other.length;i++){
		var questionCode=this.additionalCheck.other[i].question;
		var optionCode=this.additionalCheck.other[i].option;
		
		if (this.questions[page][questionCode].type=='checkbox'){
			var optionElement=document.getElementById(fieldPrefix+questionCode+'-'+optionCode);
			var otherElement=document.getElementById('other-'+optionCode);
			if (optionElement.checked && !otherElement.value){
				this.error('Please specify the exact details for "'+this.questions[page][questionCode].text+'".',otherElement,questionCode,true);
			}
		}else if (this.questions[page][questionCode].type=='radio'){
			var optionElement=document.getElementById(fieldPrefix+optionCode);
			var otherElement=document.getElementById('other-'+optionCode);
			if (optionElement.checked && !otherElement.value){
				this.error('Please specify the exact details for "'+this.questions[page][questionCode].text+'".',otherElement,questionCode,true);
			}
		}
	}*/
	
	//Check email fields
	var emailPattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	for (var i=0;i<this.additionalCheck.email.length;i++){
		var element = document.getElementById(fieldPrefix+this.additionalCheck.email[i]);
		if (!emailPattern.test(jQuery.trim(element.value)))
		{
		    this.error('Please enter a valid email address.',element,this.additionalCheck.email[i],true);
		}
	}
	
	//Check location fields
	for (var i=0;i<this.additionalCheck.location.length;i++){
	    //if (document.getElementById('container'+this.additionalCheck.location[i]).style.display=='none')continue;
 	    var element = document.getElementById(fieldPrefix+this.additionalCheck.location[i]);
 	    if (!element){
 	        element = document.getElementById('other-'+this.additionalCheck.location[i]);
 	    }
		if (element && element.value){
			LepRegistration.checkLocation(element.value,false,function(){
							LepRegistration.error('Please enter a valid suburb or postcode.',element,LepRegistration.additionalCheck.location[i],true);
			});
		}
	}

	//Check password against registered email
	if (LepRegistration.doAccountCheck)
	{
        var emailField=null;    
        var passwordField=null;    
   	    if (this.additionalCheck.password.length>0)
   	    {
   	       var passwordField=document.getElementById(fieldPrefix+this.additionalCheck.password[0]);	    
   	       //this.currentElement=fieldPrefix+this.additionalCheck.password[0];
   	       this.currentElement=passwordField;
           this.currentQuestionCode=this.additionalCheck.password[0];
           
    	   if (passwordField.value && this.additionalCheck.email.length>0)
    	   {
               var emailField = document.getElementById(fieldPrefix+this.additionalCheck.email[0]);	    
               this.currentText=emailField.value;
    	   }
   	    }
	    
	    if (emailField && passwordField)
	    {
	        $.ajax({
	   			type: "GET",
	   			dataType: 'json',
	   			async: false,
	   			url: LepRegistration.jsonService+'?task=CheckAccount&email='+emailField.value+'&password='+passwordField.value,
	   			error: function(){
	   				//Let the server side handle CheckAccount errors
	   			},
	   			success: function(response)
	   			         {
	   			             if (response.result!='Ok')
	   			             {
	   			                 LepRegistration.error('Your password does not match the password registered with the email address "'+LepRegistration.currentText+'".',LepRegistration.currentElement,LepRegistration.currentQuestionCode,true);
	   			             }
   						}
			});	    
	    }
	}
	
	
    //Check Terms and Conditions
	if (this.additionalCheck.tandc)
	{
	    var tandc = document.getElementById('edit-tandc');
	    if (!tandc.checked)
	    {
         this.error('Please indicate that you have accepted the terms and conditions.',document.getElementById('containerTandc'),'Tandc');	        
	    }
	}
	
	
	//if (this.errorMessage.length){
	if (this.errorElements.length){
	
		/*var sp1 = document.createElement('div');
		sp1.id='lep_error_messages';
		sp1.className='messages error';
		sp1.innerHTML='<ul><li>'+this.errorMessage.join('</li><li>')+'</li></ul>';
		container.insertBefore(sp1,container.childNodes[0]);
		alert('Please correct the following errors.'+"\n*"+this.errorMessage.join("\n*"));
		*/
		//alert(this.errorElements[0]);
		//document.getElementById(this.errorElements[0]).focus();
		
		alert('Please correct the errors on the form.');
		//alert(this.errorElements[0]);
		try{ 
		  $.scrollTo( $("#"+this.errorElements[0]), 200);
		}catch(err){}
  		return false;
	}
	
	if (finished){
	    this.trackSuccess('Submit Form');
	}
	return true;
}
/**
*   Tracks success events
*/
LepRegistration.trackSuccess = function(msg){
    if (window.s!==undefined && window.s.sendFormEvent!==undefined)
	{
        s.sendFormEvent('s', s.pageName, 'registration', msg);
	}
}
/**
* Validates a location against LEP
*/
LepRegistration.checkLocation = function(location,isAsync,errorFunc){
	location = jQuery.trim(location);
	if (location!=''){
		if (LepRegistration.checkedLocations[location]==null)
		{
			$.ajax({
	   			type: "GET",
	   			dataType: 'json',
	   			async: isAsync,
	   			url: LepRegistration.jsonService+'?task=ValidatePostcode&location='+location,
	   			error: function(){
	   				if (errorFunc!=null){
     					errorFunc();
     				}
	   			},
	   			success: function(response){
   								if (!response || !response.result || response.result!='Ok'){
     								LepRegistration.checkedLocations[location]=false;
     								if (errorFunc!=null){
     									errorFunc();
     								}
   								}else{
   									LepRegistration.checkedLocations[location]=true;
   								}
   							}
			});
			
		}
		else if (LepRegistration.checkedLocations[location]===false && errorFunc!=null)
		{
			errorFunc();
		}
	}
}
/**
*	Resets all form errors
*/
LepRegistration.resetErrors = function(){
	//reset the error container
	this.errorMessage = new Array();
	/*
	for (var i=0;i<this.errorElements.length;i++){
		$('#'+this.errorElements[i]).attr({'class':$('#'+this.errorElements[i]).attr('class').replace(/ error/,'')});
	}*/
	
	
    /*$('span.error-image').each(function(){
        $('#'+this.id).remove();
    });	*/
    $('div.custom-error').each(function(){
        this.innerHTML='';
    });
    
    this.showRequiredText();
	this.errorElements = new Array();

}
/**
*	Sets a form error
*/
LepRegistration.error = function(msg,element,questionCode,useCustomError){
	//this.errorMessage.push(msg);
	if (element && this.inArray(element.id,this.errorElements)===false){
        if (useCustomError)
        {
            $('#container'+questionCode).find("div#customError"+questionCode).each(function(){
                this.innerHTML=msg;
            });	
        }
        else
        {
            $('#container'+questionCode).find("span.form-required").each(function(){
                this.innerHTML='<span class="please-complete"></span>';
            });	
        }
        this.errorElements.push('container'+questionCode);

        
		//element.className+=' error';
		//this.errorElements.push(element.id);
		
		if (window.s!==undefined && window.s.sendFormEvent!==undefined)
		{
		    s.sendFormEvent('e', s.pageName, 'registration', msg);
		}
	}

}
/**
* Add to the "selected options" list
*/
LepRegistration.addSelectedOption = function(optionCode)
{
   if (!this.inArray(optionCode,this.selectedOptions))
   {
      this.selectedOptions.push(optionCode);
   }
}
/**
* Sets the "parent" options that have been selected
* 
* Options which aren't parents and therefore do not alter the form flow
* are not included in this list
*/
LepRegistration.toggleSelectedOptions = function(optionCode,page,state)
{
    if (state=='on')
    {
        this.addSelectedOption(optionCode);
    }
    else
    {
        //Remove unselected options from the selected options list as well
        //as the descendents
        for (var i in this.selectedOptions)
        {
            if (this.selectedOptions[i]==optionCode)
            {
                this.selectedOptions.splice(i,1);   
                var optionChildQuestions=this.optionChildren[optionCode];
		        //This option is not a parent
		        if (!optionChildQuestions)continue;
		        for (var x in optionChildQuestions)
		        {
	               var childQuestionCode=optionChildQuestions[x];          
	               for (var z in this.questions[page][childQuestionCode].options)
	               {
	                   var childOptionCode=this.questions[page][childQuestionCode].options[z].id;
	                   //This child option is not a parent
		               if (!this.optionChildren[childOptionCode])continue;
	                   this.toggleSelectedOptions(childOptionCode,page,'off');
	               }
    	        }
		        
            }
        }        
    }
}
/**
* Sets the visibility of a question
*/
LepRegistration.toggleQuestion	= function(id,page,visibile)
{
    var divElement = document.getElementById('container'+id);
    var codes = $('#edit-hidden-questions').val().split(',');
    if (visibile)
    {
        this.displayedQuestions[id]=true;
        //$('#container'+id).css('display','block'); 
        divElement.style.display='block';
		var hiddenQuestions = new Array();
		for (var x=0;x<codes.length;x++){
			if (codes[x]!=id){
				hiddenQuestions.push(codes[x]);
			}
		}
		$('#edit-hidden-questions').val(hiddenQuestions.join(','));
    }
    else
    {
        divElement.style.display='none';
        codes.push(id);
        $('#edit-hidden-questions').val(codes.join(','));
    }
}

LepRegistration.ctPlayback = function(formid,clickedElName,page,selectedQue){
	LepRegistration.toggle(document.forms[formid].elements[clickedElName],document.getElementById(formid),page,selectedQue);
}

/**
* Hide/Show child questions	
*
* Radio button,checkboxes and single selects are the only elements
* which should be triggering this event
*/
LepRegistration.toggle	= function(clickedElement,form,page,selectedQuestion){

    if(!IsInPlayback()){
		if (typeof ClickTaleExec == "function")
		{
			var clickTaleStr="LepRegistration.ctPlayback('"+form.id+"','"+clickedElement.name+"','"+page+"','"+selectedQuestion+"')";
			ClickTaleExec(clickTaleStr);
		}
    }
    
    
    //Reset question display
    $('#edit-hidden-questions').val('');
    this.displayedQuestions=new Array();
    for (var i in this.questions[page])
    {
        //If a question has no parents, then it should always be displayed
        if (this.questions[page][i].hasParents)
        {
           this.toggleQuestion(i,page,false); 
        }
    }
    
    
	var question = this.questions[page][selectedQuestion];
	//For each of the question's options set the selected options
	for (var i=0;i<question.options.length;i++)
	{
		var optionChildQuestions=this.optionChildren[question.options[i].id];
		//This option is not a parent
		if (!optionChildQuestions)continue;
		
		var checked = false;
		if (question.type=='radio' || question.type=='location-specific'){
			var formElement = form[selectedQuestion];
			var optionValue = question.options[i].id;
			for (var z=0;z<formElement.length;z++){
				if (formElement[z].value==question.options[i].id){
					checked=formElement[z].checked?true:false;
				}
			}				
		}else if (question.type=='select'){	
			if (clickedElement.value==question.options[i].id)
			{
			    checked=true;
			}
			optionValue=question.options[i].id;
		}else{
			var optionValue = clickedElement.value;
			checked = clickedElement.checked;
		}
		
		if (checked)
		{
		    this.toggleSelectedOptions(optionValue,page,'on');
		}
		else
		{
		    this.toggleSelectedOptions(optionValue,page,'off');
		}
	}
	
	//alert(this.selectedOptions);
    // Now set the visibility of the questions
	for (var i in this.selectedOptions)
	{
	    
	    var currentQuestion=LepRegistration.optionQuestion[this.selectedOptions[i]];
	    this.toggleQuestion(currentQuestion,page,true);
	    var optionChildQuestions=this.optionChildren[this.selectedOptions[i]];
		//This option is not a parent
		if (!optionChildQuestions)continue;
		
		for (var x=0;x<optionChildQuestions.length;x++)
		{
		    this.toggleQuestion(optionChildQuestions[x],page,true);
		}
	}

    
	//Reset the values of any elements which are not displayed
	/*
    var fieldPrefix = 'edit-';	
	for (var i in this.questions[page])
    {
    	if (!this.displayedQuestions[i])
    	{
    	    if (this.questions[page][i].type=='radio' || this.questions[page][i].type=='checkbox')
    	    {
                  var formEl=$("input[name="+i+"]");  	        
                  for (var i=0;i<formEl.length;i++){
					formEl[i].checked=false;
				 }
    	    }
    	    else
    	    {
        	     var formEl=$('#'+fieldPrefix+i);  	        
        	     if (formEl){
        	       formEl.val('');
        	     }
    	    }
    	}
    }
    */
	
	this.toggleContinue();
}

function IsInPlayback(){
    try { return parent && parent.WebPlayer; }
    catch(e) { return false; }
}
