﻿/////////////variables

var fieldsGroups = [];

var currentTextBox = null;
var lastSearchText = '';
var currentSelectionIndex = null;
var currentValuesTable = [];
var provinceFields = [];
var provinceFieldsNames = [];

///////////////////// init

function SubscribeLocationFieldsEvents() {
    InitFieldsGroup();
    //InitValueTable();
    InitProvinceFields();

    AttachEvents(0);
    AttachEvents(1);
    AttachEvents(2);
    AttachEvents(3);
    AttachEvents(4);
    AttachEvents(5);
    AttachEvents(6);
}

function InitFieldsGroup() {

    //mieszkania
    fieldsGroups[0] = ['ddlFlatProvince', 'ucMainSearchBox_txtFlatLocation', 'ucMainSearchBox_txtFlatStreet'];
    //domy
    fieldsGroups[1] = ['ddlHouseProvince', 'ucMainSearchBox_txtHouseLocation', 'ucMainSearchBox_txtHouseStreet'];
    //dzialki
    fieldsGroups[2] = ['ddlGroundProvince', 'ucMainSearchBox_txtGroundLocation', 'ucMainSearchBox_txtGroundStreet'];
    //lokale
    fieldsGroups[3] = ['ddlLocalProvince', 'ucMainSearchBox_txtLocalLocation', 'ucMainSearchBox_txtLocalStreet'];
    //obiekty
    fieldsGroups[4] = ['ddlObjectProvince', 'ucMainSearchBox_txtObjectLocation', 'ucMainSearchBox_txtObjectStreet'];
    //posrednicy
    fieldsGroups[5] = ['', 'ucMainSearchBox_txtAgentLocation', ''];
    //firmy
    fieldsGroups[6] = ['', 'ucMainSearchBox_txtOfficeLocation', ''];

}

function InitValueTable() {
    currentValuesTable['ucMainSearchBox_txtFlatLocation'] = '';
    currentValuesTable['ucMainSearchBox_txtFlatStreet'] = '';
    currentValuesTable['ucMainSearchBox_txtHouseLocation'] = '';
    currentValuesTable['ucMainSearchBox_txtHouseStreet'] = '';
    currentValuesTable['ucMainSearchBox_txtGroundLocation'] = '';
    currentValuesTable['ucMainSearchBox_txtGroundStreet'] = '';
    currentValuesTable['ucMainSearchBox_txtLocalLocation'] = '';
    currentValuesTable['ucMainSearchBox_txtLocalStreet'] = '';
    currentValuesTable['ucMainSearchBox_txtObjectLocation'] = '';
    currentValuesTable['ucMainSearchBox_txtObjectStreet'] = '';
    currentValuesTable['ucMainSearchBox_txtAgentLocality'] = '';
    currentValuesTable['ucMainSearchBox_txtOfficeLocation'] = '';
}

function InitProvinceFields(){
    provinceFields['ddlFlatProvince']='ucMainSearchBox_flatSelectedProvinceId';
    provinceFields['ddlHouseProvince']='ucMainSearchBox_houseSelectedProvinceId';
    provinceFields['ddlGroundProvince']='ucMainSearchBox_groundSelectedProvinceId';
    provinceFields['ddlLocalProvince']='ucMainSearchBox_localSelectedProvinceId';
    provinceFields['ddlObjectProvince']='ucMainSearchBox_objectSelectedProvinceId';
    
    provinceFieldsNames['ddlFlatProvince']='ucMainSearchBox_flatSelectedProvinceName';
    provinceFieldsNames['ddlHouseProvince']='ucMainSearchBox_houseSelectedProvinceName';
    provinceFieldsNames['ddlGroundProvince']='ucMainSearchBox_groundSelectedProvinceName';
    provinceFieldsNames['ddlLocalProvince']='ucMainSearchBox_localSelectedProvinceName';
    provinceFieldsNames['ddlObjectProvince']='ucMainSearchBox_objectSelectedProvinceName';
}

