var MG_AD_RULES = {};

var mg_rule_timeout;
function delayedShowByRule(adId, questionId, keycode){
    var isClickable = false;
    try{
        if(keycode.type=='radio' || keycode.type=='checkbox' || keycode.type=='hidden')
            isClickable = true;
    }catch(err){}
    if(isClickable || keycode == 8 || keycode == 32 || keycode == 46 
        ||(37 <= keycode && keycode <= 40) // ARROW KEYS - for select
        ||(48 <= keycode && keycode <= 57)
        ||(65 <= keycode && keycode <= 90)){
        clearTimeout(mg_rule_timeout);
        mg_rule_timeout=setTimeout("showByRule('"+adId+"','"+questionId+"');",500);
    }
    return true;
}


function showByRule(adId, questionId){
    clearTimeout(mg_rule_timeout);
    mg_validate(adId, questionId);
    //if(typeof console != 'undefined') console.log("showByRule(adId:"+adId+",questionId:"+questionId+")");
    
    if (MG_AD_RULES[adId].questions[questionId].questions_that_merge_with_me != null){
        for (var i=0; i < MG_AD_RULES[adId].questions[questionId].questions_that_merge_with_me.length; i++){    
              mg_rule_foreach(adId, MG_AD_RULES[adId].questions[questionId].questions_that_merge_with_me[i]);
        }
    }
    
    for(var t in MG_AD_RULES[adId].questions){        
        try{
          var question = MG_AD_RULES[adId].questions[t];
          var shouldShowQuestion = true;
          var questionIdStr = question.question_id;
          if (question.display_conditions){
              for(var i=0; i < question.display_conditions.length; i++){
                  var rule = question.display_conditions[i];
                  shouldShowQuestion = shouldShowQuestion && mg_rule_matches(rule);      
              }
          }        

          if(shouldShowQuestion){            
              if (document.getElementById('question_wrapper_'+questionIdStr).style.display == 'none')
              {
                    document.getElementById('question_wrapper_'+questionIdStr).style.display='';
              }
          }
          else{
              if (document.getElementById('question_wrapper_'+questionIdStr).style.display != 'none')
              {
                  var node = document.getElementById('question_wrapper_'+questionIdStr);
                  nullNodes(node);
              }
              document.getElementById('question_wrapper_'+questionIdStr).style.display='none';                        
          }
        }
        catch (e)
        {
            
        }
    }        
    
}

function nullNodes(node){
    if (node){
        
        var inputs = node.getElementsByTagName("input")
        for(var i=0; i<inputs.length; i++)
        {         
            inputs[i].value = '';                         
        }
        inputs = node.getElementsByTagName("select")
        for(var i=0; i<inputs.length; i++)
        {
            inputs[i].options[0].selected = true;            
        }
      
    }
}

function mg_rule_matches(rule){
    var questionId = rule.question_id;
    var condition = rule.condition;
    var requiredObject = rule.value;

    if("!NULL" == condition){
        var answerValue = "";
        var givenValue = mg_rule_givenAnswer(questionId, "default_answer");
        for(var i = 0; i < givenValue.length; i++){
            answerValue += givenValue[i];
        }
        //if(typeof console != 'undefined') console.log("::!NULL:: givenValue:"+answerValue);
        if("" != answerValue)
            return true;
        return false;
    } 

    var numTrue = 0;
    var maxTrue = 0;
    for(part in  requiredObject){
        var requiredValue = requiredObject[part];
        var givenValue = mg_rule_givenAnswer(questionId, part);
        maxTrue++;
//        if(console) console.log("part:"+part+"; requiredValue:"+requiredValue+" ::"+condition+":: givenValue:"+givenValue);
        if("==" == condition) {
            if(mg_rule_equals(requiredValue, givenValue))
                numTrue++;
        } else if("!=" == condition) {
            if(!mg_rule_equals(requiredValue, givenValue))
                return true;
        } else if("<" == condition) {
            if(mg_rule_compare(requiredValue, givenValue) < 0)
                return true;
        } else if(">" == condition) {
            if(mg_rule_compare(requiredValue, givenValue) > 0)
                return true;
        } else if("IN" == condition) {
            if(mg_rule_contains(requiredValue, givenValue))
                return true;
        }
    }
    if("==" == condition && numTrue == maxTrue)
        // all parts are equal
        return true;
    return false;
}

