function checkMandatoryFields(id) {
    var form1 = document.getElementById(id);
    var node_list  = form1.getElementsByTagName('input');
    var canSubmit  = true;
    var isCheckbox = false;

    for (i = 0; i < node_list.length; i++) {
        var node = node_list[i];
        var nodeType = node.getAttribute('type');
        var mandatory = node.getAttribute('mandatory');
        
        // Check box
        if (nodeType == 'checkbox' && (mandatory != null || mandatory === 'true' || mandatory === 'yes')) {
            if (!node.checked) {
                isCheckbox = true;
            }
        }
        // Input fields = password or text
        if (nodeType == 'text' ||  !nodeType || nodeType == 'password' ) { //check type
                if (node.value == '' && node.disabled == false && (mandatory != null || mandatory === 'true' || mandatory === 'yes')) {
                        node.className = 'errorText';
                        canSubmit = false;
                        node.focus();
                } else {
                        node.className = 'text';
                }
        }

    }

    // Drop downs
    node_list = form1.getElementsByTagName('select');
    for (i = 0; i < node_list.length; i++) {
        var node = node_list[i];
        if (node.value == '' && node.disabled == false
            && (node.getAttribute('mandatory') != null || node.getAttribute('mandatory') === 'true' || node.getAttribute('mandatory') === 'yes')) {
            node.className = 'errorText';
            canSubmit = false;
            node.focus();
        } else {
            node.className = 'text';
        }
    }

    // Text areas
    var node_list = form1.getElementsByTagName('textarea');
    for (i = 0; i < node_list.length; i++) {
        var node = node_list[i];
        if (node.value == '' && node.disabled == false
            && (node.getAttribute('mandatory') != null || node.getAttribute('mandatory') === 'true' || node.getAttribute('mandatory') === 'yes')) {
            node.className = 'errorText';
            canSubmit = false;
            node.focus();
        } else {
            node.className = 'text';
        }
    }
    
    if (!canSubmit) { // Alert the mandatory fields first
        alert("Please fill all mandatory fields!");
        return canSubmit;
    }

    if (isCheckbox) { // If everithing else is fine alert checkbox.
        alert("You have to accept the agreement!");
        return false;
    }
    return canSubmit;
}


function onQuickCheckLoad( rent ){
    replaceOptionsRent();
}

function sendRegistration(){
    if (checkMandatoryFieldsInRegister()) {
        document.registrantionForm.submit();
    } 
}
function makeOffer(propertyID){
    alert("makeAnOfferForm"+propertyID);
    var reply = prompt("Please,Introduce a price for your offer", "");
    if(reply==null) reply = prompt("You have to introduce a price for your offer", "");
    var form = document.getElementById("makeAnOfferForm"+propertyID);
    var offerPrice = document.getElementById("offerPrice"+propertyID);
    offerPrice.value=reply;
    form.action="../handlers/propertyH.jsp";
    form.submit();
}

function checkMandatoryFieldsInRegister(formId){
    var canSubmit = checkMandatoryFields(formId);

    if (!canSubmit) return false;
    // Mobile
    canSubmit = checkMobile(document.getElementById("register_mobile").value);
    // Email
    if (canSubmit) {
        canSubmit = echeck(document.getElementById("register_email").value);
    }
    // Are the passwords equals?
    var   passwd1 = document.getElementById("register_pass1").value;
    var   passwd2 = document.getElementById("register_pass2").value;
    if(canSubmit && passwd1 != passwd2){
        alert("The new passwords are not the same");
        canSubmit = false;
    }

    return canSubmit;
}


function submitQuickSearchForm(){
    /*
    try{
        if ( "Area or postcode" == document.getElementById("zip").value )
            document.getElementById("zip").disabled = true;
        else
            document.getElementById("select_location").disabled = true;
    }catch( ex ){
    alert( ex );
    return false;
    */
   return true;
}

function replaceOptionsBuy(){

    valueArray = [ "", "50000", "100000", "200000", "250000", "300000", "350000", "400000", "450000", "500000", "550000", "1000000" ];
    textArray = [ "&pound;0k", "&pound;50k", "&pound;100k", "&pound;200k", "&pound;250k", "&pound;300k", "&pound;350k", "&pound;400k", "&pound;450k", "&pound;500k", "&pound;550k", "&pound;1 million" ];
    loadList( document.getElementById('select_from'), valueArray, textArray );

    valueArray = [ "50000", "100000", "200000", "250000", "300000", "350000", "400000", "450000", "500000", "550000", "1000000", "" ];
    textArray = [ "&pound;50k", "&pound;100k", "&pound;200k", "&pound;250k", "&pound;300k", "&pound;350k", "&pound;400k", "&pound;450k", "&pound;500k", "&pound;550k", "&pound;1 million", "&pound;1 million+" ];
    loadList( document.getElementById('select_to'), valueArray, textArray );
}