function AttachEvents(fieldIndex) {
    var ddlField;
    var locationField;
    var streetField;

    if (fieldsGroups[fieldIndex][0] != '')
        ddlField = document.getElementById(fieldsGroups[fieldIndex][0]);

    if (fieldsGroups[fieldIndex][1] != '')
        locationField = document.getElementById(fieldsGroups[fieldIndex][1]);

    if (fieldsGroups[fieldIndex][2] != '')
        subLocationField = document.getElementById(fieldsGroups[fieldIndex][2]);

    if (locationField != null) {
        if (locationField.attachEvent) {
            locationField.attachEvent('onkeyup', HandleLocationKeyUpEvent)
            locationField.attachEvent('onkeydown', HandleLocationKeyDownEvent)
            locationField.attachEvent('onblur', HideLocationHint)
        }
        else {
            if (locationField.addEventListener) {
                locationField.addEventListener('keyup', HandleLocationKeyUpEvent, false);
                locationField.addEventListener('keydown', HandleLocationKeyDownEvent, true)
                locationField.addEventListener('blur', HideLocationHint, false);
            }
        }
    }

    if (subLocationField != null) {
        if (subLocationField.attachEvent) {
            subLocationField.attachEvent('onkeyup', HandleSubLocationKeyUpEvent)
            subLocationField.attachEvent('onkeydown', HandleLocationKeyDownEvent)
            subLocationField.attachEvent('onblur', HideLocationHint)
        }
        else {
            if (subLocationField.addEventListener) {
                subLocationField.addEventListener('keyup', HandleSubLocationKeyUpEvent, false);
                subLocationField.addEventListener('keydown', HandleLocationKeyDownEvent, false)
                subLocationField.addEventListener('blur', HideLocationHint, false);
            }
        }
    }

    if (ddlField != null) {
        if (ddlField.attachEvent) {
            ddlField.attachEvent('onchange', HandleDdlOnChange)
        }
        else {
            if (ddlField.addEventListener) {
                ddlField.addEventListener('change', HandleDdlOnChange, false);
            }
        }

        BindProvinces(fieldsGroups[fieldIndex][0]);
    }
}

////////////////////////event handlers

function HandleLocationKeyUpEvent(e) {
    switch (e.keyCode) {
        case 13:
            //enter/ opuszczmy!!
            if (currentTextBox != null) {
                HideLocationHint();
                if (e.cancelBubble != null)
                    e.cancelBubble = true;
                if (e.stopPropagation)
                    e.stopPropagation();
                if (e.preventDefault)
                    e.preventDefault();
                if (window.event)
                    e.returnValue = false;
                if (e.cancel != null)
                    e.cancel = true;
            }
            break;
        case 38:
            //strzalka do gory
            SelectUp();
            break;
        case 40:
            //strzalka w dol
            SelectDown();
            break;
        //case 32:  
        //spacja to powinno byc na enter  
        //SelectCurrent();  
        //    break;  
        case 37:
        case 39:
            //pozostale strzalki
            //ignorowane
            break;
        default:
            HideLocationHint();
            var currentFieldName = e.srcElement ? e.srcElement.id : e.target.id;
            var parentId = '';
            var index = -1;
             for (i = 0; i < fieldsGroups.length; i++) {
                if (fieldsGroups[i][1] == currentFieldName) {
                    index = i;
                    break;
                }
            }
            if (index >= 0 && index < fieldsGroups.length) {
                var provinceHf = document.getElementById(provinceFields[fieldsGroups[index][0]])
                if(provinceHf!= null){
                    parentId = provinceHf.value;
                }
            }
            
            var subLocationField = document.getElementById(fieldsGroups[index][2]);
            if(subLocationField!= null)
                subLocationField.value = '';

            setTimeout('ShowLocationHint(\'Location\',\'' + parentId + '\',\'' + currentFieldName + '\')', 100);
            break;
    }
}

function HandleLocationKeyDownEvent(e) {
    //enter albo przecinek
    if (currentTextBox != null){
        if(e.keyCode == 13) {
            //SelectLocation();
            HideLocationHint();
            if (e.cancelBubble != null)
                e.cancelBubble = true;
            if (e.stopPropagation)
                e.stopPropagation();
            if (e.preventDefault)
                e.preventDefault();
            if (window.event)
                e.returnValue = false;
            if (e.cancel != null)
                e.cancel = true;
        }
        //tab lub comma
        if(e.keyCode == 9 || e.keyCode == 188){
            //SelectLocation();
            HideLocationHint();
        }
    } 
    
}


