// JScript File
//
// Javascript used to drive the verticle search control
//
var areaRows=0;
var checkedRow = -1;
var areasOpen = false;
var alertOpen = false;
var calcMatchesAfterLoad = false;

function UpdateSearching(name, email, phone, city, area, lp, up, type, student, furnished, beds, typeoflet, alertEmailOnly)
{
    SearchControlBase.UpdateSearchingCriteria(name, email, phone, city, area, lp, up, type, student, furnished, beds, typeoflet, alertEmailOnly, UpdateSearching_CallBack);
}

function GetByID(t)
{
    if (document.getElementById(t) != null && document.getElementById(t).value != null) {
        return document.getElementById(t).value;
    }
    return null;
}

function SetAjaxMsg(s)
{
    if (s=="") {
       document.getElementById("ajaxLoading").style.display = "none";
       document.getElementById("matchesID").innerHTML = "";
       if (searchType != "H" && searchType != "V") 
           document.getElementById("icArrow").style.display = "none";
    } else {
       document.getElementById("ajaxLoading").style.display = (s=="Loading..." ? "inline" : "none");
       document.getElementById("matchesID").innerHTML = s;
       if (searchType != "H" && searchType != "V") 
           document.getElementById("icArrow").style.display = (s=="Loading..." ? "none" : "inline");
       
    }
}

function getCheckedAreas()
{
    if (searchType == "H" || searchType=="F") return "";
    var tags = document.getElementsByTagName("input");
    var areas = "";
    var i=0
    var allChecked = true;
    
    for (i=0; i<tags.length; i++) {
        var tag = tags[i];
        if (tag.id !=null && tag.id.substr(0, 6) == "check_")  {
            if (document.getElementById(tag.id).checked) {
                var id = tag.id.substr(6,tag.id.length - 6);
                if (areas == "") areas=id; else areas = areas+","+id;
            } else {
                allChecked = false;
            }
        }
    }
    return (allChecked ? "" : areas);
}

function CalculateMatches() {
   var city = getSearchValue();
   var freetext = "";
   if (city == null || city == text || city == " " || city == "") { SetAjaxMsg(""); return; }
   /* If city starts with a number it is a city/area picked from the list */
   if (city.charCodeAt(0) <= 47 || city.charCodeAt(0) >= 58) {
       freetext = city;
       city = "";
   }
   if (freetext!="" && freetext.length<2) {
    SetAjaxMsg("");
    return;
   }

   var typeoflet = djTypeOfLet.get("value");
   var lp = GetByID(lpID);
   if (lp=="") lp=0;
   var up = GetByID(upID);
   if (up=="") up=9999;
   var beds = djBeds.get("value");
   var type = djType.get("value");
   var furnishing = djFurnished.get("value");
   
   var has_images = (typeof has_imagesID != "undefined" && document.getElementById(has_imagesID)!=null && document.getElementById(has_imagesID).checked);
   var underOffer = (typeof underOfferID != "undefined" && document.getElementById(underOfferID)!=null && document.getElementById(underOfferID).checked);
   var stud =  (typeof studentID != "undefined" && document.getElementById(studentID) != null && document.getElementById(studentID).checked);
   var dss = (typeof dssID != "undefined" && document.getElementById(dssID)!=null && document.getElementById(dssID).checked);
   
   
   var backintime = "0";
   
   if (typeof backInTimeID != "undefined" && document.getElementById(backInTimeID)!=null) {
       backintime = djBackintime.get("value");
   }
   var avail = "0";
   if (typeof availID != "undefined" && document.getElementById(availID)!=null) {
        avail = djAvailDate.get("value");
   }
   var area = "";
   if (searchType != "H" && searchType != "F") area = getCheckedAreas();

    if (product == "flat-share" || type == "FS" || type == "I" || type == "J")
    {
        beds = 1;
    }
    if (product == "parking" || type=='PP' || type == "G" || type == "Q")
    {
        beds = 1;
        furnishing = "";
    }

   //alert("data sent city="+city+" typeoflet="+typeoflet+" lp="+lp+" up="+ up + " beds="+beds+" type="+type+" furnishing="+furnishing + " has images="+has_images+" freetext="+freetext+
   //      " stud="+stud+" backintime= "+backintime+" dss="+dss+" underOffer="+underOffer+" areas="+area + " avail="+avail);
   SetAjaxMsg("Loading...");
   SearchControlBase.CalculateMatches(city, typeoflet, lp, up, beds, type, furnishing, has_images, freetext, stud, backintime, avail, dss, underOffer, area, searchType, CalculateMatches_CallBack);
}


function VChangePropertyType() {
    // If single/double/parking/grarage room then grey out beds otherwise ungrey them.
    var ptype = GetByID(typeID);
    if (ptype != null && (ptype == 'PP' || ptype == "G" || ptype == "Q")) {
        disableCtrl(bedsID, true);
        disableCtrl(furnishedID, true);
        return;
    } else if (ptype != null && (ptype == "FS" || ptype == "I" || ptype == "J")) {
        disableCtrl(bedsID, true);
        disableCtrl(furnishedID, false);
        return;
    }
    disableCtrl(bedsID, false);
    disableCtrl(furnishedID, false);
}

function CalculateMatches_CallBack(response) {
    SetAjaxMsg("");
    if (response.error != null) {
        return;
    }
    if (response.value != null && response.value != 1) {
        SetAjaxMsg(response.value + " properties available");
    }
    else if (response.value != null && response.value == 1) {
        SetAjaxMsg(response.value + " property available");
    }

}

