﻿qBlokadaFocusa = false;
qInputFocused = false;
qBlokadaOnChange = false;
qTimeout = 0;
timer = null;
//static_text = 'Wpisz lokalizację lub wybierz z listy';

function qLocationsKeyUp(event) {
    var element = event.element();
  
    var key = getEventKeyCode(event);
    
    var execute = false;

    if (key == 40) {
        qBlokadaFocusa = true;
        $('LocationsSelect').focus();
        $('LocationsSelect').options[0].selected = true;
    } else if (key == 39) {
        if (getSelectionStart(element) == element.value.length) {
            if ($('LocationsSelect').options.length > 0 && ($('LocationsBox').getStyle('display') == 'block')) {
                var firstValue = $('LocationsSelect').options[0].innerHTML;
                
                if (firstValue.lastIndexOf("/") == -1) {
                    element.value = firstValue;
                } else {
                    var rest = firstValue.substr(0, firstValue.lastIndexOf("/"));

                    element.value = firstValue.substr(firstValue.lastIndexOf("/")+1, firstValue.length-1);
                    
                    if (rest.indexOf("/") == -1) {
                        element.value = rest + ", " + element.value;
                    } else {
                        element.value = rest.substr(0,rest.indexOf("/")) + ", " + element.value;
                    }
                }
            }
            
            execute = true;
        }
    } else if ((key >= 65 && key <= 90)||(key >= 97 && key <= 122)||(key==8)||(key==32)) {
        if (qBlokadaFocusa) {
            qBlokadaFocusa = false;
            return;
        }
        
        execute = true;   
    }
    
    if (execute) {
        qTimeout = 500;
        if (timer) clearTimeout(timer);
        timer = setTimeout(ExecuteSearch, qTimeout);
    }
}

function ExecuteSearch() {
    var inp = $('txtLocations');
        
    var result = "";
    var TablicaDanych = new Array();
    
    var CiagDanych = "";
    
    var parent = "";
    var prefix = inp.value;
    
    var woj = $$('.lstWojewodztwa')[0].options[$$('.lstWojewodztwa')[0].selectedIndex].value;
    
    if (inp.value.indexOf(",") > -1) {
        parent = inp.value.substr(0, inp.value.indexOf(","));
        prefix = inp.value.substr(inp.value.indexOf(",")+1, inp.value.length-1);
    }
    
    if (prefix.length > 2 || parent.length > 4) {
        var url = 'virgolisty.ashx?typ=all&prefix='+trim(prefix, " ")+"&parent="+trim(parent, " ")+"&wojewodztwo="+woj;

        new Ajax.Request(url, {
          method: 'get',
          onSuccess: function(transport) {
                eval(transport.responseText);
                
                CiagDanych = Ciagall;
                
                $('LocationsSelect').options.length = 0;

                if ((CiagDanych != null) && (CiagDanych.length > 0)) {
                    TablicaDanych = CiagDanych.split(",");

                    for (var i=0; i<TablicaDanych.length; i++)
                        $('LocationsSelect').options[i] = new Option(TablicaDanych[i].split(';')[1], TablicaDanych[i].split(';')[0]); 
                
                    if ($('LocationsBox').getStyle('display') == 'none') {
                        $('LocationsBox').show();
                    }
                    
                    RegisterEvent($('LocationsSelect'), "keydown", respondToKeyDown);                      
                    RegisterEvent($('LocationsSelect'), "change", respondToChange);
                    
                    qInputFocused = true;
                    $('txtLocations').focus();
                } else {
                    if ($('LocationsBox').getStyle('display') == 'block') {
                        $('LocationsBox').hide();
                    }
                }
           },
         onLoading: function() {
               $('imgLoading').show();
           },
         onComplete: function(transport) {
               $('imgLoading').hide();
           }
        });
    } else {
        $('LocationsBox').hide();
    }
}

function inp_focus(event) {
    qInputFocused = true;
    
    if ($('txtLocations').value == static_text) $('txtLocations').value = '';
}

function inp_blur(event) {
    qInputFocused = false;
    
    if (!qBlokadaFocusa) {
        if ($('LocationsSelect').selectedIndex == -1) $('LocationsBox').hide();
    }
    
    qBlokadaFocusa = false;
    
    if ($('txtLocations').value == '') $('txtLocations').value = static_text;
}

function sel_blur() {
    if (!qInputFocused) $('LocationsBox').hide();
}

function respondToKeyDown(event) {
  var element = getEventTarget(event);
  
  var key = getEventKeyCode(event);
  
  qBlokadaOnChange = true;

  if (key == 13) {
    var sel = $('LocationsSelect');

    if (sel.selectedIndex != -1) {
        AddElement(sel.options[sel.selectedIndex]);

        $('LocationsBox').hide();
        
        qBlokadaFocusa = true;
        
        $('txtLocations').select();
        
        qBlokadaOnChange = false;
    }
  }
  
  if (key == 38) {
        if ($('LocationsSelect').selectedIndex == 0) {
            qInputFocused = true;
            $('txtLocations').focus();
            
            $$('#LocationsSelect option').each(function(elem){
                  elem.selected = false;
            });
        }
    }
}

function respondToChange(event) {
    if(!qBlokadaOnChange) {
        var element = getEventTarget(event);

        AddElement(element.options[element.selectedIndex]);
           
        $('LocationsBox').hide();
        $('txtLocations').select();
    }
}