function HideLocationHint() {

    var hint = document.getElementById('locationHintDiv');
    var locationList = document.getElementById('locationList');
    if (hint != null && locationList != null) {
        //zmiana stylu
        hint.style.display = 'none';

        //czyszczenie
        if (locationList.children.length > 0) {
            for (var i = locationList.children.length - 1; i >= 0; i--) {
                locationList.removeChild(locationList.lastChild);
            }
        }
    }

    currentSelectionIndex = null;
    currentTextBox = null;
    lastSearchText = '';
}

function HandleSubLocationKeyUpEvent(e) {
    var subLocationFieldName = e.srcElement ? e.srcElement.id : e.target.id;

    //szukamy indexu w tabeli ktorty element zostal klikniety
    var index = -1;
    for (i = 0; i < fieldsGroups.length; i++) {
        if (fieldsGroups[i][2] == subLocationFieldName) {
            index = i;
            break;
        }
    }

    if (index >= 0 && index < fieldsGroups.length) {
        var mainLocationField = document.getElementById(fieldsGroups[index][1]);
        if (mainLocationField != null) {
            if (mainLocationField.value.length > 2) {
                switch (e.keyCode) {
                    case 13:
                        //enter/ opuszczmy!!
                        if (currentTextBox != null) {
                            HideLocationHint();
                            if (e.cancelBubble != null)
                                e.cancelBubble = true;
                            if (e.stopPropagation)
                                e.stopPropagation();
                            if (e.preventDefault)
                                e.preventDefault();
                            if (window.event)
                                e.returnValue = false;
                            if (e.cancel != null)
                                e.cancel = true;
                        }
                        break;
                    case 38:
                        //strzalka do gory
                        SelectUp();
                        break;
                    case 40:
                        //strzalka w dol
                        SelectDown();
                        break;
                    //case 32:  
                    //spacja to powinno byc na enter  
                    //SelectCurrent();  
                    //    break;  
                    case 37:
                    case 39:
                        //pozostale strzalki
                        //ignorowane
                        break;
                    default:
                        HideLocationHint();
                        var currentFieldName = e.srcElement ? e.srcElement.id : e.target.id;
                        setTimeout('ShowLocationHint(\'Sublocation\',\'' + mainLocationField.value + '\',\'' + currentFieldName + '\')', 100);
                        //ShowLocationHint(mainLocationField.value,e.srcElement ? e.srcElement.id : e.target.id);
                        break;

                }
            }
        }
    }
}

function HandleDdlOnChange(e) {
    var ddlName = e.srcElement ? e.srcElement.id : e.target.id;

    //szukamy indexu w tabeli ktorty element zostal klikniety
    var index = -1;
    for (i = 0; i < fieldsGroups.length; i++) {
        if (fieldsGroups[i][0] == ddlName) {
            index = i;
            break;
        }
    }

    //jesli znalezlismy
    if (index >= 0 && index < fieldsGroups.length) {
        var ddl = document.getElementById(ddlName);
        if (ddl != null) {
            var locationField;
            var streetField;
            if (document.getElementById(fieldsGroups[index][1])){
                locationField = document.getElementById(fieldsGroups[index][1]);
                //**currentValuesTable[fieldsGroups[index][1]] = '';
                }
            if (document.getElementById(fieldsGroups[index][2])){
                streetField = document.getElementById(fieldsGroups[index][2]);
                //**currentValuesTable[fieldsGroups[index][2]] = '';
                }

            //czyscimy zaznaczenie
            if (locationField != null) {
                locationField.value = '';

                if (streetField != null) {
                    streetField.value = '';
                }
                //sprawdzamy czy zaznaczyl cos konkretnie
            }

            var selectedProvince = document.getElementById(provinceFields[fieldsGroups[index][0]]);
            if (selectedProvince != null){
                selectedProvince.value = ddl.value;
                
                if(selectedProvince.value =='00000000-0000-0000-0000-000000000000')
                    selectedProvince.value = '';
            }
            
            var selectedProvinceName = document.getElementById(provinceFieldsNames[fieldsGroups[index][0]]);
            if (selectedProvinceName != null){
                selectedProvinceName.value = ddl.options[ddl.selectedIndex].text;
                
                if(selectedProvinceName.value =='wybierz')
                    selectedProvinceName.value = '';
            }
        }
    }
}

