/**********************************************************/
/* VOA - VALUATION OFFICE AUTHORITY                       */
/**********************************************************/
/*                                                        */
/* FILENAME:			site_ajax.js                      */
/*                                                        */
/* CREATED:				10th June 2009                    */
/*                                                        */
/* MODIFIED:		    05th August 2009                  */
/*                                                        */
/* AUTHOR: 				IOKO (David Yarham)               */
/*                                                        */
/* LAST MODIFIER: 		IOKO (Lewis Leighton)	          */
/*                                                        */
/**********************************************************/

function removeEmptyBoxes()
{
	$("div.content").each(function(){
		var thisChildren = $(this).children();
		if(thisChildren.length == 0)
		{
			$(this).parent('div.box').hide();
		}

	})
}

function setupModeSwitcher() {
	$('.tab-mode').colorbox({
		overlayClose: false,
		preventClose: true,
		href: "/rli/switch/agent"
	});
	$('.agent .tab-mode').colorbox({
		overlayClose: false,
		preventClose: true,
		href: "/rli/switch/normal"
	});
}

function setupVideoBoxes() {
	$("a[href*='.flv']").each(function (i) {
		if ($(this).attr("title") === "") {
			$(this).attr("title", "Video");
		}
		$(this).colorbox({
			speed: 350
		});
	});
}

function setupPages() {
	if ($("body.propertySearchResults").length > 0) {
		/**********************************************************/
		/* Search by property Form Switcher                       */
		/**********************************************************/
		//$("#swap_search_form").hide();
		$("#swap_search_instruction_2").hide();
		$(".ev_swap_search").click(function () {
			if ($("#swap_search_form").is(':hidden')) {
				$("#swap_search_information").fadeOut(300, function () {
					$("#swap_search_form").slideDown(300);
				});
				$("#swap_search_instruction_1").fadeOut(300, function () {
					$("#swap_search_instruction_2").fadeIn(300);
				});
			}
			if ($("#swap_search_information").is(':hidden')) {
				$("#swap_search_form").slideUp(300, function () {
					$("#swap_search_information").fadeIn(300);
				});
				$("#swap_search_instruction_2").fadeOut(300, function () {
					$("#swap_search_instruction_1").fadeIn(300);
				});
			}
			return false;
		});
	}

	if ($("body.propertyResults").length > 0) {
		/**********************************************************/
		/* Add - Remove from Comparison list                      */
		/**********************************************************/
		$(".comparison-buttons").hide();
		$(".comparison-buttons .ev_remove-all").click(function () {
			$(".comparison-box .compare-list").remove();
			$(".comparison-box .ev_information").fadeIn(400);
			$(".comparison-buttons").slideUp(100);
			return false;
		});
		$(".data-table .add").click(function () {
			if ($(".comparison-box .compare-list li").length >= 5) {
				alert('Sorry, only 5 properties can be added to your Comparison List');
				return false;
			}
			if ($(".comparison-box .compare-list").length < 1) {
				//Create the List Container
				var compareListContainer = document.createElement('ul');
				$(compareListContainer).addClass("compare-list");
				$(compareListContainer).appendTo(".comparison-box");
			}
			if ($(".comparison-box .compare-list li").length === 0) {
				$(".comparison-box .ev_information").hide();
				$(".comparison-buttons").slideDown(100);
			}
			if ($(".comparison-box .compare-list").length > 0) {
				var BAR = $(this).parents('tr').find('.ev_bar').html();
				var ADDRESS = $(this).parents('tr').find('.ev_address').html();
				if (eval($(".comparison-box .compare-list li.BAR_" + BAR)).length >= 1) {
					alert('Sorry, you cannot add the same property to your Comparison List');
					return false;
				}
				//Create the List Item
				var propertyLi = document.createElement('li');
				$(propertyLi).addClass("BAR_" + BAR);
				//Create the Address Span
				var propertyAddress = document.createElement('span');
				$(propertyAddress).addClass("property");
				$(propertyAddress).html(ADDRESS);
				$(propertyAddress).appendTo(propertyLi);
				//Create Remove Button
				var propertyRemove = document.createElement('span');
				$(propertyRemove).addClass("remove");
				var propertyRemoveButton = document.createElement('a');
				$(propertyRemoveButton).attr("href", "/removebar/" + BAR);
				$(propertyRemoveButton).attr("title", "Remove from list");
				$(propertyRemoveButton).html("Remove");
				$(propertyRemoveButton).click(function () {
					$(this).parents("li").children().fadeTo(200, 0.01, function () {
						$(this).slideUp(200, function () {
							$(this).parents("li").remove();
						});
					});
					setTimeout(function () {
						if ($(".comparison-box .compare-list li").length === 0) {
							$(".comparison-box .compare-list").remove();
							$(".comparison-box .ev_information").fadeIn(500);
							$(".comparison-buttons").slideUp(100);
						}
					},
					450);
					return false;
				});
				$(propertyRemoveButton).appendTo(propertyRemove);
				$(propertyRemove).appendTo(propertyLi);
				//Create Compare Button
				var propertyCompare = document.createElement('span');
				$(propertyCompare).addClass("compare");
				var propertyCompareButton = document.createElement('a');
				$(propertyCompareButton).attr("href", "compare_side_by_side.html/bar/" + BAR);
				$(propertyCompareButton).html("Compare");
				$(propertyCompareButton).appendTo(propertyCompare);
				$(propertyCompare).appendTo(propertyLi);
				//Add the List item to the Container
				$(propertyLi).appendTo(".comparison-box .compare-list");
				$(propertyLi).children().hide();
				$(propertyLi).children().fadeIn(200);
				//Scroll to new List item
				$(".comparison-box").scrollTo($(propertyLi), 200);
			}
			return false;
		});
	}

    /**********************************************************/
    /* Add - Remove from Valuation list                       */
    /**********************************************************/
    if($("#valuation_list_form .ev_appeal").length > 0){
        initJSON(".ev_appeal", null);
        $("#valuation_list_form .ev_appeal").click(function () {
            var checkedNum = 0;
            $(".comparison-box .compare-list li input").each(function () {
                if ($(this).attr("checked") === true) {
                    checkedNum++;
                }
            });
            if (checkedNum <1) {
                alert(getMessage(".ev_appeal", "appeal.main.error.selected"));
                return false;
            }
        });
    }

    if($("#valuation_list_form .ev_compare").length > 0){
        initJSON(".ev_compare", null);
        $("#valuation_list_form .ev_compare").click(function () {
			var checkedNum = 0;
            var valid = true;
			$(".comparison-box .compare-list li input").each(function () {
				if ($(this).attr("checked") === true) {
					checkedNum++;
                    var value = $(this).attr("value");
                    var osRef = value.substring(value.lastIndexOf("/")+1);
                    if(osRef==0){
                        valid = false;
                    }
				}
			});
            
            if(!valid){
               alert(getMessage(".ev_compare", "compare.main.error.invalid"))
               return false;
            }else if (checkedNum != 2 )  {
				alert(getMessage(".ev_compare", "compare.main.error.selected"));
				return false;
			}
		});
    }

	if ($("body.agentPropertyResults").length > 0) {
		/**********************************************************/
		/* Add - Remove from Comparison list                      */
		/**********************************************************/
		$(".comparison-buttons .ev_remove-all").click(function () {
			$(".comparison-box .compare-list").remove();
			$(".comparison-box .ev_information").fadeIn(400);
			return false;
		});
		$(".data-table .add").click(function () {
			if ($(".comparison-box .compare-list li").length >= 20) {
				alert('Sorry, only 20 properties can be added to your Valuation List');
				return false;
			}
			if ($(".comparison-box .compare-list").length < 1) {
			//Create the List Container
				var compareListContainer = document.createElement('ul');
				$(compareListContainer).addClass("compare-list");
				$(compareListContainer).appendTo(".comparison-box");
			}
			if ($(".comparison-box .compare-list li").length === 0) {
				$(".comparison-box .ev_information").hide();
			}
			if ($(".comparison-box .compare-list").length > 0) {
				var BAR = $(this).parents('tr').find('.ev_bar').html();
				var ADDRESS = $(this).parents('tr').find('.ev_address').html();
				if (eval($(".comparison-box .compare-list li.BAR_" + BAR)).length >= 1) {
					alert('Sorry, you cannot add the same property to your Valuation List');
					return false;
				}
				//Create the List Item
				var propertyLi = document.createElement('li');
				$(propertyLi).addClass("BAR_" + BAR);
				//Create the Address Span
				var propertyAddress = document.createElement('span');
				$(propertyAddress).addClass("property");
				$(propertyAddress).html(ADDRESS);
				$(propertyAddress).appendTo(propertyLi);
				//Create Remove Button
				var propertyRemove = document.createElement('span');
				$(propertyRemove).addClass("remove");
				var propertyRemoveButton = document.createElement('a');
				$(propertyRemoveButton).attr("href", "/removebar/" + BAR);
				$(propertyRemoveButton).attr("title", "Remove from list");
				$(propertyRemoveButton).html("Remove");
				$(propertyRemoveButton).click(function () {
					$(this).parents("li").children().fadeTo(200, 0.01, function () {
						$(this).slideUp(200, function () {
							$(this).parents("li").remove();
						});
					});
					setTimeout(function () {
						if ($(".comparison-box .compare-list li").length === 0) {
							$(".comparison-box .compare-list").remove();
							$(".comparison-box .ev_information").fadeIn(500);
						}
					},
					450);
					return false;
				});
				$(propertyRemoveButton).appendTo(propertyRemove);
				$(propertyRemove).appendTo(propertyLi);
				//Create Compare Button
				var propertyChkBox = document.createElement('span');
				$(propertyChkBox).addClass("chkbox");
				var propertyCompareButton = document.createElement('input');
				$(propertyCompareButton).attr("type", "checkbox");
				$(propertyCompareButton).appendTo(propertyChkBox);
				$(propertyChkBox).appendTo(propertyLi);
				//Add the List item to the Container
				$(propertyLi).appendTo(".comparison-box .compare-list");
				$(propertyLi).children().hide();
				$(propertyLi).children().fadeIn(200);
				//Scroll to new List item
				$(".comparison-box").scrollTo($(propertyLi), 200);
			}
			return false;
		});
	}
	if ($("body.glossary").length > 0) {
		/**********************************************************/
		/* JQuery SmoothScroll                                    */
		/**********************************************************/
		$('a[href*=#]').click(function () {
			if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
				var $target = $(this.hash);
				$target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');
				if ($target.length) {
					var targetOffset = $target.offset().top;
					$('html,body').animate({
						scrollTop: targetOffset
					},
					1000);
					return false;
				}
			}
		});
	}
	/**********************************************************/
	/* Results per page - Auto-postback                       */
	/**********************************************************/
	if ($("form.results_per_page").length > 0) {
		$("form.results_per_page select").change(function(){
			$(this).closest("form").submit();
		});
	}

}