function mg_rule_givenAnswer(questionId, part){
//    console.log("Looking for "+questionId);
    var partString = "";
    if(part != null && part != "default_answer" && part != "default_answer")
        partString = "_"+part;
    var givenAnswerObj = Array();
    if(part == "default_answer"){
        var qWrapper = document.getElementById("question_wrapper_"+questionId);
        var inputs = qWrapper.getElementsByTagName("input")
        for(var i=0; i<inputs.length; i++)
            givenAnswerObj.push(inputs[i]);
        inputs = qWrapper.getElementsByTagName("select")
        for(var i=0; i<inputs.length; i++)
            givenAnswerObj.push(inputs[i]);
        inputs = qWrapper.getElementsByTagName("textarea")
        for(var i=0; i<inputs.length; i++)
            givenAnswerObj.push(inputs[i]);
    } else {
        givenAnswerObj = document.getElementsByName(questionId+partString);
    }
    var givenAnswer = new Array();
    for(var i = 0; i < givenAnswerObj.length; i++){
        if(givenAnswerObj[i].value == "")
            continue;
        if(givenAnswerObj[i].type == "radio" || givenAnswerObj[i].type == "checkbox")
            if(!givenAnswerObj[i].checked)
                continue;
        givenAnswer.push(givenAnswerObj[i].value);
    }
//    if(console) console.log("GIVEN ANSWER:"+givenAnswer)
    return givenAnswer;
}
      
function mg_rule_equals(requiredValue, givenValue){
//    if(console) console.log("CHECK "+requiredValue+" == "+givenValue)
    if(String(givenValue).match("^"+requiredValue+"$")){
//    if( givenValue == requiredValue ){
        return true;
    }
    return false;
}
    
// -1 if the given answer is less than the required, 
// 1 if the given answer is greater than the required,
// 0 if the values are equal or ther was an error.
function mg_rule_compare(requiredValue, givenValue){
    if(!isNaN(Number(requiredValue))){
        if(isNaN(Number(givenValue)))
            return 0;
        var requiredDouble = Number(requiredValue);
        var givenDouble = Number(givenValue);
        var differenceDouble = requiredDouble - givenDouble;
        if(differenceDouble > 0)
            return 1;
        else if(differenceDouble < 0)
            return -1;
        else
            return 0;
    } else {
        if(requiredValue > givenValue)
            return 1;
        else if(requiredValue < givenValue)
            return -1;
        else
            return 0;
    }
}
    
function mg_rule_contains(requiredValue, givenValue){
    if((""+givenValue).indexOf(requiredValue+"")>=0 ||  (givenValue.length > 0 && (""+givenValue[0]).indexOf(requiredValue[0]+"")>=0) )
        return true;
    return false;
}

function mg_rule_foreach(adId, toId){
    //console.log("mg_rule_foreach(adId:"+adId+",toId:"+toId+")");
    if (MG_AD_RULES[adId].questions[toId].question_string != null){

      var questionHTML = MG_AD_RULES[adId].questions[toId].question_string;
      //var QUESTION_ID_REGEX = /(?:<|(?:&lt;))merge\s+question=(?:(?:'|"))([1-9][0-9]*)(?:(?:'|"))(?:\s+part=(?:(?:'))([a-zA-z0-9\s]*)(?:(?:')))?\s*\/(?:>|(?:&gt;))/i;
      var QUESTION_ID_REGEX = /%%([1-9][0-9]*)(?:\.([a-zA-z0-9\s]*))?%%/i;
      
      var leftContent = Array();
      var midContent = Array();
      while((result = QUESTION_ID_REGEX.exec(questionHTML)) != null){
          leftContent.push(RegExp.leftContext);
          questionHTML = RegExp.rightContext;

          var fromId = result[1];
          var part = "default_answer";
          if(result.length>2 && result[2] != null)
              part = result[2];
          if(part == "")
              part = "default_answer";

          var num = leftContent.length-1;

          midContent[num] = mg_rule_givenAnswer(ORDER[adId][fromId], part);
          if(midContent[num].length == 0)
              midContent[num].push(result[0]);
      }
      var allAnswers = Array();
      var allParts = Array();
      allAnswers[0] = Array();
      allParts[0] = Array();
      allAnswers[0].push("");
      allParts[0].push("");
      for(var i = 0; i< leftContent.length; i++){
          allAnswers[i+1] = Array();
          allParts[i+1] = Array();
          for(var j=0; j<allAnswers[i].length; j++){
              for(var k = 0; k<midContent[i].length; k++){
                  allAnswers[i+1].push(allAnswers[i][j] + leftContent[i] + midContent[i][k]);
                  allParts[i+1].push(allParts[i][j]+"_"+midContent[i][k]);
              }
          }
      }
      var cleanQuestion = Array();
      for(var i=0; i<allAnswers[allAnswers.length-1].length; i++){
          var question = allAnswers[allAnswers.length-1][i]+questionHTML;
          if((result = QUESTION_ID_REGEX.exec(question)) != null)
              return false;
          var questionString = "";
          var NAME_REGEX = /name\s?=\s?['"]([1-9][0-9]*_[1-9][0-9]*[.^'"]*)['"]/i
          while((result = NAME_REGEX.exec(question)) != null){
              question = RegExp.rightContext;
              questionString += RegExp.leftContext + "name='"+ result[1] + allParts[allParts.length-1][i] +"'"
          }
          questionString += question;
          cleanQuestion.push(questionString);
      }


      // Attatch to DOM
      while(document.getElementById('question_wrapper_'+toId).childNodes[0]) {
          document.getElementById('question_wrapper_'+toId).removeChild(document.getElementById('question_wrapper_'+toId).childNodes[0]);
      }
      for(var i=0; i<cleanQuestion.length; i++){
          var questionWrapper = document.createElement("div");
          questionWrapper.innerHTML = cleanQuestion[i];
          document.getElementById('question_wrapper_'+toId).appendChild(questionWrapper);
      }
    }
    return true;
}


