var data;
var map;
var geocoder;
var categories = {};
var objs = {};
var categories_state = {};
var layers = {};
var layers_state = {};
var markerOptions = {};
var markerOptionsOrot = {};
var markers = {};
var tours = {};
var markers_tours = [];

var events = {};
events.data = {};
events.loaded = 0;
var markers_events = [];

var panoramioPhotos1 = {};
var panoramioPhotos2 = {};


function cat(){
	var age = 0;
}



$(function(){

    $('#btn_select_all').button({
        text: true,
        icons: {}
    });
    $('#btn_deselect_all').button({
        text: true,
        icons: {}
    });
    
    $("#tabs").tabs();
    
    $(window).resize(function(){
        keep_size();
    });
    
    keep_size();
    
    /* Rozwijanie Zwijanie kategorii */
    $(".collapse").click(function(){
        $(".subcategories", $(this).parent()).toggle();
        $('.scrollbar2').jScrollPane({
            showArrows: true,
            scrollbarWidth: 15,
            arrowSize: 16
        });
    });
    
    $(".chk_cat").click(function(event){
        $(this).attr("checked", $(this).attr("checked") ? "checked" : false);
        var checked = $(this).attr("checked");
        $(".chk_subcat", $(this).parent()).each(function(){
            var id = $(this).val();
            if (checked) {
                $(this).attr("checked", "checked");
                categories_state[id].checkbox = 1;
            }
            else {
                $(this).attr("checked", false);
                categories_state[id].checkbox = 0;
            }
        });
        update_categories();
    });
    
    
    $(".chk_subcat").click(function(event){
        $(this).attr("checked", $(this).attr("checked") ? "checked" : false);
        var id = $(this).val();
        var checked = $(this).attr("checked");
        var checkparent = false;
        
        if (checked) {
            categories_state[id].checkbox = 1;
        }
        else {
            categories_state[id].checkbox = 0;
        }
        
        $(".chk_subcat", $(this).parents(".category_item")).each(function(){
            if ($(this).attr("checked") == true) {
                checkparent = true;
            }
        });
        
        if (checkparent) {
            $(".chk_cat", $(this).parents(".category_item")).attr("checked", true);
        }
        else {
            $(".chk_cat", $(this).parents(".category_item")).attr("checked", false);
        }
        
        update_categories();
    });
    
    
    $(".chk_subcat_l").click(function(){
        $(this).attr("checked", $(this).attr("checked") ? "checked" : false);
        var id = $(this).val();
        var checked = $(this).attr("checked");
        
        if (checked) {
            layers_state[id].checkbox = 1;
        }
        else {
            layers_state[id].checkbox = 0;
        }
        
        update_layers();
    });
    
    $(".chk_events").click(function(){
        $(this).attr("checked", $(this).attr("checked") ? "checked" : false);
        if ($(this).attr("checked")) {
            if (events.loaded == 0) {
                show_loader();
                load_events();
            }
            else {
                show_event_markers();
            }
        }
        else {
            hide_event_markers();
        }
    });
    
    
    
    
});

function keep_size(){
    $("#map_container").css({
        'width': ($(window).width() - $('#panel_left').width()) + 'px',
        'height': ($(window).height() - $('#header').height() - $('#footer').height()) - 10 + 'px'
    });
    
    $("#panel_left").css({
        'height': ($(window).height() - $('#header').height() - $('#footer').height()) - 10 + 'px'
    });
    
    $("#container_all").css({
        'width': ($(window).width()) + 'px',
        'height': ($(window).height()) + 'px'
    });
    
}


//=========================================================================================
//  MAPA 

$(function(){
    gmap_initialize();
});