function setupSearchValidation(){
    var pageName = "#search";
    var search = new LiveValidation('search', {
        onlyOnSubmit: false,
        onlyOnBlur: true,
        onValid: function () {},
        insertAfterWhatNode: 'searchbox'
    }).add(Validate.Presence, {
        failureMessage: getMessage(pageName, "error.searchTerm.required")
    });
}

function setupSearchAgainValidation(){
    var pageName = "body.searchAgain";
    var searchAgain = new LiveValidation('search_again', {
        onlyOnSubmit: false,
        onlyOnBlur: true,
        onValid: function () {}
    }).add(Validate.Presence, {
        failureMessage: getMessage(pageName, "error.searchTerm.required")
    });
}

function setupSearchAgainValidation(){
    var pageName = "body.searchAgain";
    var searchAgain = new LiveValidation('search_again', {
        onlyOnSubmit: false,
        onlyOnBlur: true,
        onValid: function () {}
    }).add(Validate.Presence, {
        failureMessage: getMessage(pageName, "error.searchTerm.required")
    });
}

function setupBasicResultsValidation() {
    var pageName = "body.propertySearchResults";

    var searchAgainTerm = new LiveValidation('searchAgainTerm', {
        onlyOnSubmit: false,
        onlyOnBlur: true,
        onValid: function () {
            this.removeMessageAndFieldClass();
        }
    });

    var searchStreet = new LiveValidation('searchStreet', {
        onlyOnSubmit: false,
        onlyOnBlur: true,
        onValid: function () {
            this.removeMessageAndFieldClass();
        }
    });

	searchStreet.add(Validate.Length,{minimum:1,maximum:146,tooLongMessage:getMessage(pageName, "error.street.badLength")});
    searchStreet.add(Validate.Format,{pattern:simple_text_regex,failureMessage:getMessage(pageName, "error.street.invalid")});

    var searchTown = new LiveValidation('searchTown', {
        onlyOnSubmit: false,
        onlyOnBlur: true,
        onValid: function () {
            this.removeMessageAndFieldClass();
        }
    });

	searchTown.add(Validate.Length,{minimum:1,maximum:112,tooLongMessage:getMessage(pageName, "error.town.badLength")});
    searchTown.add(Validate.Format,{pattern:simple_text_regex,failureMessage:getMessage(pageName, "error.town.invalid")});

    var searchNameNumber = new LiveValidation('searchNameNumber', {
        onlyOnSubmit: false,
        onlyOnBlur: true,
        onValid: function () {
            this.removeMessageAndFieldClass();
        }
    });

	searchNameNumber.add(Validate.Length,{minimum:1,maximum:146,tooLongMessage:getMessage(pageName, "error.nameNumber.badLength")});
    searchNameNumber.add(Validate.Format,{pattern:simple_text_regex,failureMessage:getMessage(pageName, "error.nameNumber.invalid")});

    var currentSearchType = $("input:[name='searchType']:checked").val();
    if (currentSearchType == "bar") {
        searchAgainTerm.add(Validate.Length, {
            minimum: 1, maximum: 25,
                tooShortMessage: getMessage(pageName, "error.baRef.badLength"),
                tooLongMessage: getMessage(pageName, "error.baRef.badLength")
        });
        searchAgainTerm.add(Validate.Presence, {
                failureMessage: getMessage(pageName, "error.baRef.required")
        });
	} else if (currentSearchType == "postcode") {
        searchAgainTerm.add(Validate.Format, {
            pattern: postcodeRegExSearch,
            failureMessage: getMessage(pageName, "error.postcode.invalid")
        });
        searchAgainTerm.add(Validate.Custom, {
                failureMessage: getMessage(pageName, "error.postcode.required"),
                against: function(postcode, args) {
                    var street = document.getElementById('searchStreet').value;
                    var town = document.getElementById('searchTown').value;
                    this.displayMessageWhenEmpty = true;
                    return postcode!="" || (street!="" && town!="");
                }
        });
	} else if (currentSearchType == "voaCase") {
        searchAgainTerm.add(Validate.Length, {
            minimum: 7, maximum: 8,
                tooShortMessage: getMessage(pageName, "error.voaCaseNo.badLength"),
                tooLongMessage: getMessage(pageName, "error.voaCaseNo.badLength")
        });
        searchAgainTerm.add(Validate.Presence, {
                failureMessage: getMessage(pageName, "error.voaCaseNo.required")
        });
	}

    $("input:[name='searchType']").change(function () {
        if (this.value == "bar") {
            searchAgainTerm.destroy();
            searchAgainTerm = new LiveValidation('searchAgainTerm', {
                onlyOnSubmit: false,
                onlyOnBlur: true,
                onValid: function () {
                    this.removeMessageAndFieldClass();
                }
            });

    		searchAgainTerm.add(Validate.Presence, {
                failureMessage: getMessage(pageName, "error.baRef.required")
            });

            searchAgainTerm.add(Validate.Length, {
                minimum: 1, maximum: 25,
                tooShortMessage: getMessage(pageName, "error.baRef.badLength"),
                tooLongMessage: getMessage(pageName, "error.baRef.badLength")
            });
            /* CR 4247 - start */
            /* searchAgainTerm.add(Validate.Format,{pattern:alphanum_regex,
                failureMessage:getMessage(pageName, "error.baRef.invalid")});*/
            /* CR 4247 - end */

        } else if (this.value == "postcode") {
            searchAgainTerm.destroy();
            searchAgainTerm = new LiveValidation('searchAgainTerm', {
                onlyOnSubmit: false,
                onlyOnBlur: true,
                onValid: function () {
                    this.removeMessageAndFieldClass();
                }
            });
            searchAgainTerm.add(Validate.Format, {
                pattern: postcodeRegExSearch,
                failureMessage: getMessage(pageName, "error.postcode.invalid")
            });
            searchAgainTerm.add(Validate.Custom, {
                failureMessage: getMessage(pageName, "error.postcode.required"),
                against: function(postcode, args) {
                    var street = document.getElementById('searchStreet').value;
                    var town = document.getElementById('searchTown').value;
                    var result = postcode!="" || (street!="" && town!="");
                    return result;
                }
            });
        } else if (this.value == "voaCase") {
            searchAgainTerm.destroy();
            searchAgainTerm = new LiveValidation('searchAgainTerm', {
                onlyOnSubmit: false,
                onlyOnBlur: true,
                onValid: function () {
                    this.removeMessageAndFieldClass();
                }
            });

    		searchAgainTerm.add(Validate.Presence, {
                failureMessage: getMessage(pageName, "error.voaCaseNo.required")
            });

            searchAgainTerm.add(Validate.Length, {
                minimum: 7, maximum: 8,
                tooShortMessage: getMessage(pageName, "error.voaCaseNo.badLength"),
                tooLongMessage: getMessage(pageName, "error.voaCaseNo.badLength")
            });
            searchAgainTerm.add(Validate.Format,{pattern:numeric_regex,
                failureMessage:getMessage(pageName, "error.voaCaseNo.invalid")});

        }
    });
	
	$("form#searchCriteria").submit(function(){
		if($("input#searchAgainTerm").val()==""){
			if($("input#searchTown").val()=="" ||$("input#searchStreet").val()==""){
				searchStreet.add(Validate.Presence,{failureMessage:getMessage(pageName,"error.street.required")});
				searchTown.add(Validate.Presence,{failureMessage:getMessage(pageName,"error.town.required")});
				$("input#searchAgainTerm").blur(function(){
					if(this.value != ""){
						searchStreet.destroy();
						searchTown.destroy();
					}else{
						searchStreet = new LiveValidation().add(Validate.Presence,{failureMessage:getMessage(pageName,"error.street.required")});
						searchTown = new LiveValidation().add(Validate.Presence,{failureMessage:getMessage(pageName,"error.town.required")});
					}
				});				
				LiveValidation.massValidate([searchStreet,searchTown]);
				return false;
			}
		}else{
			searchStreet.destroy();
			searchTown.destroy();
		}
	});
	
}