function WriteToSession() {
    var city = document.getElementById(cityID).value;
    var lp = document.getElementById(lpID).value;
    var up = document.getElementById(upID).value;
    var beds = document.getElementById(bedsID).value;
    var furnished = document.getElementById(furnishedID).value;
    var type = document.getElementById(typeID).value;
    var has_images = document.getElementById(has_imagesID).checked;
    var freetext = document.getElementById('freetext').value;
    SearchControlBase.WriteToSession(city, lp, up, beds, furnished, type, has_images, freetext);
    return true;
}



function RestoreSMSButton() {
    var button = document.getElementById('alertClick');
    if (button != null) {
        button.value = "Update";
        document.body.style.cursor = 'default';
        button.enabled = true;
    }
}

function showHideMobile() {
    if (document.getElementById(alertEmailOnlyID).checked)
        document.getElementById(mobileID).style.display = "none";
    else
        document.getElementById(mobileID).style.display = "inline";
}


function UpdateSearching_CallBack(response) {
    //if the server side code threw an exception
    RestoreSMSButton();
    if (response.error != null) {
        alert("Error updating search criteria!");
        return;
    }
    if (response.value != null) {
        alert(response.value);
    }

}
function WriteToSession_CallBack(response) {
    return true;
}

function GetLocations(val) {
    if (val && val != "" && val != "0" && val != " ") {
        //document.getElementById("AreasDiv").style.display = "";
        LoadingAreasDiv();
        locationsLoaded = false;
        SearchControlBase.GetLocations(val, GetLocations_CallBack);
    }
    else {
        EmptyAreasDiv();
        //document.getElementById("AreasDiv").style.display = "none";
    }
}
function GetLocations_CallBack(response) {
    //if the server side code threw an exception
    if (response.error != null) {
        //alert("Error loading areas for selected city!!!"); //we should probably do better than this
        return;
    }
    locationsLoaded = true;;
    FillAreasDiv(response);
    CheckLocations();
    if (calcMatchesAfterLoad) { calcMatchesAfterLoad = false;CalculateMatches(); }
}
function LoadingAreasDiv() {
    if (searchType == 'F') return;
    EmptyAreasDiv();
    var checksTable = document.getElementById("CityAreas");
    var row = checksTable.insertRow(checksTable.rows.length);
    var cellLeft = row.insertCell(0);
    //cellLeft.className = "formboxheadertext";
    cellLeft.innerHTML = "<b>Loading...</b>"
}

function FillAreasDiv(response) {
    if (searchType == 'F') return;
    EmptyAreasDiv();
    var checksTable = document.getElementById("CityAreas");
    var row = checksTable.insertRow(checksTable.rows.length);
    var cellLeft;
    var cellPad;

    if (searchType != 'V') {
        cellLeft = row.insertCell(0);
        cellPad = row.insertCell(1);
        cellLeft.onclick = AllClick;
    }



    //var cellClose = row.insertCell(0);
    //cellClose.align='right';

    RemoveAllSubAreaToList();
    //cellLeft.className = "formboxheadertext";
    if ((response.value != null) && (response.value.length > 0)) {
        areaRows = 0;
        checkedRow = -1;
        if (searchType != 'V') {
            cellLeft.innerHTML = "<input type='checkbox' id='checkAll' name = 'checkAll' onclick='AllClick'/><b>All</b>";
        }
        row = checksTable.insertRow(checksTable.rows.length);
        for (var i = 0; i < response.value.length; i++) {
            row = AppendCheckCell(response.value[i].areaName, response.value[i].areaId, response.value[i].check, row, checksTable);
        }
    }
    else {
        if (cellLeft != null) cellLeft.innerHTML = "<b>No areas found</b>"
    }
    if (checkedRow != -1) {
        /* Move the scrollbar down to the bottom */
        var obj = document.getElementById('CityAreasDiv');
        obj.scrollTop = (obj.scrollHeight / areaRows * checkedRow);
    } else {
        var obj = document.getElementById('CityAreasDiv');
        obj.scrollTop = 0;
    }
    document.getElementById('CityAreasDiv').style.overflow = 'auto';
}
function AppendCheckCell(name, id, check, row, tbl) {
    if (check || document.getElementById(areaID).value == id) {
        checkedRow = areaRows;
    }
    if (row.cells.length == (searchType == 'H' ? 4 : 3)) {
        row = tbl.insertRow(tbl.rows.length);
        areaRows++;
    }
    var cellLeft = row.insertCell(row.cells.length);
    //cellLeft.className = "formboxheadertext";
    var el = document.createElement('input');
    el.type = 'checkbox';
    el.name = 'checkArea';
    el.defaultChecked = check;
    el.id = 'check_' + id;
    cellLeft.appendChild(el);
    el.onclick = AreaCheckClick;

    var textNode = document.createTextNode(name);
    var boldNode = document.createElement("b");
    if (check) {
        boldNode.appendChild(textNode);
        cellLeft.appendChild(boldNode);
        AddSubAreaToList(name);
        el.disabled = true;
    } else {
        cellLeft.appendChild(textNode);
        el.disabled = false;
    }
    return row;
}
function EmptyAreasDiv() {
    var checksTable = document.getElementById("CityAreas");
    if (checksTable == null) return;
    while (checksTable.rows.length > 0) {
        checksTable.deleteRow(0);
    }
    document.getElementById('CityAreasDiv').style.overflow = 'auto';
}
function AllClick(e, obj) {
    AllClick_Internal();
    RemoveAllSubAreaToList();
    CalculateMatches();
}
function AllClick_Internal() {
    var boolCheck = document.getElementById("checkAll").checked;
    var checksTable = document.getElementById("CityAreas");
    for (var i = 0; i < checksTable.rows.length; i++) {
        for (var j = 0; j < checksTable.rows[i].cells.length; j++) {
            if (checksTable.rows[i].cells[j].childNodes[0] != null) {
                if (checksTable.rows[i].cells[j].childNodes[0].name == "checkArea")
                    checksTable.rows[i].cells[j].childNodes[0].checked = boolCheck;
            }
        }
    }
}
function AreaCheckClick(e, obj) {
    if (searchType != 'V')
        document.getElementById("checkAll").checked = false;
    //document.getElementById("forceerror").checked = false;
    var ev = e || window.event; // IE doesn't pass event as argument.
    var target = ev.target || ev.srcElement; // IE doesn't use .target

    if (searchType == 'A' || searchType == 'V')
        CalculateMatches();

    var name;
    if (!target.nextSibling.data) {
        name = target.nextSibling.firstChild.data;
    } else {
        name = target.nextSibling.data;
    }
    if (target.checked) {
        AddSubAreaToList(name);
    } else {
        RemoveSubAreaToList(name);
    }

}

