;
// 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() {
    	/// preinitialize
		
    	//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 = 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");
			} else {
				ss.i18n.setLocale("pl_PL");
			}
    	}
    	checkLocale();
    	
        // ==================== LOAD THE CONFIGURATION =========================
        config={};
        $.ajax({
            type: "GET",
            url: "timetablesConfig.json",
            dataType: "json",
            cache: false,
            async: false,
            success: function(data) {
                config = data;
            },
            error: function() {
                var reload = confirm("Nie udało się pobrać pliku konfiguracyjnego.\nCzy chcesz spróbować ponownie?");
				if (reload) {
					window.location.reload();
				}
            }
        }); 
		
		if (config.theme) {
			var fileref=document.createElement("link");
		  	fileref.setAttribute("rel", "stylesheet");
		  	fileref.setAttribute("type", "text/css");
		  	fileref.setAttribute("href", "timetables/css/"+config.theme+".css");
		  	document.getElementsByTagName("head")[0].appendChild(fileref);	
		} else {
			config.theme = "kombus"; // default theme (for some backwards-compatibility)
		}
        
		getFullUrlForResource = function(resource) {
			if (config.siteId>0) {
			if (resource.split("?").length>1) {
				resource+="&"
			} else {
				resource+="?";
			}
			resource+="site_id="+config.siteId;
			} else if (config.operatorId>0) {
				if (resource.split("?").length>1) {
					resource+="&"
				} else {
					resource+="?";
				}
				resource+="operator_id="+config.operatorId;
			}
			if (config.dbName!=undefined) {
				if (resource.split("?").length>1) {
					resource+="&"
				} else {
					resource+="?";
				}
				resource+="dbname="+config.dbName;
			}
			if (config.dbserviceURL.split("proxy").length>1) {
				resource = escape(resource);
			}
			return config.dbserviceURL+resource;
		}
		
        
		$.ajax({
			type: "GET",
			url: getFullUrlForResource("places.json.php"),
			dataType: "json",
			cache: false,
			async: false,
			success: function(data) {
				$("#timetablesSidebar").data(
						"stops", data.places
				);

			},
			error: function() {
				var reload = confirm("Nie udało się pobrać informacji o przystankach.\nCzy chcesz spróbować ponownie?");
				if (reload) {
					window.location.reload();
				}
			}
		}); 
		
        $.ajax({
            type: "GET",
            url: getFullUrlForResource("routes_by_name.json.php"),
            dataType: "json",
            cache: false,
            async: false,
            success: function(data) {
	        	 $("#timetablesSidebar").data(
	        	            "routes", data.lines
	        	 );
            },
            error: function() {
				$.ajax({
					type: "GET",	//one more time
					url: getFullUrlForResource("routes_by_name.json.php"),
					dataType: "json",
					cache: false,
					async: false,
					success: function(data) {
						 $("#timetablesSidebar").data(
									"routes", data.lines
						 );
					},
					error: function() {
						var reload = confirm("Nie udało się pobrać informacji o liniach.\nCzy chcesz spróbować ponownie?");
						if (reload) {
							window.location.reload();
						}
					}
				});
            }
        }); 
        
        // =============== Load basic data ===============================
        
        
// ========================== GLOBALS ================================

	//global for storing current screen
	currentScreen="";
	
	TIMETABLE="timetable";
	ROUTES_BY_NAME="routesByName";
	ROUTE_DIRECTIONS="routeDirections";
	
	mousedown=false;