function setupBeginSearchValidation(){
    var pageName = "body.beginSearch";
    var searchterm = new LiveValidation('searchterm', {
        onlyOnSubmit: false,
        onlyOnBlur: true,
        onValid: function () {
            this.removeMessageAndFieldClass();
        }
    });
    var currentSearchType = $("input:[name='searchType']:checked").val();

    if (currentSearchType == "bar") {
		searchterm.add(Validate.Presence, {
            failureMessage: getMessage(pageName, "error.baRef.required")
        });
        searchterm.add(Validate.Length, {
            minimum: 1, maximum: 25,
                tooShortMessage: getMessage(pageName, "error.baRef.badLength"),
                tooLongMessage: getMessage(pageName, "error.baRef.badLength")
        });
        /* CR 4247 - start */
        /* searchterm.add(Validate.Format,{pattern:alphanum_regex,
            failureMessage:getMessage(pageName, "error.baRef.invalid")}); */
        /* CR 4247 - end */

	} else if (currentSearchType == "postcode") {
	    searchterm.add(Validate.Presence, {
            failureMessage: getMessage(pageName, "error.postcode.required")
        });
        searchterm.add(Validate.Format, {
            pattern: postcodeRegExSearch,
            failureMessage: getMessage(pageName, "error.postcode.invalid")
        });  		
	} else if (currentSearchType == "voaCase") {
		searchterm.add(Validate.Presence, {
            failureMessage: getMessage(pageName, "error.voaCaseNo.required")
        });
        searchterm.add(Validate.Length, {
            minimum: 7, maximum: 8,
                tooShortMessage: getMessage(pageName, "error.voaCaseNo.badLength"),
                tooLongMessage: getMessage(pageName, "error.voaCaseNo.badLength")
        });
        searchterm.add(Validate.Format,{pattern:numeric_regex,
            failureMessage:getMessage(pageName, "error.voaCaseNo.invalid")});

	}
    
    $("input:[name='searchType']").change(function () {
        if (this.value == "bar") {
            searchterm.destroy();
            searchterm = new LiveValidation('searchterm', {
                onlyOnSubmit: false,
                onlyOnBlur: true,
                onValid: function () {
                    this.removeMessageAndFieldClass();
                }
            }).add(Validate.Presence, {
                failureMessage: getMessage(pageName, "error.baRef.required")
            });
            searchterm.add(Validate.Length, {
                minimum: 1, maximum: 25,
                tooShortMessage: getMessage(pageName, "error.baRef.badLength"),
                tooLongMessage: getMessage(pageName, "error.baRef.badLength")
            });
            /* CR 4247 - start */
            /* searchterm.add(Validate.Format,{pattern:alphanum_regex,
                failureMessage:getMessage(pageName, "error.baRef.invalid")}); */
            /* CR 4247 - end */
        } else if (this.value == "postcode") {
            searchterm.destroy();
            searchterm = new LiveValidation('searchterm', {
                onlyOnSubmit: false,
                onlyOnBlur: true,
                onValid: function () {
                    this.removeMessageAndFieldClass();
                }
            }).add(Validate.Presence, {
                failureMessage: getMessage(pageName, "error.postcode.required")
            });
            searchterm.add(Validate.Format, {
                pattern: postcodeRegExSearch,
                failureMessage: getMessage(pageName, "error.postcode.invalid")
            });
        } else if (this.value == "voaCase") {
            searchterm.destroy();
            searchterm = new LiveValidation('searchterm', {
                onlyOnSubmit: false,
                onlyOnBlur: true,
                onValid: function () {
                    this.removeMessageAndFieldClass();
                }
            }).add(Validate.Presence, {
                failureMessage: getMessage(pageName, "error.voaCaseNo.required")
            });
            searchterm.add(Validate.Length, {
                minimum: 7, maximum: 8,
                tooShortMessage: getMessage(pageName, "error.voaCaseNo.badLength"),
                tooLongMessage: getMessage(pageName, "error.voaCaseNo.badLength")
            });
            searchterm.add(Validate.Format,{pattern:numeric_regex,
                failureMessage:getMessage(pageName, "error.voaCaseNo.invalid")
	    });
	  }
        });
}
function setupContactUsValidation(){
    var pageName = "body.contactUs";
    var postcodeRegEx = /^[a-zA-Z]{1,2}[0-9rR][0-9a-zA-Z]?( [0-9][a-zA-Z]{2})?/i;

    if ($("#title").length > 0) {
        var title = new LiveValidation('title', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {this.removeMessageAndFieldClass();}
        }).add(Validate.Presence, {failureMessage: getMessage(pageName, "error.title.required")});
    }

    if ($("#fname").length > 0) {
        var fname = new LiveValidation('fname', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {this.removeMessageAndFieldClass();}
        }).add(Validate.Presence, {failureMessage: getMessage(pageName, "error.firstName.required")});
    }

    if ($("#sname").length > 0) {
        var sname = new LiveValidation('sname', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {this.removeMessageAndFieldClass();}
        }).add(Validate.Presence, {failureMessage: getMessage(pageName, "error.surname.required")});
    }

    if ($("#email").length > 0) {
        var email = new LiveValidation('email', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {this.removeMessageAndFieldClass();}
        }).add(Validate.Presence, {failureMessage: getMessage(pageName, "error.email.required")});
        email.add(Validate.Email, {failureMessage: getMessage(pageName, "error.email.invalid")});
    }

    if ($("#postcode").length > 0) {
        var postcode = new LiveValidation('postcode', {onlyOnSubmit: true, onlyOnBlur: false, onValid: function () {this.removeMessageAndFieldClass();}
        }).add(Validate.Format, {pattern: postcodeRegEx,failureMessage: getMessage(pageName, "error.postcode.invalid")});
    }

    if ($("#phone_day").length > 0) {
        var phoneDay = new LiveValidation('phone_day', {onlyOnSubmit: true, onlyOnBlur: false, onValid: function () {this.removeMessageAndFieldClass();}
        }).add(Validate.Numericality, {notANumberMessage: getMessage(pageName, "error.phone.invalid")});
    }

    if ($("#phone_mobile").length > 0) {
        var mobilePhone = new LiveValidation('phone_mobile', {onlyOnSubmit: true, onlyOnBlur: false, onValid: function () {this.removeMessageAndFieldClass();}
        }).add(Validate.Numericality, {notANumberMessage: getMessage(pageName, "error.mobile.invalid")});
    }

    

    //FOR CANNOT FIND ASSESSMENT
    if ($("#property_name_number").length > 0) {
        var property_name_number = new LiveValidation('property_name_number', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {this.removeMessageAndFieldClass();}
        }).add(Validate.Presence, {failureMessage: getMessage(pageName, "error.propertyNameNumber.required")});
    }
    if ($("#property_address1").length > 0) {
        var property_address1 = new LiveValidation('property_address1', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {this.removeMessageAndFieldClass();}
        }).add(Validate.Presence, {failureMessage: getMessage(pageName, "error.address1.required")});
    }
    if ($("#property_town").length > 0) {
        var property_town = new LiveValidation('property_town', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {this.removeMessageAndFieldClass();}
        }).add(Validate.Presence, {failureMessage: getMessage(pageName, "error.town.required")});
    }
    if ($("#property_county").length > 0) {
        var property_county = new LiveValidation('property_county', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {this.removeMessageAndFieldClass();}
        }).add(Validate.Presence, {failureMessage: getMessage(pageName, "error.county.required")});
    }
    if ($("#property_postcode").length > 0) {
        var property_postcode = new LiveValidation('property_postcode', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {this.removeMessageAndFieldClass();}
        });
        property_postcode.add(Validate.Presence, {failureMessage: getMessage(pageName, "error.postcode.required")});
        property_postcode.add(Validate.Format, {pattern: postcodeRegEx,failureMessage: getMessage(pageName, "error.postcode.invalid")});
    }

    //FOR AMEND VALUATION PAGE
    if ($("#detailed_reasons").length > 0) {
        var detailed_reasons = new LiveValidation('detailed_reasons', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {this.removeMessageAndFieldClass();}
        }).add(Validate.Presence, {failureMessage: getMessage(pageName, "error.details.required")});
        /*detailed_reasons.add(Validate.Length, {maximum:400, tooLongMessage: getMessage(pageName, "error.details.badLength")});*/
		/* CR 4248 - start */
        /* detailed_reasons.add(Validate.Length, {
                maximum: 400,
                tooLongMessage: getMessage(pageName, "error.details.badLength")
            });*/
        detailed_reasons.add(Validate.Length, {
                maximum: 2000,
                tooLongMessage: getMessage(pageName, "error.details.badLength")
            });
		/* CR 4248 - end */
    }
    if ($("#new_name_number").length > 0) {
        var name_number = new LiveValidation('new_name_number', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {this.removeMessageAndFieldClass();}
        }).add(Validate.Presence, {failureMessage: getMessage(pageName, "error.propertyNameNumber.required")});
    }
    if ($("#new_street").length > 0) {
        var street = new LiveValidation('new_street', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {this.removeMessageAndFieldClass();}
        }).add(Validate.Presence, {failureMessage: getMessage(pageName, "error.address1.required")});
    }
    if ($("#new_town").length > 0) {
        var town = new LiveValidation('new_town', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {this.removeMessageAndFieldClass();}
        }).add(Validate.Presence, {failureMessage: getMessage(pageName, "error.town.required")});
    }
    if ($("#new_county").length > 0) {
        var email = new LiveValidation('new_county', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {this.removeMessageAndFieldClass();}
        }).add(Validate.Presence, {failureMessage: getMessage(pageName, "error.county.required")});
    }
    if ($("#new_postcode").length > 0) {
        var postcode = new LiveValidation('new_postcode', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {this.removeMessageAndFieldClass();}
        }).add(Validate.Presence, {failureMessage: getMessage(pageName, "error.postcode.required")});
        postcode.add(Validate.Format, {
        pattern: postcodeRegEx,
        failureMessage: getMessage(pageName, "error.postcode.invalid")
    });
    }    

    if ($("#continue_on").length > 0) {
        var continue_on = new LiveValidation('continue_on', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'continue0n_label' , onValid: function () {this.removeMessageAndFieldClass();}
        }).add(Validate.Acceptance, { failureMessage: getMessage(pageName, "error.checkbox.select") } );
    }

    //FOR GENERAL ENQUIRY
    if ($("#message").length > 0) {
        var message = new LiveValidation('message', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {this.removeMessageAndFieldClass();}
        }).add(Validate.Presence, {failureMessage: "Please enter your message"});
        /*message.add(Validate.Length, {maximun:400, tooLongMessage : getMessage(pageName, "error.messageText.badLength")});*/
		/* CR 4248 - start */
			/* message.add(Validate.Length, {
                maximum: 400,
                tooLongMessage: getMessage(pageName, "error.messageText.badLength")
            }); */
	        message.add(Validate.Length, {
                maximum: 2000,
                tooLongMessage: getMessage(pageName, "error.messageText.badLength")
            });
		/* CR 4248 - end */
    }
}