//////////////////////location hints
function ShowLocationHint(query, parentValue, locationFieldName) {

    var locationField = document.getElementById(locationFieldName);

    if (locationField != null) {
        if (locationField.value != '' && locationField.value.length > 2) {
            if (locationField.value != lastSearchText) {
                try {
                    lastSearchText = locationField.value;
                    var locationString = GetLocations(query, locationField.value, parentValue);

                    if (locationString != '') {
                        var locations = locationString.split(';');
                        if (locations.length > 0) {
                            var hint = this.document.getElementById('locationHintDiv');
                            var locationList = this.document.getElementById('locationList');
                            if (hint != null && locationList != null) {
                                //czyszczenie
                                if (locationList.children.length > 0) {
                                    for (var i = locationList.children.length - 1; i >= 0; i--) {
                                        locationList.removeChild(locationList.lastChild);
                                    }
                                }

                                //bindowanie do diva
                                for (var j = 0; j < locations.length; j++) {
                                    if (locations[j] != '') {
                                        var listEntry = this.document.createElement('li');
                                        //listEntry.setAttribute('id',j);

                                        var listLink = this.document.createElement('a');
                                        //listLink.setAttribute('href', 'javascript:SelectLocation(\'' + locations[j] + '\')');
                                        //listLink.setAttribute('href', 'javascript:SelectLocation(\'' + locations[j] + '\');');
                                        listLink.innerText = locations[j];
                                        listLink.textContent = locations[j];
                                        listLink.setAttribute('id', j);

                                        listEntry.appendChild(listLink);

                                        //dodanie eventow
                                        if (listEntry.attachEvent) {
                                            listEntry.attachEvent('onmouseover', HandleHintListMouseOver);
                                            //listEntry.attachEvent('onmousedown', SelectLocationOnMouseDown);
                                            //listEntry.attachEvent('onmouseout',HandleHintListMouseOut);
                                        }
                                        else {
                                            if (listEntry.addEventListener) {
                                                listEntry.addEventListener('mouseover', HandleHintListMouseOver, false);
                                                //listEntry.addEventListener('mousedown', SelectLocationOnMouseDown, false);
                                                //listEntry.addEventListener('mouseout',HandleHintListMouseOut,false);
                                            }
                                        }

                                        locationList.appendChild(listEntry);
                                    }
                                }

                                //ustawianie style!!
                                hint.style.top = parseInt(locationField.offsetTop) + 20 + 'px';
                                hint.style.left = parseInt(locationField.offsetLeft) + 'px';
                                hint.style.display = 'block';

                                //zapamietujemy okno- daje tez info czy jest widoczy hint
                                currentTextBox = locationField;
                            }
                        }

                    }
                    else {
                        HideLocationHint();
                    }
                }
                catch (err) {
                }
            }
        }
    }

}

function HandleHintListMouseOver(e) {
    var id = e.srcElement ? e.srcElement.id : e.target.id;
    if (id != currentSelectionIndex) {
        //sprawdzic czy nie aktualny
        if (currentSelectionIndex != null)
            DehoverLocation(currentSelectionIndex);

        currentSelectionIndex = e.srcElement ? e.srcElement.id : e.target.id;
        //ewentualnie odhooverowac i zahooverowac!!

        HoverLocation(currentSelectionIndex);
    }
}

//////////////////////getting locations

function BindProvinces(ddlName) {
    //pobieramy ddl
    var ddl = document.getElementById(ddlName);
    if (ddl != null) {

        //sprawdzamy czy nie trzeba zaznaczyc na poczatku
        var provinceHf = document.getElementById(provinceFields[ddlName]);
        var selectedId;
        if(provinceHf!= null){
            selectedId = provinceHf.value;
        }
        
        //pobieramy z handlerka wartosci
        try {
            var locationString = GetLocations("Province", null, null);

            if (locationString != '') {
                var locations = locationString.split(';');
                if (locations.length > 0) {
                    for (var j = 0; j < locations.length; j++) {
                        var locationPair = locations[j].split('|');
                        if (locationPair.length == 2) {
                            var option = document.createElement('option');
                            option.setAttribute('value', locationPair[1]);
                            option.setAttribute('name', locationPair[0]);
                            option.innerText = locationPair[0];
                            option.textContent = locationPair[0];
                            if(locationPair[1]==selectedId){
                                option.setAttribute('selected', 'yes');
                            }

                            ddl.appendChild(option);
                        }
                    }
                }
            }
        }
        catch (err) {
        }
    }
}