function IE6ProblemDropDowns() {
    if (ie6 && DropDownSortId != "") {
        if (document.getElementById(DropDownSortId).style.visibility == 'visible' || document.getElementById(DropDownSortId).style.visibility == '') {
            document.getElementById(DropDownSortId).style.visibility = 'hidden';
        } else if (document.getElementById(DropDownSortId).style.visibility == 'hidden') {
            document.getElementById(DropDownSortId).style.visibility = 'visible';
        }
        if (document.getElementById(DropDownSizeId).style.visibility == 'visible' || document.getElementById(DropDownSizeId).style.visibility == '') {
            document.getElementById(DropDownSizeId).style.visibility = 'hidden';
        } else if (document.getElementById(DropDownSizeId).style.visibility == 'hidden') {
            document.getElementById(DropDownSizeId).style.visibility = 'visible';
        }
    }
}

function AddSubAreaToList(area) {
    if (searchType != 'V') return;
    var areas = document.getElementById('SelectedAreas').innerHTML;

    if (areas == null) areas = '';
    if (areas.indexOf('&gt; ' + area) == 0 || areas.indexOf(", " + area + ", ") != -1 || areas.indexOf(', ' + area) == areas.length - (area.length + 2)) return;
    if (areas == '') {
        document.getElementById('SelectedAreas').innerHTML = '&gt; ' + area;
    } else {
        document.getElementById('SelectedAreas').innerHTML += ', ' + area;
    }
    UpdateShownSelectedAreas();
}

function RemoveAllSubAreaToList() {
    if (searchType != 'V') return;
    document.getElementById('SelectedAreas').innerHTML = '';
    UpdateShownSelectedAreas();
}

function RemoveSubAreaToList(area) {
    if (searchType != 'V') return;
    var areas = document.getElementById('SelectedAreas').innerHTML;
    areas = areas.replace(', ' + area + ', ', ', ');
    if (areas == '&gt; ' + area) {
        areas = '';
    } else if (areas.indexOf('&gt; ' + area + ', ') == 0) {
        areas = areas.replace('&gt; ' + area + ', ', '&gt; ');
    } else if (areas.indexOf(', ' + area) == areas.length - (area.length + 2)) {
        areas = areas.replace(', ' + area, '');
    }
    document.getElementById('SelectedAreas').innerHTML = areas;
    UpdateShownSelectedAreas();
}
function UpdateShownSelectedAreas() {
    if (searchType != "V") return;
    var areas = document.getElementById('SelectedAreas').innerHTML;
    if (areas == '') {
        document.getElementById('ShownSelectedAreas').style.display = 'none';
        return;
    } else {
        document.getElementById('ShownSelectedAreas').style.display = 'block';
    }
    if (areas.length > 54) {
        var aArr = areas.split(',');
        var newAreas;
        var tmpArea;
        newAreas = aArr[0];
        for (i = 1; i < aArr.length; i++) {
            tmpArea = newAreas + ', ' + aArr[i];
            if (tmpArea.length > 45) {
                newAreas = newAreas + "...";
                break;
            } else {
                newAreas = newAreas + ", "+aArr[i];
            }
        }
        document.getElementById('ShownSelectedAreas').innerHTML = newAreas
        console.log(newAreas);
    } else {
        document.getElementById('ShownSelectedAreas').innerHTML = areas;
        console.log(areas);
    }
}

var sbShown = false;
function ToggleAreaDiv() {
    if (!sbShown) {
        document.getElementById('CityAreasDiv').style.visibility = 'visible';
        document.getElementById('CityAreasDiv').style.overflow = 'auto';
        sbShown = true;
        document.getElementById('areaclick').innerHTML = 'Hide Areas';
    } else {
        document.getElementById('CityAreasDiv').style.visibility = 'hidden';
        document.getElementById('CityAreasDiv').style.overflow = 'hidden';
        document.getElementById('areaclick').innerHTML = 'Show Areas';
        sbShown = false;
    }
    IE6ProblemDropDowns();
    return false;
}