function gmap_initialize(){
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("map_container"));
        map.setCenter(new GLatLng(50.668559, 17.922177), 10);
        map.savePosition();
        map.setUIToDefault();
        map.setMapType(G_HYBRID_MAP);
        
        //directionsPanel = document.getElementById("directions");
        //directions = new GDirections(map, directionsPanel);
        //directions.load("from: Jana Bytnara, Opole, Opolskie, Polska to: Arki Bożka, Biała, Opolskie, Polska");
        
        var ctrl1 = new GNavLabelControl();
        ctrl1.setMinAddressLinkLevel(2);
        var topRight = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(80, 10));
        map.addControl(ctrl1, topRight);
        
        map.zoom_limiter({
            zoom_min: 10
        });
        
        map.latlng_limiter_2({
            lat_min: 49.93,
            lat_max: 51.26,
            lng_min: 16.56,
            lng_max: 18.98
        });
        
        map.disableScrollWheelZoom();
        load_categories();
        load_layers();
        load_kml(GMAP_KML_PATH + "opolskie_white.kml");
        
    }
}

function load_layers(){
    layers["wikipedia"] = new GLayer("org.wikipedia." + LANGUAGE);
    layers_state["wikipedia"] = {};
    layers_state["wikipedia"].checkbox = 0;
    layers_state["wikipedia"].map = 0;
    
    layers["panoramio"] = new GLayer("com.panoramio.all");
    layers_state["panoramio"] = {};
    layers_state["panoramio"].checkbox = 0;
    layers_state["panoramio"].map = 0;
    
    layers["kamery"] = new GLayer("com.google.webcams");
    layers_state["kamery"] = {};
    layers_state["kamery"].checkbox = 0;
    layers_state["kamery"].map = 0;
    
    layers["virtualtours"] = "virtualtours";
    layers_state["virtualtours"] = {};
    layers_state["virtualtours"].checkbox = 0;
    layers_state["virtualtours"].map = 0;
};



function load_categories(){
    $.post(APP_URL + LANGUAGE + "/dataFetcher/jsonGetCategories", {}, function(d_categories){
        //alert("loading cats");
        for (cat in d_categories) {
            var id = d_categories[cat].id;
            categories[id] = d_categories[cat];
            categories_state[id] = {};
            categories_state[id].checkbox = 0;
            categories_state[id].map = 0;
        }
        
        load_objects();
        
    }, "json");
}

function load_objects(){
    $.post(APP_URL + LANGUAGE + "/dataFetcher/jsonGetAllObjectsLight", {}, load_markers, "json");
}

function load_events(){
    events.loaded = 1;
    $.post(APP_URL + LANGUAGE + "/dataFetcher/jsonGetUpcomingEvents", {}, events_loaded, "json");
}

function events_loaded(data){
    events.data = data;
    hide_loader();
    
    
    for (evnt in events.data) {
        markerOptions = {
            image: PATH_ICONS + "regroup.png",
            width: 34,
            height: 34,
            importance: 3,
            tooltip: events.data[evnt].title
        };
        
        m = new MarkerLight(new GLatLng(events.data[evnt].lat, events.data[evnt].lng), markerOptions);
        m.eventid = events.data[evnt].id;
        markers_events.push(m);
    }
    
    show_event_markers();
}

function show_event_markers(){
    for (x in markers_events) {
        show_event_marker(markers_events[x]);
    }
}

function show_event_marker(marker){
    map.addOverlay(marker);
    
    GEvent.addListener(marker, "click", function(){
    
        //Loading DOM element with info_windows ajax loader 
        html_loader = $("#info_window_loader").html();
        marker.openInfoWindowHtml(html_loader);
        
        $.post(APP_URL + LANGUAGE + "/map/ajaxGetInfoWindowEvent", {
            id: marker.eventid
        }, function(html1){
            event1 = GEvent.addListener(map, "infowindowopen", function(event){
                $('.gmap_info_window_event .description').jScrollPane({
                    showArrows: true,
                    scrollbarWidth: 15,
                    arrowSize: 16
                });
                $('#btn_link').button({
                    text: true,
                    icons: {}
                }).click(function(event, ui){
                    window.location = $(this).attr('rel');
                });
                $(".accordion").accordion({
                    fillSpace: true
                });
                $(".iw_qtip").qtip(template_qtip01);
                event2 = GEvent.addListener(map, "infowindowclose", function(){
                    GEvent.removeListener(event1);
                    GEvent.removeListener(event2);
                    map.panTo(marker.getLatLng());
                });
            });
            marker.openInfoWindowHtml(html1);
        }, "html");
    });
}