function GetLocations(query, search, parent) {
    var locations = '';

    try {
        var url = null;

        if (parent != null) {
            url =  encodeURI("http://" + document.domain + "/getlocations.aspx?query=" + query +"&search="+search+"&parent=" + parent);
            //url = encodeURI("http://" + "localhost:1645" + "/getlocations.aspx?query=" + query + "&search=" + search + "&parent=" + parent);
        }
        else if (search != null) {
            url =  encodeURI("http://" +  document.domain  + "/getlocations.aspx?query=" + query +"&search="+search);
            //url = encodeURI("http://" + "localhost:1645" + "/getlocations.aspx?query=" + query + "&search=" + search);
        }
        else {
            url =  encodeURI("http://" +  document.domain  + "/getlocations.aspx?query=" + query);
            //url = encodeURI("http://" + "localhost:1645" + "/getlocations.aspx?query=" + query);
        }

        if (url != null) {

            if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp = new XMLHttpRequest();
            }
            else {// code for IE6, IE5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.open("GET", url, false);
            xmlhttp.send();
            if (xmlhttp.status != "404") {
                locations = xmlhttp.responseText;
            }
        }
    }
    catch (err) {
    }

    return locations;
}

//////////////////////////selectcions

function SelectLocationOnMouseDown(e) {
    //SelectLocation();
}


function SelectDown() {
    if (currentTextBox != null) {
        var locationList = this.document.getElementById('locationList');
        if (locationList != null) {
            //inicjalizacja
            if (currentSelectionIndex == null) {
                currentSelectionIndex = 0;
            }
            else {
                //odznaczenie
                DehoverLocation(currentSelectionIndex);
                //przeuniecie
                if (++currentSelectionIndex >= locationList.children.length)
                    currentSelectionIndex = 0;
            }

            HoverLocation(currentSelectionIndex);
        }
    }
}

function SelectUp() {
    if (currentTextBox != null) {
        var locationList = this.document.getElementById('locationList');
        if (locationList != null) {
            //inicjalizacja
            if (currentSelectionIndex == null) {
                currentSelectionIndex = locationList.children.length - 1;
            }
            else {
                //odznaczenie
                DehoverLocation(currentSelectionIndex);
                //przesuniecie
                if (--currentSelectionIndex < 0)
                    currentSelectionIndex = locationList.children.length - 1;
            }

            HoverLocation(currentSelectionIndex);
        }
    }
}


function DehoverLocation(e) {
    var locationList = this.document.getElementById('locationList');
    if (locationList != null) {
        var item = locationList.children[e];
        if (item != null) {
            item.style.background = '';
            //item.style.color = '#67675f';
            item.children[0].style.color = '#67675f';
            //currentTextBox.value = currentValuesTable[currentTextBox.id] != '' ? currentValuesTable[currentTextBox.id] + ', ' : '' + item.children[0].innerText;
        }
    }
}

function HoverLocation(e) {
    var locationList = this.document.getElementById('locationList');
    if (locationList != null) {
        var item = locationList.children[e];
        if (item != null) {
            item.style.background = 'lightgray';
            //item.style.color='#bf3241';
            item.children[0].style.color = '#bf3241';
            if(currentTextBox.value.lastIndexOf(',') > 0){
                currentTextBox.value =  currentTextBox.value.replace(currentTextBox.value.substring(currentTextBox.value.lastIndexOf(',')), ', ' + item.children[0].innerText);
            }
            else{
                currentTextBox.value =  item.children[0].innerText;
            }
            //currentTextBox.value = currentValuesTable[currentTextBox.id] != '' ? currentValuesTable[currentTextBox.id] + ', ' : '' + item.children[0].innerText;
        }
    }
}