function AddElement(element) { 
    var NaLiscie = false;
    $$('.LocationsListSelect option').each(function(elem){
       if (elem.value == element.value) NaLiscie = true;
    });
    
    if (!NaLiscie) {
        var sel = $$('.LocationsListSelect')[0];
    
        if (sel.getStyle('display') == 'none') sel.show(); 
    
        sel.options[sel.options.length] = new Option(element.innerHTML, element.value);
        
        if (sel.options.length%2==1) addClass(sel.options[sel.options.length-1], "odd");
        
        var del = $('LocationsListDelete');
        
        if ($('LocationsListDelete').getStyle('display') == 'none') $('LocationsListDelete').show();  
        
        del.options[sel.options.length-1] = new Option("[x]", element.value);
        
        if ($('LocationsList').getStyle('display') == 'none') $('LocationsList').show(); 
           
        if (sel.options.length > 1) {
            sel.setAttribute('size',sel.options.length);
            del.setAttribute('size',del.options.length);
            
            $('ClearLocationsList').show();
        } else {
            sel.setAttribute('size',2);
            del.setAttribute('size',2);
            
            $('ClearLocationsList').hide();
        }
        
        RegisterEvent(del, "change", respondToDelChange);
        
        $$('.hidLocations')[0].value = "";
        $$('.hidLocationsCache')[0].value = "";
        $$('.LocationsListSelect option').each(function(elem){
           $$('.hidLocations')[0].value += elem.value + ",";
        });
        $$('.hidLocations')[0].value=rtrim($$('.hidLocations')[0].value, ",");
    }
}

function respondToDelChange(event) {
    var element = getEventTarget(event);
    
    UsunLokacje(element.options[element.selectedIndex].value);
}

function UsunLokacje(id) {  
    var sel = $$('.LocationsListSelect')[0];
    var idx = 0;
    $$('.LocationsListSelect option').each(function(elem){
       if (elem.value == id) {
          sel.options[idx] = null;
       } else {
            idx += 1;
       }
    });
    
    var del = $('LocationsListDelete');
    idx = 0;
    $$('#LocationsListDelete option').each(function(elem){
       if (elem.value == id) {
          del.options[idx] = null;
       } else {
            idx += 1;
       }
    });
    
    idx=0;
    $$('.LocationsListSelect option').each(function(elem){
        if (idx%2==0) {
            addClass(sel.options[idx], "odd");
        } else {
            if (hasClass(sel.options[idx], "odd")) removeClass(sel.options[idx], "odd");
        }
        idx += 1;
    });
    
    if (sel.options.length > 1) {
        sel.setAttribute('size',sel.options.length);
        del.setAttribute('size',del.options.length);
        
        $('ClearLocationsList').show();
    } else {
        sel.setAttribute('size',2);
        del.setAttribute('size',2);
        
        $('ClearLocationsList').hide();
    }
    
    if (sel.options.length == 0) {
        sel.hide();
        del.hide();
        $('LocationsList').hide();
    }

    $$('.hidLocations')[0].value = "";
    $$('.hidLocationsCache')[0].value = "";
    $$('.LocationsListSelect option').each(function(elem){
       $$('.hidLocations')[0].value += elem.value + ",";
    });
    $$('.hidLocations')[0].value=rtrim($$('.hidLocations')[0].value, ",");
}

function ClearLocationsList() {
    var sel = $$('.LocationsListSelect')[0];
    $$('.LocationsListSelect')[0].options.length=0;
    
    var del = $('LocationsListDelete');
    $('LocationsListDelete').options.length=0;
    
    sel.hide();
    del.hide();
    $('LocationsList').hide();
    $('ClearLocationsList').hide();
    
    $$('.hidLocations')[0].value = "";
    $$('.hidLocationsCache')[0].value = "";
    $$('.LocationsListSelect option').each(function(elem){
       $$('.hidLocations')[0].value += elem.value + ",";
    });
    $$('.hidLocations')[0].value=rtrim($$('.hidLocations')[0].value, ",");
}   

function Locations_LoadFromCache() {
    if ($$('.hidLocationsCache')[0].value != "") {
        var objs = $$('.hidLocationsCache')[0].value.split(",");

        var sel = $$('.LocationsListSelect')[0];
        var del = $('LocationsListDelete');

        sel.options.length = 0;
        del.options.length = 0;
        for (var i=0; i<objs.length; i++) {
            sel.options[i] = new Option(objs[i].split(";")[1], objs[i].split(";")[0]);
            if (i%2==0) addClass(sel.options[i], "odd");
            del.options[i] = new Option("[x]", objs[i].split(";")[0]);
        }
            
        if (sel.options.length > 1) {
            sel.setAttribute('size',sel.options.length);
            del.setAttribute('size',del.options.length);
            
            $('ClearLocationsList').show();
        } else {
            sel.setAttribute('size',2);
            del.setAttribute('size',2);
            
            $('ClearLocationsList').hide();
        }

        if (sel.options.length == 0) {
            sel.hide();
            del.hide();
            $('LocationsList').hide();
        } else {
            sel.show();
            del.show();
            $('LocationsList').show();
        }

        RegisterEvent(del, "change", respondToDelChange);
        
        $$('.hidLocations')[0].value = "";
        $$('.LocationsListSelect option').each(function(elem){
           $$('.hidLocations')[0].value += elem.value + ",";
        });
        $$('.hidLocations')[0].value=rtrim($$('.hidLocations')[0].value, ",");
    }
}