function countEntries(amount)
{
	var toAdd = parseInt(amount);
	var pointsCounter = document.getElementById('points_counter');
	var pointsCounter2 = document.getElementById('local_comp_points_counter');

	if (pointsCounter != null)
	{
		var oldValue = parseInt(pointsCounter.innerHTML);
		pointsCounter.innerHTML = oldValue+toAdd;	
	}
	if (pointsCounter2 != null)
	{
		var oldValue2 = parseInt(pointsCounter2.innerHTML.split(" ")[0]);
		pointsCounter2.innerHTML = (oldValue2 + toAdd) + " entries";
	}
}

                 
function getRegexForValidationType(validationType)
{
    if (validationType == null || validationType == "none")
    {
        return null;
    }
    if (validationType == "uk_telephone")
    {
      return "^(?=01|02|03|05|070|071|072|073|074|075|07624|077|078|079)(?!.*([0-9])\\1{5,11})(?!.*(12345|23456|34567|45678|56789|67890|09876|98765|87654|76543|65432|54321))[0-9]{10,11}$";
    }
    if (validationType == "uk_mobile")
    {
        return "^(?=070|071|072|073|074|075|07624|077|078|079)(?!.*([0-9])\\1{5,11})(?!.*(12345|23456|34567|45678|56789|67890|09876|98765|87654|76543|65432|54321))[0-9]{11}$";
    }
    if (validationType == "uk_landline")
    {
        return "^(?=01|02|03|05)(?!.*([0-9])\\1{5,11})(?!.*(12345|23456|34567|45678|56789|67890|09876|98765|87654|76543|65432|54321))[0-9]{10,11}$";
    }
    if (validationType == "email")
    {
        return "^([0-9a-zA-Z]+[-\\._+&])*[0-9a-zA-Z-\\._+&]+@([-0-9a-zA-Z]+[\\.])+[a-zA-Z]{2,6}$";
    }
    if (validationType == "letters_and_numbers")
    {
        return "^[\\w]+$";
    }
    if (validationType == "letters")
    {
        return "^[a-zA-Z]+$";
    }
    if (validationType == "numbers")
    {
        return "^[0-9]+$";
    }
    if (validationType == "uk_postcode")
    {
        return "^(BFPO[ c\\/o]?[ ]?[0-9]{1,4}|GIR[ ]?0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])[ ]?[0-9][ABD-HJLNP-UW-Z]{2})$";
    }
    return null;
}

function is_object_visible(obj){
	if (typeof obj.style != "undefined" && obj.style.display == 'none') {
		return false;
	}
	while(obj=obj.parentNode ){
		if (typeof obj.style != "undefined" && obj.style.display == 'none') {
			return false;
		}
	}
	return true;
}

function can_question_be_validated(questionId){
	if (document.getElementById('question_wrapper_'+questionId).style.display == 'none') {
		return false;
	} 
	return true;
}

function mg_validateDate(calObj, input){
	calObj.date = Calendar.parseDate(input, false);
	if (calObj.minDate && calObj.date < calObj.minDate){
		return false;
	}
	if (calObj.maxDate && calObj.date > calObj.maxDate){
		return false;
	}
	return true;
}