var sbAlertsShown = false;
function ToggleAlerts() {
    if (!sbAlertsShown) {
        document.getElementById('alerts').style.top = '460px';
        document.getElementById('alerts').style.left = '496px';
        document.getElementById('alerts').style.visibility = 'visible';
        sbAlertsShown = true;
    } else {
        document.getElementById('alerts').style.visibility = 'hidden';
        sbAlertsShown = false;
    }
    return false;
}
function ToggleAlertsUp() {
    if (!sbAlertsShown) {
        document.getElementById('alerts').style.visibility = 'visible';
        document.getElementById('alerts').style.top = '50px';
        document.getElementById('alerts').style.left = '478px';
        sbAlertsShown = true;
    } else {
        document.getElementById('alerts').style.visibility = 'hidden';
        sbAlertsShown = false;
    }
    return false;
}
function isInt(input) {
    return ((input - 0) == input && input % 1 == 0);
}

function validateForm() {
    var cityVal = getSearchValue();
    if (cityVal == text && searchType == "F") {
        alert("Please Enter Postcode, City, Area!");
        return false;
    }
    if (cityVal == "" || cityVal == " " || cityVal == text) {
        if (searchType != "F") {
            alert("Please select a Location or Enter Postcode, City, Area!");
        } else {
            alert("Please Enter Postcode, City, Area!");
        }
        if (searchType != "F" && cityID != null && document.getElementById(cityID) != null) {
            document.getElementById(cityID).focus();
        }
        return false;
    }
    if (!checkArea()) {
        return false;
    }
    if (document.getElementById(lpID).value != "") {
        if (!isInt(document.getElementById(lpID).value)) {
            alert("Lower price range must be a number");
            document.getElementById(lpID).focus();
            return false;
        }
    }
    if (document.getElementById(upID).value != "") {
        if (!isInt(document.getElementById(upID).value)) {
            alert("Upper price must be a number");
            document.getElementById(upID).focus();
            return false;
        }
    }
    if (document.getElementById(upID).value == "" && document.getElementById(lpID).value == "") {
        document.getElementById(lpID).value = "0";
        document.getElementById(upID).value = "9999";
    }
    if (document.getElementById(upID).value != "" && document.getElementById(lpID).value == "") {
        document.getElementById(lpID).value = "0";
    }
    if (document.getElementById(lpID).value != "" && document.getElementById(upID).value == "") {
        document.getElementById(upID).value = "9999";
    }
    if (parseInt(document.getElementById(upID).value) < parseInt(document.getElementById(lpID).value)) {
        alert("Upper price must not be lower than lower price");
        document.getElementById(lpID).focus();
        return false;
    }

    if (navigator.userAgent.toLowerCase().indexOf("opera") != -1) {
        setButtonImage();
    }
    else {
        var t = setTimeout("setButtonImage()", 10);
    }
    return true;

}

function setButtonImage() {
    if (Submit1ID == null || searchType == 'F') return;
    document.getElementById(Submit1ID).src = imgSub.src;
}

function checkEnter(e) {
    var characterCode
    if (e == null) return true;
    if (e && e.which) {
        characterCode = e.which;
    }
    else {
        characterCode = e.keyCode;
    }

    if (characterCode == 13) {
        return false;
    }
    else {
        return true;
    }
}

function checkEnterFromFreeText(evt) {
    if (evt.keyCode != dojo.keys.ENTER) {
        return true;
    }
    if (validateForm()) document.getElementById(Submit1ID).click();
    dojo.stopEvent(evt);
    return false;
}


function noValidSuffix(formField) {
    if (formField.indexOf('@', 0) > 1 && formField.charAt(formField.length - 1) == ']') {
        return (false);
    }
    var len = formField.length;
    var pos = formField.lastIndexOf('.', len - 1) + 1;
    if ((len - pos) < 2 || (len - pos) > 4) {
        return (true);
    } else {
        return (false);
    }
}

function checkEmail(str) {
    if (str.indexOf('@', 0) == -1) return false;
    if (str.length < 2) return false;
    if (str.indexOf('.', 0) == -1) return false;
    if (noValidSuffix(str)) return false;

    return true;
}