var fieldArray = [];

function clearArray(){
    for(var i=0; i< fieldArray.length; i++){
        fieldArray[i].destroy();
    }
    fieldArray=[];
}

function setupLiveValidation() {

	var months = ["Jan","jan","Feb","feb","Mar","mar","Apr","apr","May","may","Jun","jun","Jul","jul","Aug","aug","Sep","sep","Oct","oct","Nov","nov","Dec","dec"];
	/**********************************************************/
	/* STANDARD PAGE VALIDATION                               */
	/*                                                        */
	/* Elements that appear on more than one page             */
	/**********************************************************/
	if ($("#search").length > 0) {
		initJSON("#search", setupSearchValidation)
	}
	/**********************************************************/
	/* SPECIFIC PAGE VALIDATION                               */
	/*                                                        */
	/* Elements that only appear on singular pages 			  */
	/*                                                        */
	/* BODY tag contains class='[pagetype]' and validation is */
	/* applied based on the class                             */
	/**********************************************************/

	//BEGIN SEARCH AGAIN
	if ($("body.searchAgain").length > 0) {
		initJSON("body.searchAgain", setupSearchAgainValidation);
	}
	
	//BEGIN SEARCH VALIDATION
	if ($("body.beginSearch").length > 0) {
	    initJSON("body.beginSearch", setupBeginSearchValidation);	
	}

	if ($("body.propertySearchResults").length > 0) {
	    initJSON("body.propertySearchResults", setupBasicResultsValidation);
	}
	
	//BEGIN SEARCH VALIDATION - ALREADY SUBMITTED APPEAL
	if ($("body.beginSearchCase").length > 0) {
		var searchtermSearch = new LiveValidation('searchterm', {
			onlyOnSubmit: false,
			onlyOnBlur: true,
			onValid: function () {
				this.removeMessageAndFieldClass();
			}
		}).add(Validate.Presence, {
			failureMessage: "Please enter your \'VOA Case Number\' in the field above"
		});
		$("input:[name='searchtype']").change(function () {
			if (this.value == "postcode") {
				searchtermSearch.destroy();
				searchtermSearch = new LiveValidation('searchterm', {
					onlyOnSubmit: false,
					onlyOnBlur: true,
					onValid: function () {
						this.removeMessageAndFieldClass();
					}
				}).add(Validate.Presence, {
					failureMessage: "Please enter your \'Postcode\' in the field above"
				});
				searchtermSearch.add(Validate.Format, {
					pattern: postcodeRegExSearch,
					failureMessage: "Please enter a valid Postcode"
				});
			} else {
				searchtermSearch.destroy();
				searchtermSearch = new LiveValidation('searchterm', {
					onlyOnSubmit: false,
					onlyOnBlur: true,
					onValid: function () {
						this.removeMessageAndFieldClass();
					}
				}).add(Validate.Presence, {
					failureMessage: "Please enter your \'VOA Case Number\' in the field above"
				});
			}
		});
	}
	
	//APPEAL PAGE VALIDATION
	if ($("body.appealPartA").length > 0) {
		
		if ($("#occupierName").length > 0) {
		
			var name_of_occupier = new LiveValidation('occupierName', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
			}).add(Validate.Presence, {failureMessage: "Please enter name of occupier"});
			
			// for 2000 appeals there is no check box. a hidden input field always sets the value to true but without the if validation is always added to the field
			if (!$("input[name=ownerOccupied]").hasClass("hiddenOwnerOccupied")) {
				var appA_name_owner = new LiveValidation('ownerName', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter name of owner"});
			}
			
			var appA_rent_value = new LiveValidation('rentAmount', {onlyOnSubmit: false, onlyOnBlur: false, onValid: function () {}
			}).add(Validate.Presence, {failureMessage: "Please enter the rental amount"});
			
			var appA_rentPaymentPeriodOther = new LiveValidation('rentPaymentPeriodOther',{onlyOnSubmit: false, onlyOnBlur: false,onValid:function(){}
			}).add(Validate.Presence,{failureMessage:"Please enter the payment period."});
			appA_rentPaymentPeriodOther.disable();
			
			var dateValFields =[];
//CR 4250 - start
// validation changed and only uses that already existing on server side
/*
			var rentFirstPayableCompDate_day = new LiveValidation("rentFirstPayableCompDate.day",{onlyOnSubmit:false,onlyOnBlur:true,onValid:function(){},insertAfterWhatNode:"rentFirstPayableCompDate.year"
			}).add(Validate.Presence,{failureMessage:"Date should be in format: '01 Jan 2001'"}).add(Validate.Numericality,{failureMessage:"Date should be in format: '01 Jan 2001'"}).add(Validate.Length,{is:2})
			dateValFields.push(rentFirstPayableCompDate_day);
			var rentFirstPayableCompDate_month = new LiveValidation("rentFirstPayableCompDate.month",{onlyOnSubmit:false,onlyOnBlur:true,onValid:function(){},insertAfterWhatNode:"rentFirstPayableCompDate.year"
			}).add(Validate.Presence,{failureMessage:"Date should be in format: '01 Jan 2001'"}).add(Validate.Inclusion,{within:months,
			failureMessage:"Date should be in format: '01 Jan 2001'"});
			dateValFields.push(rentFirstPayableCompDate_month);
			var rentFirstPayableCompDate_year = new LiveValidation("rentFirstPayableCompDate.year",{onlyOnSubmit:false,onlyOnBlur:true,onValid:function(){},insertAfterWhatNode:"rentFirstPayableCompDate.year"
			}).add(Validate.Presence,{failureMessage:"Date should be in format: '01 Jan 2001'"}).add(Validate.Numericality,{failureMessage:"Date should be in format: '01 Jan 2001'"})
			dateValFields.push(rentFirstPayableCompDate_year);
			var rentReviewDueCompDate_day = new LiveValidation("rentReviewDueCompDate.day",{onlyOnSubmit:false,onlyOnBlur:true,onValid:function(){},insertAfterWhatNode:"rentReviewDueCompDate.year"
			}).add(Validate.Presence,{failureMessage:"Date should be in format: '01 Jan 2001'"}).add(Validate.Numericality,{failureMessage:"Date should be in format: '01 Jan 2001'"}).add(Validate.Length,{is:2})
			dateValFields.push(rentReviewDueCompDate_day);
			var rentReviewDueCompDate_month = new LiveValidation("rentReviewDueCompDate.month",{onlyOnSubmit:false,onlyOnBlur:true,onValid:function(){},insertAfterWhatNode:"rentReviewDueCompDate.year"
			}).add(Validate.Presence,{failureMessage:"Date should be in format: '01 Jan 2001'"}).add(Validate.Inclusion,{within:months,
			failureMessage:"Date should be in format: '01 Jan 2001'"});
			dateValFields.push(rentReviewDueCompDate_month);
			var rentReviewDueCompDate_year = new LiveValidation("rentReviewDueCompDate.year",{onlyOnSubmit:false,onlyOnBlur:true,onValid:function(){},insertAfterWhatNode:"rentReviewDueCompDate.year"
			}).add(Validate.Presence,{failureMessage:"Date should be in format: '01 Jan 2001'"}).add(Validate.Numericality,{failureMessage:"Date should be in format: '01 Jan 2001'"})
			dateValFields.push(rentReviewDueCompDate_year);
*/
//CR 4250 - end
			

			function get_address_flag(){
				return $("input[name=occupierAddressFlag]:checked").val();
			}
						
			function get_licence_paid_flag(){ 
				return $("input[name=rentLicencePaidFlag]:checked").val();
			}
			
			function get_owner_address_flag(){
				return $("input[name=ownerAddressFlag]:checked").val();
			}
			
			var validatedFields = [];	
			var validatedOwnerFields = [];

			function clearValidation(arrayName){
				
				if(arrayName == "owner"){
					for(var i=0; i< validatedOwnerFields.length; i++){
						validatedOwnerFields[i].destroy();
					}
					validatedOwnerFields=[];
				}else{
					for(var i=0; i< validatedFields.length; i++){
							validatedFields[i].destroy();
					}
					validatedFields=[];
				}
			}
							
			function resetAppealA(){
				if(get_address_flag() == "property"){
					clearValidation()				
				}else{
//CR4250 - start
// validation changed and moved to server side
/*
					var appA_number_street = new LiveValidation('occupierAddress.numberStreet', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
					}).add(Validate.Presence, {failureMessage: "Please enter number and street"});
					validatedFields.push(appA_number_street);
					var appA_town = new LiveValidation('occupierAddress.town', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
					}).add(Validate.Presence, {failureMessage: "Please enter Town"});
					validatedFields.push(appA_town);
					var appA_postcode = new LiveValidation('occupierAddress.postcode', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
					}).add(Validate.Presence, {failureMessage: "Please enter a Postcode"});
					validatedFields.push(appA_postcode);
*/
//CR4250 - end
				}
				
				if(get_owner_address_flag() != "other"){
					clearValidation("owner")
				}else{
//CR4250 - start
// validation changed and moved to server side
/*
					var appA_owner_number_street = new LiveValidation('ownerAddress.numberStreet', {onlyOnSubmit: false, onlyOnBlur: false, onValid: function () {}
					}).add(Validate.Presence, {failureMessage: "Please enter number and street"});
					validatedOwnerFields.push(appA_owner_number_street);
					var appA_owner_town = new LiveValidation('ownerAddress.town', {onlyOnSubmit: false, onlyOnBlur: false, onValid: function () {}
					}).add(Validate.Presence, {failureMessage: "Please enter Town"});
					validatedOwnerFields.push(appA_owner_town);
					var appA_owner_postcode = new LiveValidation('ownerAddress.postcode', {onlyOnSubmit: false, onlyOnBlur: false, onValid: function () {}
					}).add(Validate.Presence, {failureMessage: "Please enter a Postcode"});
					validatedOwnerFields.push(appA_owner_postcode);
*/
//CR4250 - end
				}
				rentalValidationSetup();
			}
			
			function doOwnerOccupied(){
				if(typeof $("input[name=ownerOccupied]:checked").val() != "undefined"){
					appA_name_owner.disable();
					return true;
				}else{
					appA_name_owner.enable();
				}
				return false;
			}
				
			function removeRadioVal(){
				$("#rentLicencePaidFlag_1").closest(".field").children("#radio_licence_error").remove();
				rentalValidationSetup();
			}
			
			function applyRadioValErr(){
				$("#rentLicencePaidFlag_1").closest(".field").append("<div class='err-holder' id='radio_licence_error'><div class='err'><div class='arrow'></div>Please select one of the options above</div><div class='clearboth'></div></div>");								
			}
			
			function rentalValidationSetup(){
				if(get_licence_paid_flag() == "yes"){
					appA_rent_value.enable();
					for(i=0;i<dateValFields.length; i++){
						dateValFields[i].enable();
					}
				}else{
					appA_rent_value.disable()
					for(i=0;i<dateValFields.length; i++){
						dateValFields[i].disable();
					}
				}		
				if(($("input:radio[name=rentPaymentPeriodFlag]:checked").val()=="other") && (!doOwnerOccupied())){
					appA_rentPaymentPeriodOther.enable();
				}else{
					appA_rentPaymentPeriodOther.disable();
				}
			}
			
			$("form#form").submit(function(){
				if(typeof get_licence_paid_flag() == "undefined"){	
					removeRadioVal();
					applyRadioValErr();
					
					if(!doOwnerOccupied()){
						rentalValidationSetup();
					}
					
					return false;
				}else{
					removeRadioVal();
				}			
			});
			
			$("input[name=rentLicencePaidFlag]").change(removeRadioVal);
			$("input[name=occupierAddressFlag],input[name=ownerAddressFlag]").change(resetAppealA);
			$("input[name=ownerOccupied]").change(function(){
				if(doOwnerOccupied()){
					//removeRadioVal();
				}
				rentalValidationSetup();
			});
			$("input:radio[name=rentPaymentPeriodFlag]").change(rentalValidationSetup);
			
			resetAppealA();
			doOwnerOccupied();
			
		}
	}
	
	if ($("body.appealPartB").length > 0) {

		$("#form").submit(function(){
			removeFormValidationMessage();
			var radioButtonValue = $("input[name='alterRLEntryFlag']:checked").val();
			if(typeof radioButtonValue=="undefined"){
				$("#question").append("<div class='err-holder' id='question_error'><div class='err'>Please select one of the options below</div><div class='clearboth'></div></div>");
				return false;
			}
		})
		

		function removeFormValidationMessage()
		{
			$("#question_error").remove();
		}
		
		function setupPartB(value){
		if (value == "A"){
				var altered_value = new LiveValidation('alterRLEntryAmount', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter the altered value"}).add(Validate.Numericality);
				fieldArray.push(altered_value);
				
				var altered_day = new LiveValidation('alterRLEntryCompDateA.day', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'altered_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"});
				altered_day.add(Validate.Numericality, {notANumberMessage: "Altered day must be a number"});
				fieldArray.push(altered_day);
				
				var altered_month = new LiveValidation('alterRLEntryCompDateA.month', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'altered_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"}).add(Validate.Inclusion,{within:months,
				failureMessage:"Date should be in format: '01 Jan 2001'"});
				fieldArray.push(altered_month);
				
				var altered_year = new LiveValidation('alterRLEntryCompDateA.year', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'altered_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"});
				altered_year.add(Validate.Numericality, {notANumberMessage: "Altered year must be a number"});
				fieldArray.push(altered_year);
			}
			if (value == "B"){
				var deleted_day = new LiveValidation('alterRLEntryCompDateB.day', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'deleted_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"});
				deleted_day.add(Validate.Numericality, {notANumberMessage: "Altered day must be a number"});
				fieldArray.push(deleted_day);
				
				var deleted_month = new LiveValidation('alterRLEntryCompDateB.month', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'deleted_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"}).add(Validate.Inclusion,{within:months,
			failureMessage:"Date should be in format: '01 Jan 2001'"});;
				fieldArray.push(deleted_month);
				
				var deleted_year = new LiveValidation('alterRLEntryCompDateB.year', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'deleted_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"});
				deleted_year.add(Validate.Numericality, {notANumberMessage: "Altered year must be a number"});
				fieldArray.push(deleted_year);
			}
			if (value == "C"){
				var divided_value = new LiveValidation('alterRLEntryDivisions', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter divided into"});
				divided_value.add(Validate.Numericality, {notANumberMessage: "into must be a number"});
				fieldArray.push(divided_value);
				
				var divided_day = new LiveValidation('alterRLEntryCompDateC.day', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'divided_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"});
				divided_day.add(Validate.Numericality, {notANumberMessage: "Altered day must be a number"});
				fieldArray.push(divided_day);
				
				var divided_month = new LiveValidation('alterRLEntryCompDateC.month', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'divided_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"}).add(Validate.Inclusion,{within:months,
			failureMessage:"Date should be in format: '01 Jan 2001'"});;
				fieldArray.push(divided_month);
				
				var divided_year = new LiveValidation('alterRLEntryCompDateC.year', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'divided_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"});
				divided_year.add(Validate.Numericality, {notANumberMessage: "Altered year must be a number"});
				fieldArray.push(divided_year);
			}
			if (value == "D"){
				//MERGED OPTION ONLY
			}
			if (value == "E"){
				var changed_day = new LiveValidation('alterRLEntryCompDateE.day', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'changed_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"});
				changed_day.add(Validate.Numericality, {notANumberMessage: "Altered day must be a number"});
				fieldArray.push(changed_day);
				
				var changed_month = new LiveValidation('alterRLEntryCompDateE.month', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'changed_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"}).add(Validate.Inclusion,{within:months,
			failureMessage:"Date should be in format: '01 Jan 2001'"});;
				fieldArray.push(changed_month);
				
				var changed_year = new LiveValidation('alterRLEntryCompDateE.year', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'changed_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"});
				changed_year.add(Validate.Numericality, {notANumberMessage: "Altered year must be a number"});
				fieldArray.push(changed_year);
			}
			if (value == "F"){
				var other_changes = new LiveValidation('alterRLEntryOther', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter changes"});
				fieldArray.push(other_changes);
				
				var other_day = new LiveValidation('alterRLEntryCompDateF.day', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'other_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"});
				other_day.add(Validate.Numericality, {notANumberMessage: "Altered day must be a number"});
				fieldArray.push(other_day);
				
				var other_month = new LiveValidation('alterRLEntryCompDateF.month', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'other_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"}).add(Validate.Inclusion,{within:months,
			failureMessage:"Date should be in format: '01 Jan 2001'"});
				fieldArray.push(other_month);
				
				var other_year = new LiveValidation('alterRLEntryCompDateF.year', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'other_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"});
				other_year.add(Validate.Numericality, {notANumberMessage: "Altered year must be a number"});
				fieldArray.push(other_year);

                var alterRLEntryOther = new LiveValidation('alterRLEntryOther', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
                });
                alterRLEntryOther.add(Validate.Length, {
                    maximum: 1000,
                    tooLongMessage: "The text you have entered exceeds the maximum. Please limit yourself to 1000 characters at most"
                     });
                fieldArray.push(alterRLEntryOther);
			}		
		}
		
		$("input:[name='alterRLEntryFlag']").change(function () {
			clearArray();
			removeFormValidationMessage()
			setupPartB(this.value)
		})
		setupPartB($("input[name='alterRLEntryFlag']:checked").value);
	}
	
	if ($("body.appealPartC").length > 0) {
		
		
		$("#form").submit(function(){
			removeFormValidationMessage();
			var radioButtonValue = $("input[name='alterRLReasonFlag']:checked").val();
			if(typeof radioButtonValue=="undefined"){
				$("#question").append("<div class='err-holder' id='question_error'><div class='err'>Please select one of the options below</div><div class='clearboth'></div></div>");
				return false;
			}
		})

		
		function removeFormValidationMessage()
		{
			$("#question_error").remove();
		}
		
		var detailed_reasons = new LiveValidation('alterRLReasonDetails', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter Details"});
				fieldArray.push(detailed_reasons);
		
		$("input:[name='alterRLReasonFlag']").change(function () {
			clearArray();
			removeFormValidationMessage();
			
			detailed_reasons = new LiveValidation('alterRLReasonDetails', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter Details"});
				fieldArray.push(detailed_reasons);
			
			setupPartC(this.value);
			
		})
		
		function setupPartC(value){
			if (value == "B"){
				
				var day = new LiveValidation('alterRLReasonCompDateB.day', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'altering_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"});
				day.add(Validate.Numericality, {notANumberMessage: "Altered day must be a number"});
				fieldArray.push(day);
				
				var month = new LiveValidation('alterRLReasonCompDateB.month', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'altering_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"}).add(Validate.Inclusion,{within:months,failureMessage:"Month should be like 'Jan'"});
				fieldArray.push(month);
				
				var year = new LiveValidation('alterRLReasonCompDateB.year', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'altering_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"});
				year.add(Validate.Numericality, {notANumberMessage: "Altered year must be a number"});
				fieldArray.push(year);
				
			}else if (value == "C"){
				
				var day = new LiveValidation('alterRLReasonCompDateC.day', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'alteringEffDate_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"});
				day.add(Validate.Numericality, {notANumberMessage: "Altered day must be a number"});
				fieldArray.push(day);
				
				var month = new LiveValidation('alterRLReasonCompDateC.month', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'alteringEffDate_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"}).add(Validate.Inclusion,{within:months,failureMessage:"Month should be like 'Jan'"});
				fieldArray.push(month);
				
				var year = new LiveValidation('alterRLReasonCompDateC.year', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'alteringEffDate_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"});
				year.add(Validate.Numericality, {notANumberMessage: "Altered year must be a number"});
				fieldArray.push(year);
			}else if (value == "D"){
				
				var affecting_day = new LiveValidation('alterRLReasonCompDateD.day', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'affecting_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"});
				affecting_day.add(Validate.Numericality, {notANumberMessage: "Altered day must be a number"});
				fieldArray.push(affecting_day);
				
				var affecting_month = new LiveValidation('alterRLReasonCompDateD.month', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'affecting_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"}).add(Validate.Inclusion,{within:months,failureMessage:"Month should be like 'Jan'"});
				fieldArray.push(affecting_month);
				
				var affecting_year = new LiveValidation('alterRLReasonCompDateD.year', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'affecting_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"});
				affecting_year.add(Validate.Numericality, {notANumberMessage: "Altered year must be a number"});
				fieldArray.push(affecting_year);
			}else if (value == "K"){
				
				var altered_day = new LiveValidation('alterRLReasonCompDateK.day', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'altered_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"});
				altered_day.add(Validate.Numericality, {notANumberMessage: "Altered day must be a number"});
				fieldArray.push(altered_day);
				
				var altered_month = new LiveValidation('alterRLReasonCompDateK.month', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'altered_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"}).add(Validate.Inclusion,{within:months,failureMessage:"Month should be like 'Jan'"});
				fieldArray.push(altered_month);
				
				var altered_year = new LiveValidation('alterRLReasonCompDateK.year', {onlyOnSubmit: false, onlyOnBlur: true, insertAfterWhatNode: 'altered_date', onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter with effect from"});
				altered_year.add(Validate.Numericality, {notANumberMessage: "Altered year must be a number"});
				fieldArray.push(altered_year);
				
				
				var ofthe = new LiveValidation('reasonKDecisionMaker', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter of the"});
				fieldArray.push(ofthe);
				
//CR 4250 - start
// validation changed and moved to server side
/*
				var property_name = new LiveValidation('reasonKAddress.propertyName', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter Property Name"});
				fieldArray.push(property_name);
				
				var number_street = new LiveValidation('reasonKAddress.numberStreet', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter Number \& Street"});
				fieldArray.push(number_street);
				
				var postal_district = new LiveValidation('reasonKAddress.postalDistrict', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter Postal District"});
				fieldArray.push(postal_district);
				
				var town = new LiveValidation('reasonKAddress.town', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter Town"});
				fieldArray.push(town);
				
				var county = new LiveValidation('reasonKAddress.county', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter County"});
				fieldArray.push(county);
				
				var postcode = new LiveValidation('reasonKAddress.postcode', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter Postcode"});
				fieldArray.push(postcode);
*/				
//CR 4250 - end
				var because = new LiveValidation('reasonKRelatedReasoning', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter Details"});
				fieldArray.push(because);
				
				var decision = new LiveValidation('reasonKInvalidatesRLReasoning', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter Details"});
				fieldArray.push(decision);
			}
		
		}
		
		setupPartC($("input:[name='alterRLReasonFlag']:checked").val())
	}
	
	if ($("body.appealPartD").length > 0) {
		
		var capacity_value;
		
		var capacity = new LiveValidation('capacity', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
		}).add(Validate.Presence, {failureMessage: "Please choose a capacity"});
		
		
		var name = new LiveValidation('name', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
		}).add(Validate.Presence, {failureMessage: "Please enter name"});
		
//CR4250 - start
		var correspondenceDayPhone = new LiveValidation('correspondenceDayPhone', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
		}).add(Validate.Presence, {failureMessage: "Please enter a daytime telephone number"});
//CR4250 - end
		
		var correspondance = new LiveValidation('correspondenceMethod', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
		}).add(Validate.Presence, {failureMessage: "Please choose correspondence method"});
		
		function partDaddressValidation(){
			clearArray();
//CR 4250 - start
// validation changed and moved to server side
/*
			var numberStreetD = new LiveValidation('correspondenceAddress.numberStreet',{onlyOnSubmit: false, onlyOnBlur: true,onValid:function(){}
			}).add(Validate.Presence,{failureMessage: 'Please enter street number'});
			fieldArray.push(numberStreetD);
			
			var townD = new LiveValidation('correspondenceAddress.town',{onlyOnSubmit: false, onlyOnBlur: true,onValid:function(){}
			}).add(Validate.Presence,{failureMessage: 'Please enter Town'});
			fieldArray.push(townD);
			
			var postcodeD = new LiveValidation('correspondenceAddress.postcode',{onlyOnSubmit: false, onlyOnBlur: true,onValid:function(){}
			}).add(Validate.Presence,{failureMessage: 'Please enter a postcode'});
			fieldArray.push(postcodeD);
*/
//CR 4250 - end
		}

		
		$("#capacity").change(function () {			
			if (this.value == "other"){
				capacity_value = new LiveValidation('capacityOther', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter other capacity"});
			}else{
				if(typeof capacity_value != "undefined"){
					capacity_value.destroy();
				}
			}
		})
		
		var email_of_occupier;
		
		$("#correspondenceMethod").change(function () {
			if(this.value == "email"){
				email_of_occupier = new LiveValidation('correspondenceEmail', {onlyOnSubmit: false, onlyOnBlur: true, onValid: function () {}
				}).add(Validate.Presence, {failureMessage: "Please enter email address"});
			}else{
				if (typeof email_of_occupier != "undefined"){
					email_of_occupier.destroy();
				}
			}
		});
		
		$("input[name=correspondenceAddressFlag]").change(function(){
			if($("input[name=correspondenceAddressFlag]:checked").val()=="other"){
				partDaddressValidation();
			}else{
				clearArray();
			}
		})
		
		
	}
	
	//CONTACT PAGE VALIDATION
	if ($("body.contactUs").length > 0) {
		initJSON("body.contactUs", setupContactUsValidation);
	}
	
}

function disableLiveValidation(){
    for(var i=0; i<fieldArray.length; i++){
        fieldArray[i].disable();
    }
    if($("#form")){
       $("#form").unbind("submit");
    }
    var allInputs = $("input[type!=radio]");
    allInputs.each(function (i){
        if(this.id!='' && this.id!="undefined"){
            var inputField = new LiveValidation(this.id);
            inputField.disable();
        }
    });
    var allSelects = $("select");
    allSelects.each(function (i){
        if(this.id!='' && this.id!="undefined"){
            var inputField = new LiveValidation(this.id);
            inputField.disable();
        }
    });
    var allTextAreas =  $("textarea");
    allTextAreas.each(function (i){
        if(this.id!='' && this.id!="undefined"){
            var inputField = new LiveValidation(this.id);
            inputField.disable();
        }
    });
}


function setupAdvancedSearch(){
	
	//ADVANCED SEARCH PAGE VALIDATION AND ARRANGEMENT
	if($("body.nav_1.agent").length>0){
		initJSON("body.nav_1.agent",setUpAdvancedSearchValidation);
	}
}

//function disableAdvancedSearchFields(selectedField) {
//	$(".jsdisabled input,.jsdisabled select").each(function(){
//        if(this.id!="postcode" || selectedField!="POSTCODE"){
//            this.disable=true;
//        }
//
//    });
//}

function setUpAdvancedSearchValidation(){
	var pageName = "body.nav_1.agent";

	var allOptions={
		ADDRESS:["ADDRESS","form.address.option"],
		BA_REF:["BA_REF","form.baRef.option"],
		BA_NAME:["BA_NAME","form.baName.option"],
		UPRN:["UPRN","form.uprn.option"],
		SCAT:["SCAT","form.sCat.option"],
		SCHEME:["SCHEME","form.scheme.option"],
		SPROG_ID:["SPROG_ID","form.subProgrammeID.option"],
		VOA_CASE_NO:["VOA_CASE_NO","form.caseNumber.option"],
        POSTCODE: ["POSTCODE", "form.postcode.option"]
	}
		
	hideFields();
	//object holds array of strings (later parsed into selectors) to show for each chosen option
	var searchByOptions = {
		PROPERTY:[allOptions.ADDRESS,allOptions.BA_REF,allOptions.BA_NAME,allOptions.UPRN,allOptions.SCAT,allOptions.SCHEME],
		SUB_PROGRAMME:[allOptions.ADDRESS,allOptions.BA_REF,allOptions.BA_NAME, allOptions.UPRN,allOptions.SCAT,allOptions.SCHEME,allOptions.SPROG_ID,allOptions.VOA_CASE_NO],
		BILLING_AUTHORITY:[allOptions.BA_NAME,allOptions.POSTCODE]
	};
	
	//object holds array of selectors/items to show for each chosen option
	var visibleFieldOptions = {
		ADDRESS:[],
		BA_REF:["#ba_ref_row"],
		BA_NAME:["#baName_row"],
		UPRN:["#uprn_row"],
		SCAT:["#scat_code_row"],
		SCHEME:["#scheme_row"],
		SPROG_ID:["#subProgId_row"],
		VOA_CASE_NO:["#voaCaseNo_row"],
        POSTCODE: []
	};
	
	
	function hideFields(){
		$(".jshidden").hide();	
	}

    function showField(selector) {
        for(x in validationArray){
			try {
				validationArray[x].disable()
			} catch (err) {
				
			}
		}

		if(selector.length > 0){
			$(selector).show();
			selector=selector.substring(1,selector.length-4);
			if(validationArray[selector]){
				validationArray[selector].enable();
			}
		}
		//CR 4278 - start
		if (selector=="baName") {
 			showField("#scat_code2_row");
 		} else if (selector=="scat_code") {
 			showField("#baName2_row");
 		}
		//CR 4278 - end
    }

	hideFields();
	
	var validationArray=[];
	
//	var townValPresent = new LiveValidation("town",{onValid:function(){}}).add(Validate.Presence,{failureMessage:getLocalMessage("error.town.required")});
    var postocdeVal = new LiveValidation("postcode",{onValid:function(){},onlyOnBlur:true}).add(Validate.Format,{pattern:postcodeRegExSearch,failureMessage:getMessage(pageName, "error.postcode.invalid")});

	var as_ba_ref = new LiveValidation("ba_ref",{onValid:function(){},onlyOnBlur:true}).disable();
	as_ba_ref.add(Validate.Presence,{failureMessage: getMessage(pageName, "error.baRefAdvanced.required")});
	as_ba_ref.add(Validate.Length,{minimum:1,maximum:25,tooLongMessage: getMessage(pageName, "error.baRef.badLength")});
/* CR 4247 - start */
//    as_ba_ref.add(Validate.Format,{pattern:alphanum_regex,failureMessage:getMessage(pageName, "error.baRef.invalid")});
/* CR 4247 - end */
    validationArray["ba_ref"]=as_ba_ref;
	
//CR 4278 - start
/*
	var as_ba_max_length = document.location.href.match("/en/")?40:70;
	var as_ba_name = new LiveValidation("baName",{onValid:function(){},onlyOnBlur:true}).disable();
	as_ba_name.add(Validate.Presence,{failureMessage:getMessage(pageName, "error.baName.required")});
	as_ba_name.add(Validate.Length,{minimum:1,maximum:as_ba_max_length,tooLongMessage:getMessage(pageName, "error.baName.badLength")});
    as_ba_name.add(Validate.Format,{pattern:simple_text_regex,failureMessage:getMessage(pageName, "error.baName.invalid")});
    validationArray["baName"]=as_ba_name;
*/	
//CR 4278 - end

//    var as_ba_name_postcode = new LiveValidation("postcode",{onValid:function(){},onlyOnBlur:true}).add(Validate.Format,{pattern:postcodeRegEx,failureMessage:getMessage(pageName, "error.postcode.invalid")});
//    validationArray["postcode"]=as_ba_name_postcode;
    
	var as_uprn = new LiveValidation("uprn",{onValid:function(){},onlyOnBlur:true}).disable();
	as_uprn.add(Validate.Presence,{failureMessage:getMessage(pageName, "error.uprn.required")});
	as_uprn.add(Validate.Length,{minimum:1,maximum:12,tooLongMessage:getMessage(pageName, "error.uprn.badLength")});
	as_uprn.add(Validate.Numericality,{notANumberMessage:getMessage(pageName, "error.uprn.invalid")})
	validationArray["uprn"]=as_uprn;
	
	var as_voaCaseNo = new LiveValidation("voaCaseNo",{onValid:function(){},onlyOnBlur:true}).disable();
	as_voaCaseNo.add(Validate.Presence,{failureMessage:getMessage(pageName, "error.voaCaseNo.required")});
	as_voaCaseNo.add(Validate.Numericality,{notANumberMessage:getMessage(pageName, "error.voaCaseNo.invalid")});
	as_voaCaseNo.add(Validate.Length,{min:10,max:11,tooShortMessage:getMessage(pageName, "error.voaCaseNo.advanced.badLength"),tooLongMessage:getMessage(pageName, "error.voaCaseNo.advanced.badLength")});
	validationArray["voaCaseNo"]=as_voaCaseNo;
	
	var as_scheme = new LiveValidation("scheme",{onValid:function(){},onlyOnBlur:true}).disable();
	as_scheme.add(Validate.Presence,{failureMessage:getMessage(pageName, "error.scheme.required")});
	as_scheme.add(Validate.Length,{minimum:1,maximum:11,tooLongMessage:getMessage(pageName, "error.uprn.badLength")});
	as_scheme.add(Validate.Numericality,{notANumberMessage:getMessage(pageName, "error.scheme.invalid")});
	validationArray["scheme"]=as_scheme;
	
	var as_subProgId = new LiveValidation("subProgId",{onValid:function(){},onlyOnBlur:true}).disable();
	as_subProgId.add(Validate.Presence,{failureMessage:getMessage(pageName, "error.sProgId.required")});
	as_subProgId.add(Validate.Format,{pattern:s_prog_id_regex,failureMessage:getMessage(pageName, "error.sProgId.invalid")});
	validationArray["subProgId"]=as_subProgId;

    var townVal = new LiveValidation("town",{onValid:function(){},onlyOnBlur:true}).add(Validate.Format,{pattern:simple_text_regex,failureMessage:getMessage(pageName, "error.town.invalid")});

//	var streetValPresent = new LiveValidation("street",{onValid:function(){}}).add(Validate.Presence,{failureMessage:getLocalMessage("error.street.required")});
    var streetVal = new LiveValidation("street",{onValid:function(){},onlyOnBlur:true}).add(Validate.Format,{pattern:simple_text_regex,failureMessage:getMessage(pageName, "error.street.invalid")});

    var nameNumVal = new LiveValidation("property_name_number",{onValid:function(){},onlyOnBlur:true}).add(Validate.Format,{pattern:simple_text_regex,failureMessage:getMessage(pageName, "error.nameNumber.invalid")});

    var nonStandardDescVal = new LiveValidation("non_standard_desc", {onValid:function(){},onlyOnBlur:true}).add(Validate.Format,{pattern:simple_text_regex,failureMessage:getMessage(pageName, "error.nonStandardDesc.invalid")});

    var searchForIndex = document.getElementById('search_for').selectedIndex; // remember the current search for index

	//tag on the change handler and don't forget to fire it off via chaining i.e X.change(func(){foo=bar}).change()
	$("select#search_for").change(function(){
        var searchByIndex = document.getElementById('search_by').selectedIndex; // remember the current index
        var orig =
		$("#search_by").empty();
		$.each(searchByOptions[this.value],function(){
			$("#search_by").append("<option value="+this[0]+">"+getMessage(pageName,this[1])+"</option>");
	    });

		$("#search_by").val(searchByOptions[this.value][0]);
		//this is for IE to keep the select width after dumping all the options
		$("#search_by").width($("#search_by").outerWidth()).val(searchByOptions[this.value][0][0]).change();

        if(document.getElementById('search_for').selectedIndex == searchForIndex) {
            if(searchForIndex==2) { // Special handling for BA search hack
                if(searchByIndex==2) {
                    searchByIndex = 0;
                } else {
                    searchByIndex = 1;
                }
            }

            document.getElementById('search_by')[searchByIndex].selected = 1; // set previous selected
            var visibleFieldKey = document.getElementById('search_by')[searchByIndex].value;
            showField(visibleFieldOptions[visibleFieldKey].toString()); // show the right primary search field
        }
        //disableAdvancedSearchFields(this.value);
	}).change();
	
	$("select#search_by").change(function(){
		hideFields();
		var selector = visibleFieldOptions[this.value].toString();
        showField(selector);
	});
	
	$("form#propertySearch").submit(function(){
		if(!$("input:radio[@name=listYear]:checked").length > 0){
			var radioErrHTML = '<div class="err-holder LV_validation_message LV_invalid"><div class="err"><div class="arrow"/><span>Validation Error: </span>Please choose a list year</div><div class="clearboth"/></div>';
			$("input:radio[@name=listYear]:last").after(radioErrHTML);
			return false;
		}
	});	
}



// AJAX - JSON
function initJSON(pageName, callBack) {
    var data = "messageIds="+pages[pageName];
    var url = "/rli/ajaxGetMessage";
    $.ajax({
    type: "POST",
    url: url,
    data: data,
    dataType: "json",
    success: function(data, textStatus ) {
        jJSON[pageName] = (function(){
            response = {
                ids: []
            };
            $.each(data.messages, function(id, message) {
                  response.ids[message.id] = message.value;
            });
            return response.ids;
        })();
        if(callBack!=null)
            eval(callBack).apply();
    }});
}

function getMessage(pageName, id){
    return jJSON.getValue(pageName, id)
}

var pages = {
    "#search":["error.searchTerm.required"],
    "body.searchAgain":["error.searchTerm.required"],
    "body.beginSearch":["error.postcode.required","error.postcode.invalid","error.baRef.required","error.baRef.invalid",
        "error.baRef.badLength","error.voaCaseNo.badLength","error.voaCaseNo.invalid","error.voaCaseNo.required"],
    "body.propertySearchResults":["error.postcode.required","error.postcode.invalid","error.baRef.required","error.baRef.invalid",
        "error.baRef.badLength","error.street.required","error.street.invalid","error.street.badLength",
        "error.town.required","error.town.invalid","error.town.badLength","error.nameNumber.invalid",
        "error.nameNumber.badLength","error.voaCaseNo.badLength","error.voaCaseNo.invalid","error.voaCaseNo.required"],
    "body.contactUs":["error.title.required","error.firstName.required","error.surname.required","error.email.required",
     "error.email.invalid","error.messageText.required","error.messageText.badLength","error.propertyNameNumber.required",
     "error.address1.required", "error.address2.required", "error.town.required", "error.county.required",
     "error.postcode.required", "error.postcode.invalid", "error.phone.invalid","error.mobile.invalid",
     "error.details.required", "error.details.badLength", "error.messageText.badLength", "error.checkbox.select"],
    "body.nav_1.agent":["error.baRef.required","error.baRef.invalid","error.town.required","error.baRef.length",
        "error.baRefAdvanced.required","error.baRef.badLength","error.baName.required","error.uprn.required",
        "error.uprn.invalid","error.uprn.badLength","error.scheme.required","error.scheme.invalid",
        "error.sProgId.required","error.sProgId.invalid","error.voaCaseNo.required","error.voaCaseNo.invalid",
        "error.voaCaseNo.advanced.badLength","error.nameNumber.invalid", "error.nameNumber.badLength","error.street.badLength",
        "error.street.required","error.street.invalid","error.town.invalid",
        "error.town.badLength","error.town.required","error.postcode.invalid","error.nonStandardDesc.invalid",
        "error.nonStandardDesc.badLength","error.rvFrom.invalid","error.rvTo.invalid","error.rvFrom.negativeValue",
        "error.rvTo.negativeValue","form.propertyValuation.option","form.subProgramme.option",
        "form.billingAuthority.option","form.address.option","form.baRef.option","form.baName.option",
        "form.uprn.option","form.sCat.option","form.scheme.option","form.subProgrammeID.option",
        "form.caseNumber.option","form.postcode.option","error.voaCaseNo.badLength","error.voaCaseNo.invalid","error.voaCaseNo.required"],
    ".ev_compare":["compare.main.error.invalid", "compare.main.error.selected"],
    ".ev_appeal":["appeal.main.error.selected"]
};

var jJSON = {

    getValue: function(pageName, id) {
        return jJSON[pageName][id];
    }

};

// END AJAX - JSON

// Global Regex
var s_prog_id_regex = /([A-Za-z0-9]{1,4})-([\\+A-Za-z0-9]{1,4})-([A-Za-z0-9]{1,4})$/;
var alphanum_regex = /^[A-Za-z0-9]+$/;
var numeric_regex = /^[0-9]+$/;
var simple_text_regex = /^[A-Za-z0-9 &,\-//]+$/;
// full OR partial postcode
var postcodeRegEx = /^[a-zA-Z]{1,2}[0-9rR][0-9a-zA-Z]?( [0-9][a-zA-Z]{2})?$/i;
var postcodeRegExSearch = /^[a-zA-Z]{1,2}[0-9rR][0-9a-zA-Z]?( [0-9][a-zA-Z]{0,2})?$/i;

$(document).ready(function () {
	setupPages();
    setupLiveValidation();
	setupVideoBoxes();
	setupModeSwitcher();
	setupAdvancedSearch();
	//removeEmptyBoxes();
});