function hide_event_markers(){
    for (x in markers_events) {
        map.removeOverlay(markers_events[x]);
        GEvent.clearListeners(markers_events[x]);
    }
}



function load_markers(objects){

    for (x in objects) {
        objs[objects[x]] = {};
        objs[objects[x].id] = objects[x];
    }
    
    for (i in objects) {
    
        for (j in objects[i].categories) {
        
            markerOptions[i] = {
                image: PATH_ICONS + categories[objects[i].categories[j]].icon,
                width: Number(objects[i].isOrot) == 1 ? 35 : 20,
                height: Number(objects[i].isOrot) == 1 ? 35 : 20,
                importance: (objects[i].isOrot) == 1 ? 1 : 0,
                tooltip: objects[i].name
            }
            
            
            m = new MarkerLight(new GLatLng(objects[i].lat, objects[i].lng), markerOptions[i]);
            
            m.obid = objects[i].id;
            
            m.importance = Number(objects[i].isOrot) == 1 ? 2 : 1;
            
            if (typeof markers[objects[i].categories[j]] == "undefined") 
                markers[objects[i].categories[j]] = [];
            markers[objects[i].categories[j]].push(m);
        }
    }
    
    $.post(APP_URL + LANGUAGE + "/dataFetcher/jsonTours", {}, function(data){
    
        tours = data;
        
        
        
        
        for (i in tours) {
        
            markerOptions = {
                image: PATH_ICONS + "info.png",
                width: 40,
                height: 40,
                importance: 2,
                tooltip: tours[i].tour_title
            };
            
            m = new MarkerLight(new GLatLng(tours[i].lat, tours[i].lng), markerOptions);
            m.vtid = tours[i].tour_id;
            markers_tours.push(m);
            
        }
        
        
        hide_loader();
    }, "json")
}





function update_categories(){
    for (id in categories_state) {
        var state = categories_state[id];
        if (state.checkbox == 1 && state.map == 0) {
            show_markers(id);
            state.map = 1;
            continue;
        }
        else 
            if (state.checkbox == 0 && state.map == 1) {
                remove_markers(id);
                state.map = 0;
                continue;
            }
    }
}

function update_layers(){
    for (id in layers_state) {
        var state = layers_state[id];
        if (state.checkbox == 1 && state.map == 0) {
            show_layer(layers[id]);
            state.map = 1;
            continue;
        }
        else 
            if (state.checkbox == 0 && state.map == 1) {
                remove_layer(layers[id]);
                state.map = 0;
                continue;
            }
    }
}

function show_layer(layer){
    if (layer == "virtualtours") {
        show_virtualtours();
    }
    else {
        map.addOverlay(layer);
    }
    
}

function remove_layer(layer){
    if (layer == "virtualtours") {
        hide_virtualtours();
    }
    else {
        map.removeOverlay(layer);
    }
}



function show_virtualtours(){
    for (i in markers_tours) {
        show_tourmarker(markers_tours[i]);
    }
}

function show_tourmarker(marker){
    map.addOverlay(marker);
    GEvent.addListener(marker, "click", function(){
        open_tour(marker.vtid);
    });
}

function hide_virtualtours(){
    for (i in markers_tours) {
        map.removeOverlay(markers_tours[i]);
    }
}


function show_markers(cat){
    if (!cat) {
        //alert("Showing all markers");
        for (i in markers) {
            for (j in markers[i]) {
                show_marker(markers[i][j]);
            }
        }
    }
    else {
        for (k in markers[cat]) {
            show_marker(markers[cat][k]);
        }
    }
    
}