function checkSMS(button) {
    if (searchType == 'A' && !(document.getElementById(smsID).checked)) {
        return true;
    }
    var city = getSearchValue();
    var freetext = "";
    var freetextSearch = false;

    if (city.charCodeAt(0) <= 47 || city.charCodeAt(0) >= 58) {
        freetext = city;
        city = "";
        freetextSearch = true;
    }
    if (((freetext == text || freetext=="") && freetextSearch) || (city=="" && !freetextSearch)) {
        alert('You must select a city or type a city area to receive sms alerts');
        document.getElementById(cityID).focus();
        return false;
    }
    if (document.getElementById("emailAlerts") != null && (searchType == 'H' || searchType == 'F'))
        document.getElementById("emailAlerts").style.display = "inline";

    if (document.getElementById(nameID).value == '' || document.getElementById(nameID).value == 'enter name') {
        alert('You must supply your name if you are registering for alerts');
        document.getElementById(nameID).focus();
        return false;
    }

    if (!checkEmail(document.getElementById(emailID).value)) {
        alert('You must supply a valid email address');
        document.getElementById(emailID).focus();
        return false;
    }

    var ph = document.getElementById(mobileID).value;

    if (!document.getElementById(alertEmailOnlyID).checked) {
        if (ph.length != 11 || ph.charAt(1) != '7' || ph.charAt(0) != '0') {
            alert("Mobile number Invalid. It must be start with 07 and contain only numbers (no spaces), and be 11 digits long.");
            document.getElementById(mobileID).value = '';
            document.getElementById(mobileID).focus();
            return false;
        }
        for (i = 0; i < ph.length; i++) {
            var test = parseInt(ph.charAt(i))
            if (isNaN(test)) {
                alert("Mobile number invalid. It must be start with 07 and contain only numbers (no spaces), and be 11 digits long.");
                document.getElementById(mobileID).value = '';
                document.getElementById(mobileID).focus();
                return false;
            }
        }
    }
    checkArea();

    button.value = "Updating";
    document.body.style.cursor = 'wait';
    button.enabled = false;
    alert('Click OK to contact Citylets to update your alert criteria based on the search criteria entered. This may take a few seconds. Please wait!');


    if (searchType == 'V') {
        ToggleAlerts();
    }
    var stud = (document.getElementById(studentID).checked ? "yes" : "");

    var cityVal = (freetextSearch ? "FREETEXT:" + freetext : city);

    var type;
    if (document.getElementById(typeID).value == null) {
        type = djType.get("value");
    } else {
        type = document.getElementById(typeID).value;
    }
    var furnished;
    if (document.getElementById(furnishedID).value == null) {
        furnished = djFurnished.get("value");
    } else {
        furnished = document.getElementById(furnishedID).value;
    }
    var beds;
    if (document.getElementById(bedsID).value == null) {
        beds = djBeds.get("value");
    } else {
        beds = document.getElementById(bedsID).value;
    }
    var typeoflet;
    if (document.getElementById(typeOfLetID).value == null) {
        typeoflet = djTypeOfLet.get("value");
    } else {
        typeoflet = document.getElementById(typeOfLetID).value;
    }

    /*
    alert(document.getElementById(nameID).value + document.getElementById(emailID).value + ph +  cityVal + 
                document.getElementById(areaID).value +  document.getElementById(lpID).value + document.getElementById(upID).value +
                type + stud + furnished +
                beds + typeoflet + 
                (document.getElementById(alertEmailOnlyID).checked ? "Y" : "N"));
    */

    UpdateSearching(document.getElementById(nameID).value, document.getElementById(emailID).value, ph, cityVal,
                document.getElementById(areaID).value, document.getElementById(lpID).value, document.getElementById(upID).value,
                type, stud, furnished,
                beds, typeoflet,
                (document.getElementById(alertEmailOnlyID).checked ? "Y" : "N")
                );
    if (searchType == 'H' || searchType == 'F') {
        HideAlertBox();
    }
    return false;
}


function checkArea() {
    if (searchType == 'F') return true;
    var found = false;
    var hArea = document.getElementById(areaID);
    hArea.value = "0";
    if ((document.getElementById("checkAll") != null) && (document.getElementById("checkAll").checked))
        hArea.value = "0";
    else {
        var selectionList = "";
        var checksTable = document.getElementById("CityAreas");
        for (var i = 0; i < checksTable.rows.length; i++) {
            for (var j = 0; j < checksTable.rows[i].cells.length; j++) {
                var firstKid = checksTable.rows[i].cells[j].childNodes[0];
                if (firstKid != null) {
                    if (firstKid.name == "checkArea")
                        if (firstKid.checked == true) {
                            selectionList += firstKid.id.substring(6, firstKid.id.length) + ",";
                        }
                }
            }
        }
        if (selectionList.length > 0) {
            hArea.value = selectionList.substring(0, selectionList.length - 1);
        }
        else {
            hArea.value = "-1";
        }
    }
    return true;
}

function CheckLocations() {
    var hArea = document.getElementById(areaID).value;
    var ids = hArea.split(",");
    var boolPreselectAll = false;

    if (hArea != null && hArea != "" && searchType == 'H') {
        // We have areas so we must open the areas box
        if (document.getElementById('AreasDiv') != null && document.getElementById('CityAreasDiv') != null) {
            OpenAreas();
        }
    }

    for (var i = 0; i < ids.length; i++) {
        var posibbleCheck = document.getElementById("check_" + ids[i]);
        if (posibbleCheck != null) {
            if (ids[i] != "checkAll")
                boolPreselectAll = true;
            posibbleCheck.checked = true;
            var name;
            if (!posibbleCheck.nextSibling.data) {
                name = posibbleCheck.nextSibling.firstChild.data;
            } else {
                name = posibbleCheck.nextSibling.data;
            }
            AddSubAreaToList(name);
        }
    }
    //document.getElementById(areaID).value = "";
    // Removed by TDK 
    if (!boolPreselectAll) {
        if (document.getElementById("checkAll") != null) {
            if (ids.length == 0 || ids[0] == "0") {
                document.getElementById("checkAll").checked = true;
                AllClick_Internal();
            }
        }
    }
}

function PreSelect(ctrl, text) {

    switch (text) {
        case 'name':
            if (ctrl.value.toLowerCase() == "enter name")
                ctrl.select()
            break;
        case 'email':
            if (ctrl.value.toLowerCase() == (searchType == 'F' ? "enter email" : "enter email"))
                ctrl.select()
            break;
        case 'mobile':
            if (ctrl.value.toLowerCase() == (searchType == 'F' ? "enter mobile" : "enter mobile"))
                ctrl.select()
            break;

    }
}

function ShowSearchControl(parent) {
    var thisContent = document.getElementById('SearchControlContent');
    parent.appendChild(thisContent);
    thisContent.style.display = "";
}


