// Standard jQuery header
;(function($) {
    $(document).ready(function() {

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

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

        loadData = function() {
            loadLines();
//            loadStops();
//            enableWidget();
        };

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

        loadStops = function() {
            $.ajax({
                dataType: 'jsonp',
                data:'name_like=&operator_id='+config.operatorId,
                jsonp: 'jsonp_callback',
                url: config.dbserviceURL+'places.php',
                async: false,
                success: function (data) {
                    $("#timetablesWidget").data("stops",data.places);
                    enableWidget();
                }
            });

        };

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

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

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

//            inputField.autocomplete({
//                list:       $("#timetablesWidget").data("list"),
//                match:      function(typed) {
//                    return this.name.match(new RegExp("^"+typed,"i"));
//                },
//                insertText: function(item)  {
//                    return item.name
//                },
//                template:   function(item)  {
//                    return "<li>"+item.template+"</li>"
//                }
//            })
//            .bind("activate.autocomplete", function(e, 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) {
            window.location=ss.i18n._t(config.timetablesURL)+"#/"+item.functionName+"/"+item.functionArg;
        }

		checkLocale = function() {
			if (jQuery('meta[http-equiv="Content-Language"]').attr("content")=="en-US") {
				ss.i18n.setLocale("en_US");
			} else {
				ss.i18n.setLocale("pl_PL");
			}
		}


        // ====================== 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();
		$("#timetablesWidget h2").html(ss.i18n._t('TIMETABLES.Timetables'));

        loadData();

	


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