/**
 * @author Alfred Broda
 * @edited-by Michal Pomaskow
 */
var opis;
var removed;
var persistent;
var temp_latlng = null;
var listener = null;
var allcats;

function showCat(url) {
    url = url.replace('.html','/rand/'+rand(1000)+'.html');
    new Ajax.Request(url, {
        asynchronous :true,
        evalScripts :false,
        method :'get',
        onComplete : function(request, json) {
            Element.hide('wait');
        },
        onLoading : function(request, json) {
            Element.show('wait');
        },
        onSuccess : function(response) {
            if (response.status == 200) {
                var list = String(response.responseText);
                list = list.evalJSON();
                var cats = Object.values(list.cats);
                cats._each( function(list) {
                        if (typeof (list) == "object") {
                                allcats[list.id] = list;
                        }
                });
                redrawCats();
            }
        }
    });
}

function hideCat(cat) {
    removed = allcats[cat];
    allcats.splice(cat, 1);
    redrawCats();
}

function redrawCats() {
    /* Uwaga! clearPolys usuwa i wielokąty i linie! */
    clearMarkers();
    clearPolys();

    allcats._each( function(cat) {
        if (typeof (cat) == 'object') {
            if (typeof (cat.lines) == 'object') {
                makeLines(cat);
            }
            if (typeof (cat.polys) == 'object') {
                makePolys(cat);
            }
            if (typeof (cat.places) == 'object') {
                makeMarkers(cat);
            }
        }
    });
}

function resetCats() {
    var to_hide = new Array();
    allcats._each( function(cat) {
            if (typeof (cat) == 'object') {
                    to_hide.Push(cat.id);
            }
    });
    to_hide._each( function(cat) {
            hideCat(cat);
    });
    allcats = Array();
    map.clearOverlays();
}

function catch_pos(latlng) {
    temp_latlng = latlng;
}

/**
 * Pokazuje opis klikniętego markera wyciągając go z bazy AJAXem
 *
 * @param {Object}
 *            marker Objekt markera
 */
function get_opis(marker, junk) {
    //alert('Kliknniecie na ikonke');
    if (marker && typeof (marker) == 'object' && marker.item) {
            new Ajax.Request(marker.item.desc, {
                    asynchronous :true,
                    evalScripts :false,
                    method :'get',
                    onComplete : function(request, json) {
                            Element.hide('wait');
                    },
                    onLoading : function(request, json) {
                            Element.show('wait');
                    },
                            onSuccess : function(res) {

                                    var temp = res.responseText;

                                    if (typeof (marker.getLatLng) != 'function') {
                                            latlng = new GLatLng(marker.item.posn[0],
                                                            marker.item.posn[1]);
                                    } else {
                                            latlng = marker.getLatLng();
                                    }

                                    var gtabs = Array();

                                    var contentDiv = document.createElement('div');
                                    // contentDiv.innerHTML = temp;
                                    contentDiv.id = marker.id;
                                    // contentDiv.style.marginRight = "10px";
                                    var fullDiv = contentDiv.cloneNode(true);

                                    fullDiv.innerHTML = temp.slice(temp.match("<!--full-start").index,temp.match("<!--end-->").index);
                                    /* opis pełny */
                                    var maxopts = {
                                            maxContent :fullDiv,
                                            maxTitle :marker.item.name
                                    }

                                    /* zakładki dymka */
                                    contentDiv.className = "gpopup";

                                    var start_end = Array();
                                    var opis = "";
                                    var tytul = "";
                                    var start = 0;
                                    var end = 0;
                                    start_end = ["<!--begin", "<!--opis-end", "<!--loka-end", "<!--srch-end", "<!--trak-end", "<!--full-start" ];

                                    /* Tniemy odpowiedź na bloki */
                                    if (temp.match(start_end[0])) {

                                            //var head = temp.slice(0, temp.match(start_end[0]).index);
                                            var i = 0;
                                            while ( i < start_end.length-1 ) {
                                                    var startt = start_end[i];
                                                    start = temp.match(start_end[i]);
                                                    var endt = start_end[i+1];
                                                    end = temp.match(start_end[i+1]);
                                                    if ( start && end ) {
                                                            opis = temp.slice(temp.match(start).index, temp.match(end).index);
                                                            var content = opis.slice(opis.match("start-->").index+8);
                                                            if (content.strip() != "") {
                                                                    start = opis.match(start_end[i]).index+start_end[i].length;
                                                                    end = opis.match("start-->").index;
                                                                    tytul = opis.slice(start, end);
                                                                    var descDiv = contentDiv.cloneNode(true);
                                                                    descDiv.innerHTML = opis;

                                                                    gtabs.push(new GInfoWindowTab(tytul.strip(), descDiv));
                                                            }
                                                            start = end = 0;
                                                    }
                                                    i++;
                                            }
                                            map.openInfoWindowTabs(latlng, gtabs, maxopts);
                                    } else {
                                            fullDiv.innerHTML = temp;
                                            map.openInfoWindow(latlng, fullDiv, maxopts);
                                    }
                            }
            });
    }
}