// ======================== END OF GLOBALS ===========================

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

	createOverlay = function() {
		overlay = $("<div id='overlay'></div>");
		$("body").append(overlay);
	}
	
	showOverlay = function() {
		$("#overlay").show();//css("display","block");
	}
	
	hideOverlay = function() {
		$("#overlay").hide();//css("display","none");
	}
	
	

	truncateText = function(element,targetWidth,targetLength) {
		if (((targetWidth==0)&&(element.html().length>targetLength))
				|| ((targetWidth!=0)&&(element.width()>targetWidth))) {
				element.html(element.html().substring(0,targetLength-4+element.html().length-element.text().length)+'...');
		} 
	}

	injectHtmlIntoSidebar = function(resource,callback) {
		showOverlay();
		$("#timetablesSidebar").load(getFullUrlForResource(resource)+" #main",function(){
			hideOverlay();
			if (callback!=undefined) {
				callback();
			}
			onAjaxLoad();
		});
	};

	getHashFromUrl = function (url,base) {
		url = url.split("/");
		url = url[url.length-1];
		url = url.split("?");
		switch(url[0]) {
			case "route_directions.html.php":
				return base+"/kierunki/"+url[1].split("=")[1];
			case "timetable.html.php":
				url=url[1].split("&");
				return base+"/rozklad/"+url[0].split("=")[1]+"/"+url[1].split("=")[1]+"/"+"wgLinii";
			case "routes_by_name.html.php":
			default:
				return base;
		}
	}

    onAjaxLoad = function() {
    	if ($("#timetablesSidebar").height()<$("#main").height()) {
    		$("#timetablesSidebar").height($("#main").height());
    	}
/*		if (currentScreen==TIMETABLE) {
				$("#timetablesMap").width(300);
				$("#timetablesMapWrapper").width(300);
				$("#timetablesSidebar").width(550);
		} else {
				$("#timetablesSidebar").width(400);
				$("#timetablesMapWrapper").width(450);
				$("#timetablesMap").width(450);
				
		}*/
		
		if (currentScreen==ROUTES_BY_NAME) {
			$("#timetablesSearchWrapper").append("<input id='timetablesSearchBox' type='text'>");
			enableWidget();
		}
		
		//resizeTimetablesMap();
		base = window.location.href.split("#")[0]+"#";
		//alert('fixing hrefs in a moment');
		$.each($("#timetablesSidebar a"),function(j,a) {
			//alert('fixing href for '+a+": "+getHashFromUrl($(a).attr("href"),base)+
					//"\n$(a).attr('href')="+$(a).attr("href"));
			if ((parseFloat(navigator.appVersion.split("MSIE")[1])<7)) {
				 //IE 6 wants to reload the whole page on hash update so let's prevent this
				 // Opera fails here as well
				$(a).click(function(e) {
					e.preventDefault();
					showOverlay();
					var resource = $(a).attr("href");
					resource = resource.split("/");
					resource = resource[resource.length-1];
//					alert(resource);
					injectHtmlIntoSidebar(resource);
				});
			} else {
				$(a).attr("href",getHashFromUrl($(a).attr("href"),base));
			}
			  	
        });
		
		/* fix breadcrumbs in Firefox (sic!)
		 * 		I didn't have time to find out why it's so, but
		 * 		under firefox all <a><li>...</li><a> from source are
		 * 		replaced by <a></a><li><a>...</a></li> 
		 * 		And therefore we cannot style this as nicely in pure css (no "hover" detection for "li")
		 */
		if ($.browser.mozilla) {
			$("#timetablesBreadcrumbs ol li a").parent().css("background-image", "url(timetables/images/"+config.theme+"/breadcrumb-link.png)");
			$("#timetablesBreadcrumbs ol li a").parent().mouseover(function () {$(this).css("background-image", "url(timetables/images/"+config.theme+"/breadcrumb-active.png)")});
			$("#timetablesBreadcrumbs ol li a").parent().mouseout(function () {$(this).css("background-image", "url(timetables/images/"+config.theme+"/breadcrumb-link.png)")});
			$("#timetablesBreadcrumbs ol li a").parent().click(function () {window.location=$($(this).children()[0]).attr("href")});
		}
		
		/*
		 * 
		 */
		if ($(".routeListWrapper").length==1) {
			$(".routeListWrapper").css("width","100%");
		}
		if ($(".routeDirection").length==1) {
			$(".routeDirection").css("margin-left","116px");
		}
		if (currentScreen == TIMETABLE) {
			//reverse transfer tabs sorting
			mylist = $('#transfers ul');
			listitems = mylist.children('li').get();
			listitems.sort(function(a, b) {
			   compA = $(a).text();
			   compB = $(b).text();
			   return (+compA > +compB) ? -1 : (+compA < +compB) ? 1 : 0;
			})
			$.each(listitems, function(idx, itm) { mylist.append(itm); });
			
			//hide operator name when it should not be displayed
			if (config.showOperatorName) {
				$("#operatorName").show();
			}
			
			//fix descriptions
			var splt = $("#descriptions").html().split(/ . - /g);
			var mtch = $("#descriptions").html().match(/ . - /g);
			var newd = splt[0];
			for (var i=1; i<splt.length; i++) {
				newd+="<br/>";
				newd+=mtch[i-1];
				newd+=splt[i];
			}
			// remove stray "# - " if there is a mistake in the database
//			newd = $("#descriptions").html().split(/ . -<br>/g);
//			newd = newd.join("<br/>");
			$("#descriptions").html(newd);
			
			//truncate stop names
			/*$.each($("#stops ul li a, #stops ul li b"),function(idx,itm) {
				truncateText($(itm),130,18);
			});
			
			$.each($("#timetableHeader h5.direction, #timetableHeader h5.currentStop"),function(idx,itm) {
				truncateText($(itm),0,18);
			});*/
			
			//fix stops div height
			var stopsHeight = $("#descriptions").position().top+$("#descriptions").height()-$("#stops").position().top+9;
			if (stopsHeight<250) {
				$("#descriptions").height($("#descriptions").height()+250-stopsHeight);
				stopsHeight=250;
			}
			$("#stops").height(stopsHeight);
			
			//and scroll it to show current stop
//			$("#stops").scrollTop($("#stops ul b").position().top-$("#stops").position().top);
			$("#stops").scrollTop($("#stops ul b").position().top-20);
			// fix sidebar height
			minHeight = $("#stops").position().top+$("#stops").height();
			if ($("#timetablesSidebar").height()<minHeight) {
				$("#timetablesSidebar").height(minHeight);
			}
			
//			printButton = $("<div id='printButton'><a href='javascript:window.print();'>&nbsp;</a></div>");
//			$("#timetablesSidebar").append(printButton);
			$("#printButton a").text("");
			$("#printButton").click(function(e) {
				e.preventDefault();
				window.print();
			});
			
			$("#timetablesSidebar").append($("<div id='scrollStopsUp' class='scrollStops'><a href='#'><img src='timetables/images/"+config.theme+"/scrollUp.png'></img></a></div><div id='scrollStopsDown' class='scrollStops'><a href='#'><img src='timetables/images/"+config.theme+"/scrollDown.png'></img></a></div>"));
			
			$("#scrollStopsDown").css("top",$("#stops").height()+parseInt($("#stops").css("top"))-12+"px");			
			
			$(document).bind('mouseup',function(){mousedown=false});
			
			$("#scrollStopsUp a").click(function(e) {
				e.preventDefault();
			});
			
			$("#scrollStopsUp a").bind("mousedown",function() {
				mousedown=true;
				scrollStopsUp();
			});
			
			$("#scrollStopsDown a").click(function(e) {
				e.preventDefault();
			});
			
			$("#scrollStopsDown a").bind("mousedown",function() {
				mousedown=true;
				scrollStopsDown();
			});
			
			$("#scrollStopsDown a").bind("mouseover",function() {
				if (!$("#scrollStopsDown a img").data("disabled")) {
					$("#scrollStopsDown a img").attr("src","timetables/images/"+config.theme+"/scrollDownOver.png");
				}
			});
			
			$("#scrollStopsDown a").bind("mouseout",function() {
				if (!$("#scrollStopsDown a img").data("disabled")) {
					$("#scrollStopsDown a img").attr("src","timetables/images/"+config.theme+"/scrollDown.png");
				}
			});
			
			$("#scrollStopsUp a").bind("mouseover",function() {
				if (!$("#scrollStopsUp a img").data("disabled")) {
					$("#scrollStopsUp a img").attr("src","timetables/images/"+config.theme+"/scrollUpOver.png");
				}
			});
			
			$("#scrollStopsUp a").bind("mouseout",function() {
				if (!$("#scrollStopsUp a img").data("disabled")) {
					$("#scrollStopsUp a img").attr("src","timetables/images/"+config.theme+"/scrollUp.png");
				}
			});
			
			if ($("#stops").scrollTop()==0) {
				scrollStopsUpDisabled();
			} 
				if ($("#stops").scrollTop()>=$("#stops ul").height()-$("#stops").height()) {
				scrollStopsDownDisabled();	
			}
			
			hideOverlay();	
		}
    };
	
	scrollStopsUp = function() {
		var scrollTop = $("#stops").scrollTop();
		if (mousedown&&(scrollTop>0)) {
			scrollStopsDownOut();
			$("#stops").scrollTop(scrollTop-2);
			if (scrollTop-2<=1) {
				scrollStopsUpDisabled();	
			}
			setTimeout(scrollStopsUp,10);
		} 
	};
	
	scrollStopsDown = function() {
		var scrollTop = $("#stops").scrollTop();
		if (mousedown&&(scrollTop<$("#stops ul").height()-$("#stops").height())) {
			scrollStopsUpOut();
			$("#stops").scrollTop(scrollTop+2);
			if (scrollTop+2>=$("#stops ul").height()-$("#stops").height()) {
				scrollStopsDownDisabled();	
			}
			setTimeout(scrollStopsDown,10);
		}
	};
	
	scrollStopsDownDisabled = function () {
		$("#scrollStopsDown a img").attr("src","timetables/images/"+config.theme+"/scrollDownDisabled.png").data("disabled",true);	
	};
	
	scrollStopsDownOver = function () {
		$("#scrollStopsDown a img").attr("src","timetables/images"+config.theme+"//scrollDownOver.png").data("disabled",false);
	};
	
	scrollStopsDownOut = function () {
		$("#scrollStopsDown a img").attr("src","timetables/images/"+config.theme+"/scrollDown.png").data("disabled",false);
	};
	
	scrollStopsUpDisabled = function () {
		$("#scrollStopsUp a img").attr("src","timetables/images/"+config.theme+"/scrollUpDisabled.png").data("disabled",true);
	};
	
	scrollStopsUpOver = function () {
		$("#scrollStopsUp a img").attr("src","timetables/images/"+config.theme+"/scrollUpOver.png").data("disabled",false);
	};
	
	scrollStopsUpOut = function () {
		$("#scrollStopsUp a img").attr("src","timetables/images/"+config.theme+"/scrollUp.png").data("disabled",false);
	};
	
	onTimetablesLoad = function() {
		
	};
	
	resizeTimetablesMap = function(width) {	
			if (width == undefined) {
						var width = 455;
			}
			targetHeightOffset = Math.max($("#timetablesMapWrapper").offset().top-$(window).scrollTop(),0);
			if (window.innerHeight!=undefined) {
				windowHeight=window.innerHeight;
			} else {
				windowHeight = document.documentElement.clientHeight;
			}
			targetHeight = windowHeight-targetHeightOffset;
			$("#timetablesMap").height(targetHeight);
			maxWrapperPaddingTop = $("#timetablesSidebar").height()-$("#timetablesMap").height();
			$("#timetablesMapWrapper").css("padding-top",Math.max(Math.min($(window).scrollTop()-$("#timetablesMapWrapper").offset().top,maxWrapperPaddingTop),0));
	};
	
	processUrl = function() {
            switch ($.address.pathNames()[0]) {
                case "showRoutes":
				case "kierunki":
					currentScreen = ROUTE_DIRECTIONS;
					injectHtmlIntoSidebar("route_directions.html.php?route_name="+$.address.pathNames()[1]);
                    break;
                case "showRoutesByStop":
                case "zPrzystanku":
//                    showRoutesByStop($.address.pathNames()[1]);
                	injectHtmlIntoSidebar("routes_by_stop.html.php?stop="+$.address.pathNames()[1]);
                    break;
                case "showTimetable":
				case "rozklad":
					currentScreen = TIMETABLE;				
					injectHtmlIntoSidebar("timetable.html.php?route_id="+$.address.pathNames()[1]+"&stop_id="+$.address.pathNames()[2]+"&mode="+$.address.pathNames()[3],onTimetablesLoad);
//                    showTimetable($.address.pathNames()[1],
//                        $.address.pathNames()[2], $.address.pathNames()[3]);
                    break;
                case "showStopsLike":
//                    showStopsLike($.address.pathNames()[1]);
                    break;
                case "home":
                default:
					currentScreen = ROUTES_BY_NAME;
                    injectHtmlIntoSidebar("routes_by_name.html.php");
                    break;
            }
    }    
	
	
	 // multi-choice single search field related functions:


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

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

        inputField.autocomplete($("#timetablesSidebar").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.template = item.name+" (linia)";
        processedItem.functionName = "kierunki";
        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.template = item.name+" (przystanek";
		if (item.zone) {
			processedItem.template+=" w strefie "+item.zone;
		}
		processedItem.template+=")";
        processedItem.functionName = "zPrzystanku";
        processedItem.functionArg = item.id;
        return processedItem;
    };

    gotoTimetables = function(item) {
    	if (parseFloat(navigator.appVersion.split("MSIE")[1])<7) {
			 //IE 6 wants to reload the whole page on hash update so let's prevent this
				showOverlay();
				var resource = "";
				switch (item.functionName) {
					case "zPrzystanku":
						resource="routes_by_stop.html.php?stop=";
						break;
					case "kierunki":
						resource="routedirections.html.php?route_name=";
						break;
				}
				injectHtmlIntoSidebar(resource+item.functionArg);
		} else {
			$.address.value("/"+item.functionName+"/"+item.functionArg);
		}
    }
	
// ======================= END OF FUNCTIONS ===========================
    // the actual document.ready routine follows:

	// first of all, remove "no javascript" text
	$("#timetablesSidebar").text("Trwa ładowanie rozkładów jazdy...");	

    // ensure that it gets done each time the address changes
    
	
//	$(window).resize( resizeTimetablesMap );
//	$(window).scroll( resizeTimetablesMap );
	
	createOverlay();
	
//	injectHtmlIntoSidebar("routes_by_name.html.php");
    	
	$.address.change(function(event) {
        processUrl();
    });
	// check the url for possible deep linked commands
//    processUrl();
	
        // Standard jQuery footer
    })
})(jQuery);