function mg_validate(adId, questionId){
    try{
        var validationType = MG_AD_RULES[adId].questions[questionId].validation;
        var minCharacters = (MG_AD_RULES[adId].questions[questionId].min_characters != null)? MG_AD_RULES[adId].questions[questionId].min_characters : 0;
        var maxCharacters = (MG_AD_RULES[adId].questions[questionId].max_characters != null)? MG_AD_RULES[adId].questions[questionId].max_characters : 0;
        var minValue = (MG_AD_RULES[adId].questions[questionId].min_value != null)? MG_AD_RULES[adId].questions[questionId].min_value : 0;
        var maxValue = (MG_AD_RULES[adId].questions[questionId].max_value != null)? MG_AD_RULES[adId].questions[questionId].max_value : 0;
        var passwdVerify = MG_AD_RULES[adId].questions[questionId].passwdVerify;
        var validation = getRegexForValidationType(validationType);
        var regexp = new RegExp(validation);
        var inputsI = document.getElementById("question_wrapper_"+questionId).getElementsByTagName("input");
        var inputsS = document.getElementById("question_wrapper_"+questionId).getElementsByTagName("select");
        var inputsT = document.getElementById("question_wrapper_"+questionId).getElementsByTagName("textarea");
        var inputs = Array();
        for(var i=0; i<inputsI.length; i++)
            if (inputsI[i].type == "hidden") {
            	if (inputsI[i].value !="") {
            		inputs.push(inputsI[i].value);
            	}
            } else if((inputsI[i].type != "radio" && inputsI[i].type != "checkbox") || inputsI[i].checked) {
       			inputs.push(inputsI[i].value);
            } 
		for(var i=0; i<inputsS.length; i++)
			inputs.push(inputsS[i].value);
		for(var i=0; i<inputsT.length; i++)
			inputs.push(inputsT[i].value);
        var required = MG_AD_RULES[adId].questions[questionId].required;

        if (required && inputs.length == 0) {
               	MG_AD_RULES[adId].validation.errors.push(questionId);
               	return false;
        }

        for(var i=0; i < inputs.length; i++){
            if(inputs[i] != "" && typeof validation != 'undefined' && validation && !regexp.test(inputs[i])){
                MG_AD_RULES[adId].validation.errors.push(questionId);
            } else if (inputs[i].length < minCharacters || (maxCharacters != 0 && inputs[i].length > maxCharacters) ) {
               	MG_AD_RULES[adId].validation.errors.push(questionId);
            } else if (inputs[i] < minValue || (maxValue != 0 && inputs[i] > maxValue) ) {
               	MG_AD_RULES[adId].validation.errors.push(questionId);
            } else if (required && inputs[i] == "") {
               	MG_AD_RULES[adId].validation.errors.push(questionId);
            } else if (passwdVerify!=null && typeof passwdVerify != 'undefined' && passwdVerify.value!=inputs[i]){
               	MG_AD_RULES[adId].validation.errors.push(questionId);
            } else if (validationType=="calendar" && !mg_validateDate(eval("cal_"+questionId),inputs[i])){
               	MG_AD_RULES[adId].validation.errors.push(questionId);
            } else {
                var wrapper = document.getElementById("question_wrapper_"+questionId);
                var input = wrapper.getElementsByTagName("input")[0];
                if(typeof input == "undefined")
                    input = wrapper.getElementsByTagName("select")[0]
                if(typeof input == "undefined")
                    input = wrapper.getElementsByTagName("textarea")[0]

			    if (input.type != null && (input.type == "text" || input.type.indexOf("select") >= 0 || input.type == "textarea")) {
                	input.style.backgroundColor="#FFFFFF";
                }
                if (input.type == "radio" || input.type == "checkbox" || input.type == "hidden") {
                	input.parentNode.parentNode.style.backgroundColor="transparent";
                }
                //not sure about this - try replacing
                var length = MG_AD_RULES[adId].validation.errors.length;
                for(var j=0; j<MG_AD_RULES[adId].validation.errors.length; j++){
                    if(MG_AD_RULES[adId].validation.errors[j] == questionId){
                        MG_AD_RULES[adId].validation.errors.splice(j,1);
                        if(length != MG_AD_RULES[adId].validation.errors.length){
                            length = MG_AD_RULES[adId].validation.errors.length;
                            j--;
                        }
                    }
                }
            }
        }
    }catch(err){
    	if(typeof console != 'undefined') console.log("ERROR:"+err.message);
    }
}