function AddToInfoPos(i) {
    /* We no longer want to change the infopos div here. We may require this in the future though */
    return;
    if (searchType != 'H' || searchType == 'F') return;
    var mt = document.getElementById('main').style.marginTop;
    if (mt != null) {
        var j = parseInt(mt);
        document.getElementById('main').style.marginTop = (j + i) + "px";
    }
}

function OpenAreas() {
    if (document.getElementById('AreasDiv') == null) return;
    document.getElementById('AreasDiv').style.height = "260px";
    document.getElementById('CityAreasDiv').style.height = "250px";
    document.getElementById('CityAreasDiv').style.border = "solid 1px #aaa";
    if (document.getElementById('areaspanectrl') != null)
        document.getElementById('areaspanectrl').src = bp + "/images/up.gif";
    if (searchType == 'A')
        document.getElementById('areaselect').style.visibility = "visible";
    if (!areasOpen) {
        AddToInfoPos(180);
        areasOpen = true;
    }
    if (searchType == 'H') {
        document.getElementById('areaselect').style.visibility = "visible";
    }
}
function CloseAreas() {
    if (document.getElementById('AreasDiv') == null) return;
    document.getElementById('AreasDiv').style.height = (searchType == 'A' ? "180px" : "16px");
    document.getElementById('CityAreasDiv').style.height = "0px";
    document.getElementById('CityAreasDiv').style.border = "0";
    if (document.getElementById('areaspanectrl') != null)
        document.getElementById('areaspanectrl').src = bp + "/images/down.gif";
    if (areasOpen) {
        AddToInfoPos(-180);
        areasOpen = false;
    }
    if (searchType == 'A')
        document.getElementById('areaselect').style.visibility = "hidden";
}


function ShowHideAreas() {
    if (searchType == 'F') return;
    if (document.getElementById(cityID).selectedIndex == 0) {
        CloseAreas();
        document.getElementById('areaselect').style.visibility = 'hidden';
        if (document.getElementById('areaspanectrl').style.visibility == 'visible') {
            document.getElementById('areaspanectrl').style.visibility = 'hidden';
        }
    }
    else {
        OpenAreas();
        if (document.getElementById('areaselect') == null) return;
        document.getElementById('areaselect').style.visibility = 'visible';
        GetLocations(document.getElementById(cityID).value);
    }
}
function ShowHideAreas2(value) {
    if (searchType == 'F') return;
    if (value==text) {
        CloseAreas();
        if (document.getElementById('areaselect') == null || document.getElementById('areaspanectrl') == null) return;
        document.getElementById('areaselect').style.visibility = 'hidden';
        if (document.getElementById('areaspanectrl').style.visibility == 'visible') {
            document.getElementById('areaspanectrl').style.visibility = 'hidden';
        }
    }
    else {
        OpenAreas();
        GetLocations(value);
    }
}


function ToggleAreaBox() {
    if ((document.getElementById('AreasDiv').style.height == "16px" || document.getElementById('AreasDiv').style.height == "") && document.getElementById(cityID).selectedIndex != 0) {
        OpenAreas();
    } else {
        CloseAreas();
    }
}


function ToggleAlertBoxAdvanced() {
    if (document.getElementById('alerts') == null) return;
    if (document.getElementById(nameID).disabled) {
        disableCtrl(nameID, false);
        disableCtrl('alertClick', false);
        disableCtrl(emailID, false);
        disableCtrl(mobileID, false);
        disableCtrl(alertEmailOnlyID, false);
        document.getElementById(nameID).focus();
        if (!alertOpen) {
            alertOpen = true;
        }
    } else {
        disableCtrl(nameID, true);
        disableCtrl('alertClick', true);
        disableCtrl(emailID, true);
        disableCtrl(mobileID, true);
        disableCtrl(alertEmailOnlyID, true);
        if (alertOpen) {
            alertOpen = false;
        }
    }
}

function ShowAlertBox() {
    document.getElementById('line3').style.display = 'none';
    document.getElementById('line3-alert-box').style.display = 'block';
    return 0;
    SetAjaxMsg("");
}
function HideAlertBox() {
    document.getElementById('line3-alert-box').style.display = 'none';
    document.getElementById('line3').style.display = 'block';
    return 0;
}

function ToggleAlertBox() {
    if (searchType == 'A') return ToggleAlertBoxAdvanced();

    if (document.getElementById('alerts') == null) return;
    if (document.getElementById('alerts').style.display == "none") {
        document.getElementById('alerts').style.height = "block";
        document.getElementById(Submit1ID).style.visibility = "hidden";
        document.getElementById(nameID).focus();
        if (!alertOpen) {
            AddToInfoPos(23);
            alertOpen = true;
        }
    } else {
        document.getElementById('alerts').style.display = "none";
        document.getElementById(Submit1ID).style.visibility = "block";
        if (alertOpen) {
            AddToInfoPos(-23);
            alertOpen = false;
        }
    }
}

