var resizeinterval = 0;
$.maxZIndex = $.fn.maxZIndex = function(opt) {
    /// <summary>
    /// Returns the max zOrder in the document (no parameter)
    /// Sets max zOrder by passing a non-zero number
    /// which gets added to the highest zOrder.
    /// </summary>    
    /// <param name="opt" type="object">
    /// inc: increment value, 
    /// group: selector for zIndex elements to find max for
    /// </param>
    /// <returns type="jQuery" />
    var def = { inc: 10, group: "*" };
    $.extend(def, opt);
    var zmax = 0;
    $(def.group).each(function() {
        var cur = parseInt($(this).css('z-index'));
        zmax = cur > zmax ? cur : zmax;
    });
    if (!this.jquery)
        return zmax;

    return this.each(function() {
        zmax += def.inc;
        $(this).css("z-index", zmax);
    });
}
;(function($) {
    $.fn.textfill = function(options) {
        var fontSize = options.maxFontPixels;
        var ourText = $('span:visible:first', this);
        var maxHeight = $(this).height();
        var maxWidth = $(this).width();
        var textHeight;
        var textWidth;
        while (textHeight >= maxHeight || textWidth >= maxWidth && fontSize > 3) {
                ourText.css('font-size', fontSize);
                textHeight = ourText.height();
                textWidth = ourText.width();
                fontSize = fontSize - 1;
        }
        return this;
 	}
})(jQuery);

function show_speed_graph()
{
	var choiceContainer = $("#speedchoices");
	if (race.speedgraph && race.speedgraph.dialog( "isOpen" ))
	{
		race.speedgraph.dialog("close");
		return;
	}
	else
	{
		choiceContainer.find("input").click(plotAccordingToChoices);
		$("#speedgraph #select_all").click(function()
		{
			if ($("#speedgraph #select_all").attr("checked"))
			{
				$("#speedchoices").find("input").each(function(){$(this).attr("checked", true)});
			}
			else
			{
				$("#speedchoices").find("input").each(function(){$(this).removeAttr("checked")});
			}
			plotAccordingToChoices();
		});
	}

 	function plotAccordingToChoices() 
	{
		var datasets = new Array();
        choiceContainer.find("input:checked").each(function () {
            var key = $(this).attr("name");
            if (key)
			{
				var participant = race.participants[key];
				datasets.push(participant.getFlotData());
			}
        });
		 
        if (datasets.length > 0)
			$.plot($('#plot'), datasets, {
								xaxis: {
										mode: "time",
										label: "time" 
										}
							});
	}
	race.speedgraph = $("#speedgraph").dialog({width:850, height:360, title: "Kiirus ajas (km/h)", resizable: false});

	plotAccordingToChoices();	
}