function rssubmit(form) {
    var params = Form.serialize(form);
    var link = form.link.value;
    new Ajax.Request(link, {
            asynchronous :true,
            evalScripts :false,
            method :'post',
            onSuccess : function(response) {
                if (response.status == 200) {
                    // var list = response.headerJSON;
                    var list = response.responseText;
                    list = list.evalJSON();
                    // $('rsresults').innerHTML = '';
                    if (list.count == 0) {
                        alert("Brak Wyników!");
                    } else {
                        // $('rsresults').innerHTML = response.responseText;
                        allcats = Array();
                        var cats = Object.values(list.cats);
                        cats._each( function(scategory) {
                                if (typeof (scategory) == 'object') {
                                        if (typeof (hideCat) == 'function')
                                                hideCat(scategory.id);
                                        allcats[scategory.id] = scategory;
                                }
                        });
                        redrawCats();
                        rsend();
                    }
                }
            },
            parameters : params
    });
}

var rsstarted = null;
// var rscursor = null;
// var rsposition = null;

function rsstart(text) {
    endall();

    if (rsstarted == null) {
        alert(text);
        rsstarted = addListener( function(junk, latlng) {
                $('lat').value = latlng.y;
                $('lng').value = latlng.x;
                Element.show($('rswin'));
                $('map').appendChild($('rswin'));
                new Draggable('rswin');
        });
        // cursor = getCursor();
        // rscursor = GEvent.addListener(map, 'mousemove',
        // function(e){getMousePosition(e)});
    } else {
        rsend();
    }
}

function rsend() {
    removeListener(rsstarted);
    rsstarted = null;
    // GEvent.removeListener(rscursor);
    // rscursor = null;
    Element.hide($('rswin'));
}

// Returns mouse position
function getMousePosition(e) {
    // e = e ? e : window.event;
    var position = {
            'x' :e.y,
            'y' :e.x
    }
    // rsposition = position;
    return position;
}

/*
 * Zakańcza wszelkie nasłuchujące demony
 */
function endall() {
    listeners = Array();
    GEvent.clearListeners(map, 'click');
    listener = null;
    addListener(get_opis);
}

var PDir;
var wpoints = Array();

function plotBetween(url) {
    PDir = new GDirections(map);
    var wpoints_temp = Array();
    new Ajax.Request(url, {
        asynchronous :true,
        evalScripts :false,
        method :'get',
        onComplete : function(request, json) {
                Element.hide('wait');
        },
        onLoading : function(request, json) {
                Element.show('wait');
        },
        onSuccess : function(response) {
                if (response.status == 200) {
                        var list = String(response.responseText);
                        list = list.evalJSON();
                        var cats = Object.values(list.cats);
                        cats._each( function(list) {
                                if (typeof (list) == "object") {
                                        allcats[list.id] = list;
                                        wpoints_temp = list.plot;
                                }
                        });
                        redrawCats();
                        var i =0;
                        wpoints_temp._each( function(point) {
                            wpoints[i++] = point.x+','+point.y;
                        } );
                        PDir.loadFromWaypoints(wpoints, {
                                getPolyline :true
                        });
                }
        },
        parameters :'&rand=' + rand(1000)
    });
}

var listeners = Array();

function addListener(added) {
    if (!listeners.in_array(added)) {
        listeners.push(added);
    }
    if (listener == null) {
        listener = GEvent.addListener(map, "click", function (item,point) {runListeners(item,point)});
    }
    return listeners.length - 1;
}

function removeListener(listener) {
    if (listeners.in_array(listener)) {
        listeners.splice(listener, 1);
    }
}

function runListeners(item, point) {
    if (typeof(item) == 'object' ||  typeof(point) == 'object')
    listeners._each( function(func) {
            func(item, point);
    });
}