function replaceOptionsRent(){
    
    valueArray = [ "", "100", "150", "200", "250", "300", "350", "400", "450", "500", "550", "600", "650", "700", "750" ];
    textArray = [ "&pound;0", "&pound;100", "&pound;150", "&pound;200", "&pound;250", "&pound;300", "&pound;350", "&pound;400", "&pound;450", "&pound;500", "&pound;550", "&pound;600","&pound;650","&pound;700","&pound;750" ];
    loadList( document.getElementById('select_from'), valueArray, textArray );

    valueArray = [ "200", "250", "300", "350", "400", "450", "500", "550", "600", "650", "700", "750", "1000", "1500", "" ];
    textArray = [ "&pound;200", "&pound;250", "&pound;300", "&pound;350", "&pound;400", "&pound;450", "&pound;500", "&pound;550", "&pound;600","&pound;650","&pound;700","&pound;750","&pound;1000","&pound;1500", "&pound;1500+" ];
    loadList( document.getElementById('select_to'), valueArray, textArray );
}

function loadList( list, valueArray, textArray ){
    list.options.length = 0;
    for ( i = 0; i < valueArray.length; i++ ){
        list.options[i] = new Option( textArray[i], valueArray[i] );
        list.options[i].innerHTML = textArray[i];
    }
    list.value = "";
}

function reloadImage(url){
    document.getElementById('big_image').src = url;
}

function showInfoBlock(id){
    for (var i=1; i<4; i++){
        document.getElementById('long_let'+i).style.display = 'none';
    }
    document.getElementById(id).style.display = 'block';
}

function showInfoBlockSale(id){
    document.getElementById('long_let1').style.display = 'none';
    document.getElementById(id).style.display = 'block';
}


function hideInfoBlock(id){
    document.getElementById(id).style.display = 'none';
}

function replaceAdvancedSearchBuy(){
    document.getElementById('advancedSearchArea').href="property_for_sale/search.jsp";
    document.getElementById('advancedSearchMap').href="property_for_sale/search_map.jsp";
    document.getElementById('advancedSearchSchool').href="property_for_sale/search_school.jsp";
    document.getElementById('advancedSearchStation').href="property_for_sale/search_tube.jsp";
}
function replaceAdvancedSearchRent(){
    document.getElementById('advancedSearchArea').href="property_for_rent/search.jsp";
    document.getElementById('advancedSearchMap').href="property_for_rent/search_map.jsp";
    document.getElementById('advancedSearchSchool').href="property_for_rent/search_school.jsp";
    document.getElementById('advancedSearchStation').href="property_for_rent/search_tube.jsp";
}

function check(CBid, CBvalue){
    document.getElementById(CBid).checked=true;
}
function uncheck(CBid, CBvalue){
    document.getElementById(CBid).checked=false;
}

function selectAll(id, idc){
    // $$('#'+id+' input').each(function(i){i.checked=$(idc).checked;});}
    var table=document.getElementById(id+"_table");
    var rows = table.getElementsByTagName("tr");
    for(i = 0; i < rows.length; i++){
        var row =rows[i];
        var coloumns = row.cells;
        for(c = 0; c < coloumns.length; c++){
            var col =coloumns[c];
            var inputs= col.getElementsByTagName("input");
            for( ii=0;ii<inputs.length;ii++){
                var input=inputs[ii];
                if(input==null)
                    continue;
                if(input.type!="checkbox")
                    continue;
                if(input.id==null)
                    continue;
                if(input.id.indexOf(id) ==-1 )
                    continue;
                if(input.id.length== id.length)
                    continue;
                input.checked=!(input.checked);
            }//end of for input
        } //end of for
    }//end of for rows
}
function changePage(selectMenu){
    var selectedOption=selectMenu.options[selectMenu.selectedIndex];
    var url = selectedOption.value;
    if (url !=""){
        document.selectOffice.action="/enterprise/website/morgan_randall_"+selectedOption.text.replace(' ','_')+"_office";
        document.selectOffice.submit();
    }
}

function JSchangePage(url){
    window.location=url;
}

function populateMessage(type){
    if(document.getElementById("description").value == null || document.getElementById("description").value == ""  ){
        alert("Please enter a message");
        return false;
    }

    if(document.getElementById("comment_name").value == null || document.getElementById("comment_name").value ==""){
        alert("Please enter your name");
        return false;
    }
    if(!(checkMobile(document.getElementById("comment_phone").value)) ){
        return false;
    }
    if (!(echeck($('comment_email').value))) {
        return false;
    }
    document.getElementById("Activity.description").value = document.getElementById("description").value + "; Name : "
      + document.getElementById("comment_name").value + "; Phone : "
      + document.getElementById("comment_phone").value + "; Email : "
      + document.getElementById("comment_email").value + " ; "+document.getElementById("PropertyName").value
      +"; Type: "+type;;

    return true;
}