function remove_markers(cat){
    if (!cat) {
        for (i in markers) {
            for (j in markers[i]) {
                remove_marker(markers[i][j]);
            }
        }
    }
    else {
        for (k in markers[cat]) {
            remove_marker(markers[cat][k]);
        }
    }
}


function show_marker(marker){
    map.addOverlay(marker);
    
    GEvent.addListener(marker, "click", function(){
    
        //Loading DOM element with info_windows ajax loader 
        html_loader = $("#info_window_loader").html();
        marker.openInfoWindowHtml(html_loader);
        
        $.get(APP_URL + LANGUAGE + "/dataFetcher/jsonGetPanoramioPhotos/", {
            order: "popularity",
            set: "public",
            from: "0",
            to: "10",
            lat: marker.getLatLng().lat(),
            lng: marker.getLatLng().lng(),
            range: 2
        }, function(response){
            panoramioPhotos1 = response.photos;
            $.get(APP_URL + LANGUAGE + "/dataFetcher/jsonGetPanoramioPhotos/", {
                order: "popularity",
                set: "public",
                from: "0",
                to: "10",
                lat: marker.getLatLng().lat(),
                lng: marker.getLatLng().lng(),
                range: 20
            }, function(response2){
                panoramioPhotos2 = response2.photos;
                $.post(APP_URL + LANGUAGE + "/map/ajaxGetInfoWindow/", {
                    id: marker.obid,
                    photos: $.toJSON(panoramioPhotos1),
                    photos2: $.toJSON(panoramioPhotos2)
                }, function(html1){
                    event1 = GEvent.addListener(map, "infowindowopen", function(event){
                        var photosPanoramio = panoramioPhotos1.concat(panoramioPhotos2);
                        $("#tabsiw").tabs();
                        $('.iwdecription').jScrollPane({
                            showArrows: true,
                            scrollbarWidth: 15,
                            arrowSize: 16
                        });
                        $('#btn_link').button({
                            text: true,
                            icons: {}
                        }).click(function(event, ui){
                            window.location = $(this).attr('rel');
                        });
                        $('#btn_favour').button({
                            text: true,
                            icons: {}
                        }).click(function(event, ui){
                            $("<div id='dialog' title='Informacja'><p>Nie jesteś zalogowany!</p></div>").dialog({
                                bgiframe: true,
                                height: 140,
                                modal: true
                            });
                        });
                        $(".link_panoramio_photo").click(function(event){
                            event.preventDefault();
                            var photo = searchObjectArrayForProperty(photosPanoramio, 'photo_id', $(this).attr('datasrc'));
                            photo_data = $.toJSON(photo);
                            $("<a id='dup' href='" + APP_URL + LANGUAGE + "/common/showPanoramioPhoto'></a>").fancybox({
                                'frameWidth': photo.width + 1,
                                'frameHeight': photo.height + 38,
                                'transitionIn': 'none',
                                'transitionOut': 'none',
                                'overlayShow': true,
                                'autoScale': false,
                                'titlePosition': 'inside',
                                'hideOnContentClick': false,
                                'post_vars': {
                                    'photo': photo_data
                                }
                            }).trigger('click');
                        });
                        $(".accordion").accordion({
                            fillSpace: true
                        });
                        $(".iw_qtip").qtip(template_qtip01);
                        event2 = GEvent.addListener(map, "infowindowclose", function(){
                            GEvent.removeListener(event1);
                            GEvent.removeListener(event2);
                            map.panTo(marker.getLatLng());
                        });
                    });
                    marker.openInfoWindowHtml(html1);
                }, "html");
            }, 'json');
        }, 'json');
        
        
    });
}

function remove_marker(marker){
    map.removeOverlay(marker);
    GEvent.clearInstanceListeners(marker);
}

function show_loader(){
    $("#loader").css("display", "block");
}

function hide_loader(){
    $("#loader").css("display", "none");
}