// Called from vertical search control when the city is selected or the free text box is updated
function VCityOrFreetextChanged(parent) {
    if (parent.id == "freetext") {
        if (document.getElementById('freetext').value == text) {
            document.getElementById('freetext').value = "";
            document.getElementById(cityID).selectedIndex = 0;
            EmptyAreasDiv();
            document.getElementById(areaID).value = "-1";
            RemoveAllSubAreaToList();
            if (sbShown) ToggleAreaDiv();
        }

    }
    else
        if (parent.id == cityID) {
            document.getElementById('freetext').value = text;

            if (document.getElementById(cityID).selectedIndex == 0) {
                EmptyAreasDiv();
                document.getElementById(areaID).value = "-1"; // Blank out any selected areas
                RemoveAllSubAreaToList();
                if (sbShown) ToggleAreaDiv()
            }
            else {
                document.getElementById(areaID).value = "-1"; // Blank out any selected areas
                calcMatchesAfterLoad = true;
                GetLocations(document.getElementById(cityID).value);
                if (document.getElementById('areaspan') != null)
                    document.getElementById('areaspan').style.visibility = 'visible';
            }
        }
}

// Called from horizontal search control when the city is selected or the free text box is updated
function HCityOrFreetextChanged(parent) {
    if (parent.id == "freetext") {
        if (document.getElementById('freetext').value == text) {
            document.getElementById('freetext').value = "";
            document.getElementById(cityID).selectedIndex = 0;
            EmptyAreasDiv();
            ShowHideAreas();
        }

    }
    else
        if (parent.id == cityID) {
            if (parent.value != cityValue) {
                cityValue = parent.value;
            } else {
                return;
            }
            ShowHideAreas();
            document.getElementById('freetext').value = text;
            if (searchType == "A") {
                window.parent.document.getElementById(cityID).value = parent.value;
            }
            CalculateMatches();
        }

}

function lpchanged(obj) {
    if (searchType == "A") {
        window.parent.document.getElementById(lpID).value = obj.value;
    }
    CalculateMatches();
}
function upchanged(obj) {
    if (searchType == "A") {
        window.parent.document.getElementById(upID).value = obj.value;
    }
    CalculateMatches();
}
function BedsChanged(obj) {
    if (searchType == "A") {
        parent.djBeds.set('value', obj.value);
    }
    CalculateMatches();
}
function TypeChanged(obj) {
    if (searchType == "A") {
        parent.djType.set("value", obj.value);
    }
    CalculateMatches();
}
function FurnishedChanged(obj) {
    if (searchType == "A") {
        parent.djFurnished.set("value", obj.value);
    }
    CalculateMatches();
}
function HasImagesChanged(obj) {
    if (searchType == "A") {
        window.parent.document.getElementById(has_imagesID).checked = obj.checked;
    }
    CalculateMatches();
}
function AddTextOnFreeText() {
    if (document.getElementById('freetext').value == "") {
        document.getElementById('freetext').value = text;
    }
}
var freeTextChangeTimer = null;
function ChangeFreeText() {
    if (freeTextChangeTimer != null) {
        clearTimeout(freeTextChangeTimer);
        freeTextChangeTimer = null;
    }
    freeTextChangeTimer = setTimeout("freeTextChanged()", 1000);
}
function freeTextChanged() {
    freeTextChangeTimer = null;
    //console.debug(document.getElementById('freetext').value);
    CalculateMatches();
}

function AddToOptionList(OptionList, OptionValue, SelectedValue, OptionText) {
    var opt = document.createElement("option");
    opt.innerHTML = OptionText;
    opt.value = OptionValue;

    if (OptionValue == SelectedValue) {
        opt.setAttribute("selected", "selected");
    }
    OptionList.appendChild(opt);
}

function AddToOptionToCity(OptionText, OptionValue) {
    var cityList = document.getElementById(cityID);
    var opt = document.createElement("option");
    opt.innerHTML = OptionText;
    opt.value = OptionValue;
    if (OptionValue == cityValue) opt.setAttribute("selected", "selected");
    cityList.appendChild(opt);
}

function PopulateTypeOfLet() {

    var typeOfLetList = document.getElementById(typeOfLetID);
    if (searchType == 'F') {
        AddToOptionList(typeOfLetList, "", "", "Any");
        return;
    }

    if (searchType != 'V') {
        if (product == "short-term") {
            AddToOptionList(typeOfLetList, "S", typeOfLetValue, "Short term");
            return;
        }
        if (product == '') {
            AddToOptionList(typeOfLetList, "L", typeOfLetValue, "Long term (>6 mths)");
            return;
        }
        if (product == 'student' || product == 'parking' || product == 'flat-share') {
            AddToOptionList(typeOfLetList, "", typeOfLetValue, "All");
        }
    } else {
        AddToOptionList(typeOfLetList, "", typeOfLetValue, "All");
        AddToOptionList(typeOfLetList, "L", typeOfLetValue, "Long term (>6 mths)");
        AddToOptionList(typeOfLetList, "S", typeOfLetValue, "Short term");
        AddToOptionList(typeOfLetList, "F", typeOfLetValue, "Edinburgh Festival");
    }
}


function PopulateBackInTime() {

    var backInTimeList = document.getElementById(backInTimeID);

    AddToOptionList(backInTimeList, "1", backintimeValue, "in last Day");
    AddToOptionList(backInTimeList, "2", backintimeValue, "in last Week");
    AddToOptionList(backInTimeList, "3", backintimeValue, "in last Month");
    AddToOptionList(backInTimeList, "4", backintimeValue, "in last 3 Mths");
    AddToOptionList(backInTimeList, "0", backintimeValue, "Any Time");
}