function mg_offer_required(){
	if (document.getElementById("mg_ad").value == "") {
		alert("Please ensure you have checked into at least one offer");
		return false;
	} else {
		return true;
	}
}

function mg_required(){
	try{
	    if (document.getElementById("mg_ad") == null || document.getElementById("mg_ad").value == "") {
    		return true;
    	}
        var adIds = document.getElementById("mg_ad").value.split(",");
        for(var adNum=0; adNum<adIds.length; adNum++){
        	// don't have an easily accessible list of questionIds so will iterate through the rules instead;
        	if (typeof MG_AD_RULES != 'undefined' && typeof MG_AD_RULES[adIds[adNum]] != 'undefined' && typeof MG_AD_RULES[adIds[adNum]].validation != 'undefined') {
	           	var qList = new Array();
                for (var questionId in MG_AD_RULES[adIds[adNum]].questions){
                    qList.push(questionId);
                }                
		       	// now perform the validation
		       	for (var j=0; j<qList.length; j++) {
		       		if (can_question_be_validated(qList[j])) {
						mg_validate(adIds[adNum],qList[j]);
					}
				}
				if (MG_AD_RULES[adIds[adNum]].validation.errors != null) {
		            for(var qNum=0; qNum < MG_AD_RULES[adIds[adNum]].validation.errors.length; qNum++){
		            	//check if question is still visible - remove from errors if not
		            	if (can_question_be_validated(MG_AD_RULES[adIds[adNum]].validation.errors[qNum])){
			                alert("Please ensure you have correctly answered all the questions for the offers you have selected.\n\nProblems are highlighted in red.");
			                var wrapper = document.getElementById("question_wrapper_"+MG_AD_RULES[adIds[adNum]].validation.errors[qNum]);
			                var input = wrapper.getElementsByTagName("input")[0];
			                if(typeof input == "undefined") {
			                    input = wrapper.getElementsByTagName("select")[0];
			                }
			                if(typeof input == "undefined") {
			                    input = wrapper.getElementsByTagName("textarea")[0];
			                }
			                if (input.type != null && input.type == "text" || input.type.indexOf("select") >= 0 || input.type == "textarea") {
			                	input.style.backgroundColor="#FF9999";
			                }
			                if (input.type == "radio" || input.type == "checkbox" || input.type == "hidden") {
			                	input.parentNode.parentNode.style.backgroundColor="#FF9999";
			                }
			                try {
			                	input.focus();
			                } catch(err) {
			                	// field is hidden
				                try {
				                	window.scrollTo(0,findPos(document.getElementById("checkbox_img_"+ adIds[adNum]))[1]-20);
			                	} catch(err2) { }
			                }
			                return false;
			            } else {
			            	//remove from the error array as is no longer visible (ie. required)
			            	MG_AD_RULES[adIds[adNum]].validation.errors.splice(qNum,0);
			            }
		            }
		        }
	        }
        }
    }catch(err){
    	if(typeof console != 'undefined') console.log("mg_required error: "+err.message);
    }
    return true;
}

var MG_Ads = {
    toggleAd: function(ad_id, entries){
        try{
            if (document.getElementById("mg_ad")) {
                var tickObj = document.getElementById("checkbox_img_"+ad_id);
                var wrapperId = "mg_adwrapper_"+ad_id;
                var wrapperObj = document.getElementById(wrapperId);
                var ads = new Array();
                entries = parseInt(entries);
                if (document.getElementById("mg_ad").value.length > 0) { 
                    ads = document.getElementById("mg_ad").value.split(',');
                }
                var exists = false;
                for(var i=0; i < ads.length; i++){
                    if(ads[i] == ad_id) {
                        ads.splice(i,1);
                        if (tickObj!=null) tickObj.src = "/images/checkbox_unchecked.gif";
                        if (wrapperObj!=null) wrapperObj.className = "";
                        exists=true;
                        countEntries(-1*entries);
                    }
                }
                if(!exists) {
                    ads.push(ad_id);
                    if (tickObj!=null) tickObj.src = "/images/checkbox_checked.png";
                    if (wrapperObj!=null) wrapperObj.className = "opted-into";
                    countEntries(entries);
                }
                document.getElementById("mg_ad").value = ads.toString();
            }
        }catch(e){
            /*if(console){
                console.log("ERROR:")
                console.log(e);
            }*/
        }
    }
}

