;
// We need to kill prototype (jsparty/prototype.js), 'cause it's incompatible
// Some SS modules want to call prototype functions, so let's make them happy with some dummies	
	Behaviour = {};
	Behaviour.register = function(){};
	
// Standard jQuery header
(function($) {
    $(document).ready(function() {

        // ==================== LOAD THE CONFIGURATION =========================
        var config;
        $.ajax({
            type: "GET",
            url: "timetablesConfig.json",
            dataType: "json",
            cache: false,
            async: false,
            success: function(data) {
                config = data;
            //                config.dbserviceURL = data.config.dbserviceURL;
            //                config.maxMapZoomLevel = data.config.maxMapZoomLevel;
            },
            error: function() {
                alert("Nie uda\u0142o siÄ pobraÄ pliku konfiguracyjnego.");
            }
        });
        

        // ========================== FUNCTIONS ================================



        loadLines = function() {
            $.ajax({
                dataType: 'jsonp',
				data:'operator_id='+config.operatorId,
                jsonp: 'jsonp_callback',
                url: config.dbserviceURL+'lines.php',
                async: false,
                success: function (data) {

                    $("#timetablesHome").data("lines",data.lines);
                    //clear
                    $("#timetablesHome").html();

                    //display breadcrumbs
                    $("#timetablesHome .breadcrumbs").html(breadcrumbsByLine());
                    $("#timetablesHome .breadcrumbs a").click(function(e) {
                        e.preventDefault();
                    });
                    activateBreadcrumb($("#timetablesHome .breadcrumbs a.lineBc"),goHome);

                    //display lines
                    $.each(data.lines,function(i,line) {
                        var targetDiv;
                        if (line.type=="Tram") {
                            targetDiv = "tramLines";
                        } else if (line.type=="Bus") {
                            targetDiv = "busLines";
                        }
                        var element = $("<a>").attr("class","line").attr("href", "").text(line.name);
                        if (line.night) {
                            element.addClass("night");
                        }
                        $("#"+targetDiv).append(element);
                        $("#"+targetDiv).append(" ");
                    });
					
					//if we have no trams or no buses, hide the unnecessary sections
					
					if ($("#tramLines a.line").length==0) {
						$("#tramLines").hide()
					}
					
					if ($("#busLines a.line").length==0) {
						$("#busLines").hide()
					}
					
					

                    //add behaviour to lines
                    $("a.line").click(function(e) {
                        e.preventDefault();
                        goToRoutes($(this).html());
                    });
                    //finished adding behaviour to lines
                    $("#lines").show();
                    //finished displaying lines
                    loadStops();
                    
                }
            });
        //finished loading data
        };

        loadStops = function() {
            $.ajax({
                dataType: 'jsonp',
                data:'operator_id='+config.operatorId,
                jsonp: 'jsonp_callback',
                url: config.dbserviceURL+'places.php',
                async: false,
                success: function (data) {
                    //display breadcrumbs

                    $("#timetablesHome").data("stops",data.places);
                    
                    $(['A','B','C','\u0106','D','E','F','G','H','I','J','K','L','\u0141','M','N','O','P','Q','R','S','\u015a','T','U','W','X','Y','Z','\u0179','\u017b']).each(function(i,letter) {
                        $("#byStop").append("<a href='' class='letter'>"+letter+"</a>");
                    });
                    $("#byStop a.letter").click(function(e) {
                        e.preventDefault();
                        goToStopsLike($(this).text());
                    });
                    $("#byStop").show();
                    enableWidget();
                }
            });
            
        }

        showStops = function() {
            displayTimetablesContainer("timetablesHome");
        }

        goToStopsLike = function(filter) {
            $.address.value("/showStopsLike/"+filter);
        }

        showStopsLike = function(filter) {
            $("#timetables-bookmarks .byLine").removeClass("active");
            $("#timetables-bookmarks .byStop").addClass("active");
            displayTimetablesContainer("timetables-loading");
            $.ajax({
                dataType: 'jsonp',
                data: 'name_like='+filter+'&operator_id='+config.operatorId,
                jsonp: 'jsonp_callback',
                url: config.dbserviceURL+'places.php',
                success: function (data) {
                    $("#stopList").html("<div class='breadcrumbs'></div>");

                    //display breadcrumbs
                    $("#stopList .breadcrumbs").html(breadcrumbsByStop());
                    $("#stopList .breadcrumbs a").click(function(e) {
                        e.preventDefault();
                    });
                    activateBreadcrumb($("#stopList .breadcrumbs a.stopBc"),goHome);


                    if (data.places.length==0) {
                        $("#stopList").html(ss.i18n._t('TIMETABLES.No_stops_found'));
                    }
                    $.each(data.places,function(i,place) {
                        $("#stopList").append($("<a>").attr("class","stop").attr("href","").text(place.name).
                            data("stopId",place.id));
                        $("#stopList").append(" ");
                    });
                    $("#stopList a.stop").click(function(e) {
                        e.preventDefault();
                        goToRoutesByStop($(this).data("stopId"));
                    });
                    displayTimetablesContainer("stopList");
                }
            });
        //finished displaying stops
        };

        goToRoutes = function(line) {
            $.address.value("/showRoutes/"+line);
        }

        showRoutes = function(line) {
            displayTimetablesContainer("timetables-loading");
            $("#timetables-bookmarks li:first").removeClass("active");
            $("#timetables-bookmarks li:last").addClass("active");
            $.ajax({
                dataType: 'jsonp',
                data: 'line='+line,
                jsonp: 'jsonp_callback',
                url: config.dbserviceURL+'routes.php',
                success: function (data) {
                    var map = $("#map").data("map");
                    map.clearOverlays();
                    $("#routes").html("");
                    $("#routes").append("<div class='breadcrumbs'></div>");
                    $("#routes").append($("<h4>").text(ss.i18n._t('TIMETABLES.Line')+" "+line));
                    var minLat=0;
                    var maxLat=0;
                    var minLng=0;
                    var maxLng=0;
                    $.each(data.routes,function(i,route) {
                        var currentDiv = $("<div>").attr("class","route");
                        $("#routes").append(currentDiv);
                        currentDiv.data("routeId",route.id);
                        currentDiv.append($("<div>").attr("class","route-header").text(ss.i18n._t('TIMETABLES.Direction')+" "+route.direction));
                        var stopLatLngs = [];
                        $.each(route.stops,function(i,stop) {
                            var currentA = $("<a>");
                            currentA.attr("href","#");
                            currentA.attr("class","stop");
                            currentA.text(stop.name);
                            currentA.data("stopId",stop.id);
                            var latLng = new GLatLng(stop.lat,stop.lng);
                            if (!latLng.equals(new GLatLng(0,0))) {
                                var marker = new GMarker(latLng, getMarkerOptionsForGMaps());
                                map.addOverlay(marker);
                                currentA.data("marker",marker);
                                stopLatLngs.push(latLng);
                                if ((minLat==0) || (latLng.lat()<minLat)) {
                                    minLat=latLng.lat();
                                }
                                if ((maxLat==0) || (latLng.lat()>maxLat)) {
                                    maxLat=latLng.lat();
                                }
                                if ((minLng==0) || (latLng.lng()<minLng)) {
                                    minLng=latLng.lng();
                                }
                                if ((maxLng==0) || (latLng.lng()>maxLng)) {
                                    maxLng=latLng.lng();
                                }

                            }
                            currentDiv.append(currentA);
                        });
                        map.addOverlay(new GPolyline(stopLatLngs,"#ff0000",5));
                    });
                    var targetZoomLevel = map.getBoundsZoomLevel(new GLatLngBounds(
                        new GLatLng(minLat,minLng),new GLatLng(maxLat,maxLng)));
                    map.setZoom(Math.min(targetZoomLevel,config.maxMapZoomLevel));
                    map.panTo(new GLatLng((maxLat+minLat)/2,(maxLng+minLng)/2));
                    $("#routes a").click(function(e) {
                        e.preventDefault();
                        goToTimetable($(this).parent().data("routeId"),$(this).data("stopId"),"byLine");
                    });
                    $("#routes a").hover(function() {
                        selectMarker($(this).data("marker"));
                    }, function() {
                        unselectMarker($(this).data("marker"));
                    });

                    //display breadcrumbs
                    $("#routes .breadcrumbs").html(breadcrumbsByLine());
                    $("#routes .breadcrumbs a").click(function(e) {
                        e.preventDefault();
                    });
                    activateBreadcrumb($("#routes .breadcrumbs a.lineBc"),goHome);
                    activateBreadcrumb($("#routes .breadcrumbs a.directionBc"),showRoutes,line);

                    displayTimetablesContainer("routes");
                }
            });
        };

        selectMarker=function(marker) {
            //            marker.openInfoWindowHtml("Hey!");
            
            hMarker = new GMarker(marker.getLatLng(), getHighlightedMarkerOptionsForGMaps());
            $("#map").data("highlightedMarker",hMarker);
            $("#map").data("map").addOverlay(hMarker);
            marker.hide();
        };

        unselectMarker=function(marker) {
            //            marker.closeInfoWindow();
            $("#map").data("highlightedMarker").remove();
            marker.show();
        };

        goToRoutesByStop = function(stopName) {
            $.address.value("/showRoutesByStop/"+stopName);
        }

        showRoutesByStop = function(stopName) {
            $("#timetables-bookmarks li:first").removeClass("active");
            $("#timetables-bookmarks li:last").addClass("active");
            displayTimetablesContainer("timetables-loading");
            $.ajax({
                dataType: 'jsonp',
                data: 'stop='+stopName,
                jsonp: 'jsonp_callback',
                url: config.dbserviceURL+'routes_by_stop.php',
                success: function (data) {
                    $("#routesByStop").html("");
                    //display breadcrumbs
                    $("#routesByStop").append("<div class='breadcrumbs'></div>");
                    $("#routesByStop .breadcrumbs").html(breadcrumbsByStop());
                    $("#routesByStop .breadcrumbs a").click(function(e) {
                        e.preventDefault();
                    });
                    activateBreadcrumb($("#routesByStop .breadcrumbs a.stopBc"),goHome);
                    activateBreadcrumb($("#routesByStop .breadcrumbs a.lineBc"),showRoutesByStop,stopName);

                    $("#routesByStop").append($("<center><h3>"+data.currentStopName+"</h3></center>"));

                    $.each(data.routes,function(i,route) {
                        var currentElement = $("<a>");
                        currentElement.attr("href","");
                        currentElement.attr("class","route");
                        currentElement.html("<b>"+route.name+"</b>, "+ss.i18n._t('TIMETABLES.direction')+" <b>"+route.destination+"</b>");
                        if (route.night) {
                            currentElement.addClass("night");
                        }
                        currentElement.data("routeId",route.id);
                        currentElement.data("stopId",route.currentStopId);
                        currentElement.data("stopName",route.currentStopName);
                        $("#routesByStop").append(currentElement);
                    });
                    $("#routesByStop a.route").click(function(e) {
                        e.preventDefault();
                        goToTimetable($(this).data("routeId"),$(this).data("stopId"),"byStop");
                    });
                    displayTimetablesContainer("routesByStop");
                }
            });
        }

        goToTimetable = function(routeId,stopId,breadcrumbs) {
            $.address.value("/showTimetable/"+routeId+"/"+stopId+"/"+breadcrumbs);
        }

        showTimetable = function(routeId,stopId,breadcrumbs) {
            displayTimetablesContainer("timetables-loading");
            $.ajax({
                dataType: 'jsonp',
                data: 'route_id='+routeId+'&stop_id='+stopId,
                jsonp: 'jsonp_callback',
                url: config.dbserviceURL+'timetable.php',
                success: function (data) {
                    $("#theTimetable").html("");
                    
                    //display breadcrumbs
                    $("#theTimetable").append("<div class='breadcrumbs'></div>");
                    if (breadcrumbs=="byStop") {
                        $("#theTimetable .breadcrumbs").html(breadcrumbsByStop());
                        $("#theTimetable .breadcrumbs a").click(function(e) {
                            e.preventDefault();
                        });
                        activateBreadcrumb($("#theTimetable .breadcrumbs a.stopBc"),goHome);
                        activateBreadcrumb($("#theTimetable .breadcrumbs a.lineBc"),showRoutesByStop,stopId);
                        activateBreadcrumb($("#theTimetable .breadcrumbs a.timetableBc"));
                    } else {
                        $("#theTimetable .breadcrumbs").html(breadcrumbsByLine());
                        $("#theTimetable .breadcrumbs a").click(function(e) {
                            e.preventDefault();
                        });
                        activateBreadcrumb($("#theTimetable .breadcrumbs a.lineBc"),goHome);
                        activateBreadcrumb($("#theTimetable .breadcrumbs a.directionBc"),showRoutes,data.route.name);
                        activateBreadcrumb($("#theTimetable .breadcrumbs a.timetableBc"));
                    }
                    
                    
                    theTimetableHeader = $("<div id='theTimetableHeader'>");
                    var imgFilename;
                    imgFilename = data.route.type+".png";
                    var content="<h4><img src='timetables/images/";
                    content+=imgFilename;
                    content+="'/></h4>";
                    content+="<h4>"+ss.i18n._t('TIMETABLES.Line')+" "+data.route.name+"</h4>";
                    content+="<h4>"+ss.i18n._t('TIMETABLES.Direction')+" "+data.route.destination+"</h4>";
                    content+="<h4>"+ss.i18n._t('TIMETABLES.Stop')+" "+data.currentStop.name+"</h4>"
                    content+="<a href='' class='print'><img src='timetables/images/print.png'/></a><a href='' class='print'>"+ss.i18n._t('TIMETABLES.Print')+"</a>";
                    theTimetableHeader.html(content);
                    $("#theTimetable").append(theTimetableHeader);
                    // add behaviour to printable version link
                    $('.print').click(function(e)
                    {
                        e.preventDefault();
                        displayPrinterFriendlyVersion();
                    });

                    // here come the descriptions
                    content = "";
                    $.each(data.route.descriptions,function(i,description) {
                        content+=description.text+"<br/>" ;
                    });
                    if (content!="") {
                        $("#theTimetable").append(
                            $("<div id='theTimetableDescription'>").html(content));
                    }
                    theTimetableContent = $("<div id='theTimetableContent'>");
                    content="<table class='departures'>";
                    content+="<tr>";
                    content+="<th>&nbsp;</th>";
                    content+="<th>"+ss.i18n._t('TIMETABLES.Weekdays')+"</th>";
                    content+="<th>&nbsp;</th>";
                    content+="<th>"+ss.i18n._t('TIMETABLES.Saturdays')+"</th>";
                    content+="<th>&nbsp;</th>";
                    content+="<th>"+ss.i18n._t('TIMETABLES.SundaysAndHolidays')+"</th>";
                    content+="</tr>";

                    //prepare the slots for departures
                    if(!data.route.night) {
                        for (var i=4; i<28; i++) {
                            content+="<tr class='"+(i%24)+"'>";
                            $.each(['weekday','saturday','sunday'],function(j,day) {
                                content+="<th>"+(i%24)+"</th>";
                                content+="<td class='"+day+"'></td>";
                            });
                            content+="</tr>";
                        }
                    } else {
                        for (i=22; i<30; i++) {
                            content+="<tr class='"+(i%24)+"'>";
                            $.each(['weekday','saturday','sunday'],function(j,day) {
                                content+="<th>"+(i%24)+"</th>";
                                content+="<td class='"+day+"'></td>";
                            });
                            content+="</tr>";
                        }
                    }
                

                    content+="</table>"
                    theTimetableContent.html(content);
                    $("#theTimetable").append(theTimetableContent);

                    // now create a list of stops for this route
                    // and here we shall use jQuery extensively to store important data
                    stopsTable = $("<table>");
                    stopsTable.attr("class","stops");
                    stopsTable.append("<tr><th>"+ss.i18n._t('TIMETABLES.Stops')+"</th></tr>");

                    var map = $("#map").data("map");
                    map.clearOverlays();
                    var minLat=0;
                    var maxLat=0;
                    var minLng=0;
                    var maxLng=0;
                    var stopLatLngs = [];

                    $.each(data.route.stops,function(i,stop) {
                        var currentElement = $("<a>");
                        currentElement.attr("href","");
                        if (stop.time==0) {
                            currentElement.text(stop.name);
                        } else {
                            currentElement.html("<b>"+stop.time+"</b> "+stop.name);
                        }
                        currentElement.data("id",stop.id);
                        currentElement.data("latLng",new GLatLng(stop.lat,stop.lng));
                        var latLng = new GLatLng(stop.lat,stop.lng);
                        if (!latLng.equals(new GLatLng(0,0))) {
                            var marker = new GMarker(latLng, getMarkerOptionsForGMaps());
                            map.addOverlay(marker);
                            currentElement.data("marker",marker);
                            stopLatLngs.push(latLng);
                            if ((minLat==0) || (latLng.lat()<minLat)) {
                                minLat=latLng.lat();
                            }
                            if ((maxLat==0) || (latLng.lat()>maxLat)) {
                                maxLat=latLng.lat();
                            }
                            if ((minLng==0) || (latLng.lng()<minLng)) {
                                minLng=latLng.lng();
                            }
                            if ((maxLng==0) || (latLng.lng()>maxLng)) {
                                maxLng=latLng.lng();
                            }

                        }
                        if(stop.id==data.currentStop.id) {
                            currentElement.addClass("currentStop");
                            currentElement.click(function(e) {
                                e.preventDefault();
                            });
                        }
                        stopsTable.append($("<tr>").append($("<td>").append(currentElement)));
                    });
                    $("#theTimetableContent").append(stopsTable);

                    map.addOverlay(new GPolyline(stopLatLngs,"#ff0000",5));
                    var targetZoomLevel = map.getBoundsZoomLevel(new GLatLngBounds(
                        new GLatLng(minLat,minLng),new GLatLng(maxLat,maxLng)));
                    map.setZoom(Math.min(targetZoomLevel,config.maxMapZoomLevel));
                    map.panTo(new GLatLng((maxLat+minLat)/2,(maxLng+minLng)/2));


                    

                    //populate the timetable slots
                    $.each(data.timetables,function(i,timetable) {
                        $.each(timetable.hours,function(i,hour) {
                            var slot="";
                            $.each(hour.departures, function (i,departure) {
                                if (departure.minute==0) {
                                    slot+='00';
                                } else if (departure.minute<10) {
                                    slot+='0'+departure.minute;
                                } else {
                                    slot+=departure.minute;
                                }
                                slot+=departure.note+" ";
                            });
                            $("#theTimetableContent table tr."+hour.hour+" td."+timetable.dayType).text(slot);
                        });
                    });

                    //hack to center the actual tables
                    var difference = $("#theTimetableContent table:first").width()-$("#theTimetableContent table:last").width();
                    if (difference>1) {
                        $("#theTimetableContent table:first").before("<div style='margin:0; padding:0; float:left; width:"+
                            difference+"'>&nbsp;</div>");
                    }

                    //store some missing data
                    $("#theTimetableContent").data("routeId",data.route.id);
                    $("#theTimetableContent").data("stopId",data.currentStop.id);
                    $("#theTimetableContent").data("stopName",data.currentStop.name);


                    //apply behaviour to stops list elements
                    $("#theTimetableContent table:last td a:not(.currentStop)").click(function(e) {
                        e.preventDefault();
                        goToTimetable($("#theTimetableContent").data("routeId"), $(this).data("id"),breadcrumbs);
                    });
                    $("#theTimetableContent table:last td a").hover(function() {
                        selectMarker($(this).data("marker"));
                    }, function() {
                        unselectMarker($(this).data("marker"));
                    });

                    displayTimetablesContainer("theTimetable");

                    // take care of the transfers

                    var transfers = $("<div id='transfers'/>");
                    transfers.html("<h4>"+ss.i18n._t('TIMETABLES.Transfers')+": </h4>")
                    $.each(data.transfers,function(i,route) {
                        var currentElement = $("<a>");
                        currentElement.attr("href","");
                        currentElement.html("<b>"+route.name+"</b>, "+ss.i18n._t('TIMETABLES.direction')+": <b>"+route.destination+"</b>");
                        if (route.night) {
                            currentElement.addClass("night");
                        }
                        currentElement.data("routeId",route.id);
                        currentElement.data("stopId",route.currentStopId);
                        currentElement.data("stopName",route.currentStopName);
                        transfers.append(currentElement);
                    });
                    $("#theTimetable").append(transfers);

                    $("#transfers a").click(function(e) {
                        e.preventDefault();
                        goToTimetable($(this).data("routeId"),$(this).data("stopId"),breadcrumbs);
                    });
                }
            });
        };



        displayTimetablesContainer = function(name) {
            $("#timetables-content div.timetables-container:visible").hide();
            $("#timetables-content div#"+name).show();
        }

        initializeGoogleMaps = function() {
            var map = new GMap2(document.getElementById('map'));
            //            var mapCenterLatLng = new GLatLng(52.406374,16.9251681);
            var mapCenterLatLng = new GLatLng(config.mapCenter.lat,config.mapCenter.lng);
            map.setCenter(mapCenterLatLng, config.maxMapZoomLevel);
            //            map.addOverlay(new GMarker(poznanLatLng, getMarkerOptionsForGMaps()));
            //            map.addControl(new GLargeMapControl3D);
            return map;
        };

        getMarkerOptionsForGMaps = function() {
            // Create "tiny" marker icon - as in Maps API docs
            var tinyIcon = new GIcon();
            tinyIcon.image = "timetables/images/mm_20_green.png";
            tinyIcon.shadow = "timetables/images/mm_20_shadow.png";
            tinyIcon.iconSize = new GSize(12, 20);
            tinyIcon.shadowSize = new GSize(22, 20);
            tinyIcon.iconAnchor = new GPoint(6, 20);
            tinyIcon.infoWindowAnchor = new GPoint(5, 1);
            return {
                icon:tinyIcon
            };
        };

        getHighlightedMarkerOptionsForGMaps = function() {
            // Create "tiny" marker icon - as in Maps API docs
            var tinyIcon = new GIcon();
            tinyIcon.image = "timetables/images/mm_20_white.png";
            tinyIcon.shadow = "timetables/images/mm_20_shadow.png";
            tinyIcon.iconSize = new GSize(20, 27);
            tinyIcon.shadowSize = new GSize(22, 20);
            tinyIcon.iconAnchor = new GPoint(10, 27);
            tinyIcon.infoWindowAnchor = new GPoint(8, 1);
            return {
                icon:tinyIcon
            };
        };

        breadcrumbsByLine = function() {
            var content="";
            content+='<a class="lineBc inactive">'+ss.i18n._t("TIMETABLES.Line")+'</a> Âť ';
            content+='<a class="directionBc inactive">'+ss.i18n._t("TIMETABLES.Direction")+'</a> Âť ';
            content+='<a class="timetableBc inactive">'+ss.i18n._t("TIMETABLES.Timetable")+'</a>';
            return content;
        }

        breadcrumbsByStop = function() {
            var content="";
            content+='<a href="" class="stopBc inactive">'+ss.i18n._t("TIMETABLES.Stop")+'</a> Âť ';
            content+='<a href="" class="lineBc inactive">'+ss.i18n._t("TIMETABLES.Line")+'</a> Âť ';
            content+='<a href="" class="timetableBc inactive">'+ss.i18n._t("TIMETABLES.Timetable")+'</a>';
            return content;
        }

        activateBreadcrumb = function(breadcrumb,callback,callbackArg) {
            breadcrumb.removeClass("inactive");
            breadcrumb.attr("href", "#");
            breadcrumb.click(function(e) {
                e.preventDefault();
//                displayTimetablesContainer(container);
                  callback(callbackArg);
            });
        }

        displayPrinterFriendlyVersion = function() {
            var html = "<html>\n<head>\n"+
            '<title>RozkĹad jazdy</title>'+
            '<link rel="stylesheet" type="text/css" href="timetables/css/printable.css" />'+
            "\n</head>\n<body>\n"+
            $("#theTimetableHeader").html()+
            $("#theTimetableDescription").html()+
            $("#theTimetableContent").html()+
            "\n</body>\n</html>";
            var printerFriendly = window.open();
            printerFriendly.document.open();
            printerFriendly.document.write(html);
            printerFriendly.document.close();
            printerFriendly.print();
        }

        goHome = function() {
            $.address.value("/home/");
        }

        showLines = function() {
            displayTimetablesContainer("timetablesHome");
        }

        processUrl = function() {
            switch ($.address.pathNames()[0]) {
                case "showRoutes":
                    showRoutes($.address.pathNames()[1]);
                    break;
                case "showRoutesByStop":
                    showRoutesByStop($.address.pathNames()[1]);
                    break;
                case "showTimetable":
                    showTimetable($.address.pathNames()[1],
                        $.address.pathNames()[2], $.address.pathNames()[3]);
                    break;
                case "showStopsLike":
                    showStopsLike($.address.pathNames()[1]);
                    break;
                case "home":
                default:
                    showLines();
                    break;
            }
        }


        // multi-choice single search field related functions:


        enableWidget = function() {
            $("#timetablesHome").data(
                "list",
                $("#timetablesHome").data("lines")
                    .map(processLineListItem)
                    .concat(
                        $("#timetablesHome").data("stops")
                            .map(processStopListItem)
                    )
            );

            var inputField = $("#timetablesWidgetInputField");
            inputField.attr("value",ss.i18n._t(config.searchFieldDescription));
            inputField.click(function(e) {
                $(this).attr("value","");
            });

            inputField.autocomplete($("#timetablesHome").data("list"), {
              formatItem: function(item) {
                  return item.template;
              },
              matchContains: true
            }).result(function(event,item) {
               gotoTimetables(item);
            });

        };

        processLineListItem = function(item) {
            var processedItem = new Object();
            processedItem.name = item.name;
            processedItem.template = item.name+" ("+ss.i18n._t('TIMETABLES.line')+")";
            processedItem.functionName = "showRoutes";
            processedItem.functionArg = item.name;
            return processedItem;
        };

        processStopListItem = function(item) {
            var processedItem = new Object();
            processedItem.name = item.name;
            processedItem.template = item.name+" ("+ss.i18n._t('TIMETABLES.stop')+")";
            processedItem.functionName = "showRoutesByStop";
            processedItem.functionArg = item.id;
            return processedItem;
        };

        gotoTimetables = function(item) {
            $.address.value("/"+item.functionName+"/"+item.functionArg);
        }

		checkLocale = function() {
				if (window.location.pathname.match("[rozklady][rozklad][rozkladow]")) {
					ss.i18n.setLocale("pl_PL");
				} else if (window.location.pathname.match("[english][timetable][timetables]")) {
					ss.i18n.setLocale("en_US");
				}
		}

        // ====================== END: FUNCTIONS ===============================

        // ================= ACTUAL DOCUMENT-READY PROCEDURE ===================
        //resolve possible compatibility issues, vide:	https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/map
        if (!Array.prototype.map)
        {
            Array.prototype.map = function(fun /*, thisp*/)
            {
                var len = this.length >>> 0;
                if (typeof fun != "function")
                    throw new TypeError();

                var res = new Array(len);
                var thisp = arguments[1];
                for (var i = 0; i < len; i++)
                {
                    if (i in this)
                        res[i] = fun.call(thisp, this[i], i, this);
                }

                return res;
            };
        }
		
		checkLocale();
		


		$("#timetables-header h3").html(ss.i18n._t('TIMETABLES.Timetables'));
		$("#timetables-loading h4").html(ss.i18n._t('TIMETABLES.Loading'));
		
		
		
        $("#timetablesHome").show();
        displayTimetablesContainer("timetables-loading");
    
        // load data
        loadLines();
        
        // take care of the Google Maps
        $("#map").data("map",initializeGoogleMaps());

        // check the url for possible deep linked commands
        processUrl();
        // ensure that it gets done each time the address changes
        $.address.change(function(event) {
            processUrl();
        });

    // Standard jQuery footer
    })
})(jQuery);