function PopulateType() {
    var typeList = document.getElementById(typeID);
    if (searchType == 'F') {
        AddToOptionList(typeList, "A", "A", "Any");
        return;
    }
    if (searchType == 'V' || (product != "parking" && product != "flat-share")) {
        AddToOptionList(typeList, "A", typeValue, "Any");
        AddToOptionList(typeList, "FF", typeValue, "Flats");
        AddToOptionList(typeList, "F", typeValue, "- Flat/Apartment");
        AddToOptionList(typeList, "S", typeValue, "- Studio");
        AddToOptionList(typeList, "P", typeValue, "- Penthouse");
        AddToOptionList(typeList, "SA", typeValue, "- Serviced Apartment");
        AddToOptionList(typeList, "D", typeValue, "- Double upper");
        AddToOptionList(typeList, "HH", typeValue, "House");
        AddToOptionList(typeList, "H", typeValue, "- Detached House");
        AddToOptionList(typeList, "SH", typeValue, "- Semi Detached House");
        AddToOptionList(typeList, "TH", typeValue, "- Terraced House");
        AddToOptionList(typeList, "T", typeValue, "- Town House");
        AddToOptionList(typeList, "M", typeValue, "- Mews");
        AddToOptionList(typeList, "B", typeValue, "- Bungalow");
        AddToOptionList(typeList, "V", typeValue, "- Villa");
        AddToOptionList(typeList, "C", typeValue, "- Cottage");
    }
    if (searchType == 'V' || product == "flat-share") {
        AddToOptionList(typeList, "FS", typeValue, "Flatshare");
        AddToOptionList(typeList, "I", typeValue, "- Single room");
        AddToOptionList(typeList, "J", typeValue, "- Double room");
    }
    if (searchType == 'V' || product == "parking") {
        AddToOptionList(typeList, "PP", typeValue, "Parking");
        AddToOptionList(typeList, "G", typeValue, "- Garage");
        AddToOptionList(typeList, "Q", typeValue, "- Parking Space");
    }
    if (searchType == 'V') VChangePropertyType();
}

function PopulateBeds() {
    var bedsList = document.getElementById(bedsID);
    AddToOptionList(bedsList, "1", bedsValue, "1");
    var i = 2;
    for (i = 2; i <= 10; i++) {
        AddToOptionList(bedsList, i + "", bedsValue, i + "");
    }
}

function PopulateFurnished() {
    var furnishedList = document.getElementById(furnishedID);
    AddToOptionList(furnishedList, "", furnishedValue, "Any");
    AddToOptionList(furnishedList, "Y", furnishedValue, "Full");
    AddToOptionList(furnishedList, "P", furnishedValue, "Part");
    AddToOptionList(furnishedList, "N", furnishedValue, "None");
}

/* 
* THIS IS TO KEEP THE CITY NAMES OFF THE PAGE. PLEASE NOTE WHEN CITIES ARE ADDED 
* THIS JAVASCRIPT MUST BE UPDATED
*
*/
function disableCtrl(ctrl, b) {
    if (document.getElementById(ctrl) != null) document.getElementById(ctrl).disabled = b;
}
function greyDiv(ctrl) {
    if (document.getElementById(ctrl) != null) document.getElementById(ctrl).style.color = '#ccc';
}

// Depending on the product we might want to change the GUI
function ProcessProduct() {
    if (product == "flat-share") {
        disableCtrl(bedsID, true);
        greyDiv('bedrooms');
    }
    if (product == "parking") {
        disableCtrl(furnishedID, true);
        greyDiv('furnishings');
        disableCtrl(bedsID, true);
        greyDiv('bedrooms');
        disableCtrl(studentID, true);
        disableCtrl(dssID, true);
    }
    if (product == "student") {
        document.getElementById(studentID).checked = true;
    }
}

function PopulateOptionLists() {
    PopulateTypeOfLet();
    PopulateBackInTime();
    PopulateType();
    PopulateBeds();
    PopulateFurnished();
    if (searchType != 'V') ProcessProduct();

    if (searchType == 'A') ShowHideAreas();
}

function mktbe(href) {
    return href + '&thickbox=Y&TB_iframe=true&height=345&width=610';
}

function advancedClick(href) {
    SetAjaxMsg("");
    var city = getSearchValue();
    var freetext = "";
    //if (city == null || city == "Please select..." || city == " " || city == "") { return; }
    /* If city starts with a number it is a city/area picked from the list */
    if (city.charCodeAt(0) <= 47 || city.charCodeAt(0) >= 58) {
        freetext = city;
        city = "";
    }
    var lp = document.getElementById(lpID).value;
    var up = document.getElementById(upID).value;
    var beds = djBeds.get("value");
    var furnished = djFurnished.get("value");
    var type = djType.get("value");
    var has_images = document.getElementById(has_imagesID).checked;
    var x = (735 <= parseInt(winW() * 0.9) ? 735 : parseInt(winW() * 0.9));
    var y = (320 <= parseInt(winH() * 0.9) ? 320 : parseInt(winH() * 0.9));
    //alert('?c_id=' + city + '&lp=' + lp + '&up=' + up + '&beds=' + beds + '&type=' + type + '&furnished=' + furnished + '&has_images=' + (has_images ? "Y" : "N") + '&product=' + product + '&freetext=' + freetext + '&thickbox=Y&TB_iframe=true&height=' + y + '&width=' + x);
    return href + '?c_id=' + city + '&lp=' + lp + '&up=' + up + '&beds=' + beds + '&type=' + type + '&furnished=' + furnished + '&has_images=' + (has_images ? "Y" : "N") + '&product=' + product + '&freetext=' + freetext  + '&thickbox=Y&TB_iframe=true&height=' + y + '&width=' + x;
}