function show_stats()
{
		
	if (race.timelinedialog && $("#timeline").dialog("isOpen"))
	{
		$("#timeline").dialog("close");
		return;
	}
	else
	{
		race.timelinedialog = $("#timeline").dialog({width:400, height: 600});
	}
	$("#timeline").html(format_timeline());
	
	var timepoints = new Array();

	for (var i in race.timeline)
	{
		for (var j in race.timeline[i])
		{
			for (var h in race.timeline[i][j])
			{
				var tp = race.timeline[i][j][h];
				if ($("id"+tp[1]) && $("id"+tp[1]).attr("checked"))
				{
					if (!timepoints[tp[1]])
						timepoints[tp[1]] = new Array();
					timepoints[tp[1]].push(new Array(tp[1], tp[2].speed));
				}
			}
		}
	}
	$("#wp_accordion").accordion({fillSpace:false, collapsible: true, autoHeight: false});
}
$(document).ready(function () {
	//
	//set up buttons
	//
	if ($.browser.msie && parseInt($.browser.version) < 9)
	{
		alert("Parima elamuse saamiseks soovitame kasutada Google Chrome'i, Mozilla  Firefoxi, Safari, Opera, Rekonqi võ Konquerori viimaseid versioone.");
	}
	$("#speed_graph").click(function(){show_speed_graph();});
	$("#wp_stats").click(function(){show_stats();});

	//
	//style table
	//
	$(".jtable th").each(function(){
	  $(this).addClass("ui-widget-header");
	});
	$(".jtable td").each(function(){
		$(this).addClass("ui-widget-content");
	});
	$(".jtable tr").hover(
    	function()
		{
      		$(this).children("td").addClass("ui-state-hover");
     	},
     	function()
     	{
      		$(this).children("td").removeClass("ui-state-hover");
     	}
	);
	//
	//style checkboxes
	//
	$("table input").filter(":checkbox,:radio").checkbox();
	$("#tail_slider").slider({
			min: 0,
			max: 600,
			value: Math.round((Math.log(race.default_tail))/(Math.log(Math.pow(2, 1/60)))),
			slide: function(event, ui) {
			}
		});
	$("#speed_slider").slider({
			min: 100,
			max: 1000,
			step: 100,
			value: 537,
			orientation: "vertical",
			slide: function(event, ui) {
				var new_speed = 1100 - ui.value;
				var speed = race.interval / new_speed * 1000;
				$("#speed_text").text("1 : "+Math.round(speed));
				$("#speed_slider_container").textfill({ maxFontPixels: 36 });
			},
			stop: function(event, ui) {
				changespeed();
			}
		});
	$("#hop_slider").slider({
			min: 1,
			max: 100,
			step: 1,
			value: 49,
			stop: function(event, ui) {
				changespeed();
			}
		});
	if ($('#map_canvas').width() > 500)
	{
		$('ui-slider-handle').focus();
		var tip = $('.info').cluetip({
			activation: 'click', 
			mouseOutClose: true,
			cluetipClass: 'jtip',
			arrows: true,
			onShow: function() {$('#cluetip').maxZIndex(); },
			showTitle: false}
		);
		$('#cluetip-inner').mouseleave(function () {$('#cluetip').hide()})
	}
	else
	{
		$('#logocontainer').hide();
	}
	$(".fg-button:not(.ui-state-disabled)").hover(
		function(){ 
		$(this).addClass("ui-state-hover"); 
		},
		function(){ 
		$(this).removeClass("ui-state-hover"); 
		}
	      ).mousedown(function(){
		$(this).parents('.fg-buttonset-single:first').find(".fg-button.ui-state-active").removeClass("ui-state-active");
		if( $(this).is('.ui-state-active.fg-button-toggleable, .fg-buttonset-multi .ui-state-active') ){ $(this).removeClass("ui-state-active"); }
		else { $(this).addClass("ui-state-active"); }	
		})
		.mouseup(function(){
		if(! $(this).is('.fg-button-toggleable, .fg-buttonset-single .fg-button,  .fg-buttonset-multi .fg-button') ){
		$(this).removeClass("ui-state-active");
		}
	});
	

	$("button").each(function(){$(this).button()});
	
	$("#speed_slider_container").mouseleave(function(){
		$(this).hide();
	});
	$("#speed_button").click(function(){
		var offset= $(this).offset();
		offset.top = offset.top + $(this).height();
		$("#speed_slider_container").show().offset(offset).width($(this).width())
	});
	var new_speed = 1100 - $("#speed_slider").slider("value");
	var speed = race.interval / new_speed * 1000;
	$("#speed_text").text("1 : "+Math.round(speed));
	$("#autozoom").click(function(){
		if ($('#autozoom').attr("checked"))
			fitMapToMarkers();
	});
	resizePage();
	$(window).resize(function() {
		resizePage();
	});

});

function resizePage(){
	$("#content").height($(window).height() - 50);
	var newheight = $("#content").height() - $("#logo_div").height() - $("#settings_div").height() - $("#ads_div").height() - 80;
	$("#part_div").height("auto");
	if ( $("#part_div").height() > newheight )
	{
		$("#part_div").height(newheight);
		$("#part_div").width($("#part_table").width()+20);
	}
	$("#ads_img").width($("#part_div").width());
	$("#header .side").width($("#part_div").width());
	$("#header .content").width($("#map_canvas").width() - 80);
}
function playbackToggle() //{{{
{
	$('#playback').slideToggle(100);
}//}}}

function forceReload() //{{{
{
	$( "<div id='dialog-confirm' title='S&otilde;idu andmetes on toimunud muudatus'><p><span class='ui-icon ui-icon-alert' style='float:left; margin:0 7px 20px 0;'></span>Uute andmete saamiseks on vaja leht uuesti laadida.</p></div>" ).dialog({
		resizable: false,
		modal: true,
		buttons: {
			"Lae leht uuesti": function() {
				location.reload();
			},
			"Tühista": function() {
				$( this ).dialog( "close" );
			}
		}
	});
}
//}}}
var tilesloaded_listener;

function initMap()
{
	bounds = new google.maps.LatLngBounds();
	var myOptions = {
		zoom: 14,
		center: bounds.getCenter(),
		scaleControl: true,
		mapTypeControl: false,
		mapTypeControlOptions: 
		{
			style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR, 
			position: google.maps.ControlPosition.BOTTOM,
			mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'Custom']
		},
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		navigationControlOptions: { position: google.maps.ControlPosition.RIGHT }
	};
	map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	
	var TrackMapType = new google.maps.StyledMapType(mapstyle, {name: "Custom Styled"});
	map.mapTypes.set('Custom', TrackMapType);
	map.setMapTypeId("Custom");
	
		
	tilesloaded_listener = google.maps.event.addListener(map, 'tilesloaded', function(){
		$($(".gmnoprint")[2]).css("display", "none");
		$($(".gmnoprint")[2]).next().css("display", "none");
		$($(".gmnoprint")[5]).css("top", "25px");
		google.maps.event.removeListener(tilesloaded_listener);
	});
	if ($("#meremargid").length != 0)
	{
		race.meremargid = new google.maps.KmlLayer('http://navi.kipper.ee/navikipperviiret.kml', {preserveViewport: true, suppressInfoWindows: false });

		if ($("#meremargid").attr("checked"))
			race.meremargid.setMap(map);
	}

}