function isNumberValid(numberInput){

    var anum=/^\d{11}$/

    if (!(numberInput.match(anum))){
        alert("Please enter phone number");
        return false;
    }
    if(numberInput.length != 11 ){
        alert("Phone number must of 11 numbers");
        return false;
    }

    if(numberInput.charAt(0)!= '0' ){
        alert("Phone number must start with zero");
        return false;
    }

    if( numberInput.charAt(1)!= '1' && numberInput.charAt(1)!= '2' && numberInput.charAt(1)!= '8' && numberInput.charAt(1)!= '7'  ){
        alert(numberInput +  "Phone number second digit must either be 1 or 2 or 8 or 7 (mobile) ");
        return false;
    }
    return true;
}

function submitHiddenForm(id,name){
    if(id != "" && name != ""){
        document.hiddenForm.action="/enterprise/website/"+name;
        document.hiddenForm.officeList.value=id;
        document.hiddenForm.submit();
    }
}
MyImages=new Array();
var index=0;
imagesPreloaded = new Array();
var currentIndex=-1;
var milliseconds=2000;
var paused=false;

function addImages(txt){
    MyImages[index]=txt;
    index++;
}

function loadImages(){
    for (var i = 0; i < MyImages.length ; i++)
        {
            imagesPreloaded[i] = new Image(521,350);
            imagesPreloaded[i].src=MyImages[i];
        }
    }

    function nextImage(){
        if (currentIndex < imagesPreloaded.length)
            currentIndex++;
        if (currentIndex >= imagesPreloaded.length)
            currentIndex = 0;
        document.images.propertyimage.src=imagesPreloaded[currentIndex].src;
        document.getElementById("countDisplay").innerHTML=(currentIndex+1)+"/"+imagesPreloaded.length
    }

    function previousImage(){
        currentIndex--;
        if (currentIndex < 0)
            currentIndex = imagesPreloaded.length - 1;
        document.images.propertyimage.src=imagesPreloaded[currentIndex].src;
        document.getElementById("countDisplay").innerHTML=(currentIndex+1)+"/"+imagesPreloaded.length
    }
    function pause(){
        paused=!paused;
        slideShow();
    }
    function slideShow(){
        if( !(paused)){
            nextImage();
            setTimeout("slideShow()",milliseconds);
        }
    }
    function changeSpeed(select){
        var selectedOption=select.options[select.selectedIndex];
        milliseconds = milliseconds + (selectedOption.value *1);
        if(milliseconds == 0 ){
            milliseconds=2000
        }

    }

    var radio="";
    function populateSchools(){
        var select=document.getElementById("school_LEA");
        var leaId=select.options[select.selectedIndex].value;
        radioChange();
        var targetURL=document.getElementById("target").value+"?radio="+radio;
        radio="";
        window.location="../handlers/listAttributeH.jsp?_attribute=school&_entity=LocalEducationAuthority&id="+leaId+"&_targetURL="+targetURL;

    }

    function radioChange(){
        var radioButtons=document.getElementsByName("radiobutton");
        for (i=0; i<radioButtons.length; i++){
            if (radioButtons[i].checked == true)
                radio=radioButtons[i].value;
        }
    }


    function checkMessage(propertyId){
        if(document.getElementById("ContactEvent.content").value == null || document.getElementById("ContactEvent.content").value == ""  ){
            alert("Please enter a message");
            return false;
        }
        if(propertyId != null && propertyId!= ""){
            document.getElementById("ContactEvent.content").value= document.getElementById("ContactEvent.content").value + "<br> Click here to view related <a href='../Property/view.jsp?id="+propertyId+"'>property</a>";
        }
        return true;
    }

    function populateContactEvent(){

        if(document.getElementById("preview").innerHTML == null || document.getElementById("preview").innerHTML == ""  ){
            alert("Please select a date");
            return false;
        }
        var hour= document.getElementById("hour");
        var time= document.getElementById("minute");
        document.getElementById("ContactEvent.content").value=document.getElementById("message").value + " Date requested:" + document.getElementById("preview").innerHTML  +" Time:" +hour.options[hour.selectedIndex].value + ":" + time.options[time.selectedIndex].value;

        return true;
    }

    function populateActivity(){
//        var hour= document.getElementById("hour");
//        var time= document.getElementById("minute");
        document.getElementById("Activity_description").value = document.getElementById("message").value;
        return true;
    }

    function checkEmailDetails(){

        if(document.getElementById("email_to").value==null || document.getElementById("email_to").value=="" ){
            alert("Please enter Friends email address");
            return false;
        }

        if(document.getElementById("email_name").value==null || document.getElementById("email_name").value=="" ){
            alert("Please enter your name "  );
            return false;
        }

        if(document.getElementById("email_email").value==null || document.getElementById("email_email").value=="" ){
            alert("Please enter your email address ");
            return false;
        }

        return ( echeck(document.getElementById("email_to").value) &&  echeck(document.getElementById("email_email").value)) ;

    }

    function checkSMSDetails(){

        if(document.getElementById("sms_to").value==null || document.getElementById("sms_to").value=="" ){
            alert("Please enter mobile number");
            return false;
        }
        var text=document.getElementById("sms_text").value;
        if(text.length > 165 ){
            alert("Text must be no more than 165 characters");
            return false;
        }

        return checkMobile(document.getElementById("sms_to").value);

    }

    function checkMobile(mobile){
	var expression = window.phoneRestriction;
	
	var strippedValue = mobile.split(' ').join('').trim();
	
	if(strippedValue.match(expression)){
		return true;
	}else{
		alert("Please enter a valid mobile number (only numbers)");
		return false;
	}
        return false
    }




    function echeck(str) {
        var at="@"
        var dot="."
        var lat=str.indexOf(at)
        var lstr=str.length
        var ldot=str.indexOf(dot)
        if (str.indexOf(at)==-1){
            alert("Invalid E-mail ID")
            return false
        }

        if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
            alert("Invalid E-mail ID")
            return false
        }

        if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
            alert("Invalid E-mail ID")
            return false
        }

        if (str.indexOf(at,(lat+1))!=-1){
            alert("Invalid E-mail ID")
            return false
        }

        if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
            alert("Invalid E-mail ID")
            return false
        }

        if (str.indexOf(dot,(lat+2))==-1){
            alert("Invalid E-mail ID")
            return false
        }

        if (str.indexOf(" ")!=-1){
            alert("Invalid E-mail ID")
            return false
        }

        return true
    }

    function displayDates(){

        if(document.getElementById("letType").value=="long"){
            hideInfoBlock("calendarDiv");
        }
        else {
             document.getElementById("calendarDiv").style.display = 'block';
        }

    }
    function checkDOB(str){
        if(document.getElementById(str+"*day").value == "99"  
            || document.getElementById(str+"*month").value == "99"
            || document.getElementById(str+"*year").value == "99"){
            alert("Invalid date of birth");
            return false
        }
        return true;
    }
    
    // FOR SEARCH FORM
    function refreshAvailabilityPeriods(url, selected) {
        var areaId = dojo.byId('area').value;
        dojo.byId('refreshPeriodDiv').style.display = '';
        var parameters = new Array();
        parameters["areaId"] = areaId;
	parameters["website"] = true;
        dojo.xhrPost({
            url:url,
            handleAs: "json",
            content: parameters,
            handle: function(data) {populateAvailabilityPeriodSelector(data, selected);}
        });
    }
   
    function populateAvailabilityPeriodSelector(data, selected) {
        var selector = dojo.byId('availabilityPeriodSelector');
        dojo.byId('refreshPeriodDiv').style.display = 'none';
        for (var i = selector.length - 1; i>=0; i--) {
            selector.remove(i);
        }
	var foundSelected = false;
        for (var key in data) {
            var period = data[key];
            if (period && period.name) {
                var optionElement = document.createElement('option');
                optionElement.value = key;
                optionElement.text = period.name;
                optionElement.period = period;
		if (key == selected) {
		    optionElement.selected = 'selected';
		    foundSelected = true;
		}
                try {
                    selector.add(optionElement, null); // standards compliant; doesn't work in IE
                }
                catch (ignore) {
                    selector.add(optionElement); // IE only
                }
            }
        }
	if (!foundSelected) {
	    selector.selectIndex = 0;
	}
    }
    
    function showDateFields(dropDown) {
        if (dropDown.value == 'shortLet') {
            $('shortLetFields').style.display = ''; 
        } else {
            $('shortLetFields').style.display = 'none'; 
            $('startDate').value = $('defaultFrom').value;
            $('endDate').value = $('defaultTo').value;
        }   
    }
    function checkMandatoryRadioButtons(id,name){
        var form = document.getElementById(id);
        var node_list  = document.getElementsByName(name);
        var canSubmit  = false;
       
        for (i = 0; i < node_list.length; i++) { 
            if (node_list[i].checked)
              canSubmit = true;
        }
        if (!canSubmit) { // Alert the mandatory fields first
            alert("Please fill all mandatory fields!");
            return canSubmit;
        }  
        return canSubmit;
    }


