
var CalIsOpened = false;
var LoadDataTo = null;
GOOG_IS_LODED = false;
var HiddenRunOpened = false;

$(document).ready(function(){

	$('ul.TabsLevel2 li.selected a').click(
		function(){
			return false;
		}
	);

	$('#trains_from').change(
		function(){
			var param_found = false;
			var param2_found = false;
			var x = document.getElementById('trains_from');
			var y = document.getElementById('trains_to');
			var val2 = y.options[y.selectedIndex].value; 
			var val = x.options[x.selectedIndex].value;
			var uri = document.location.toString().split('?');
			
			params = uri[1].split('&');
			new_uri = '?';
			max = params.length;
			for(var i=0; i < max; i++ ){
				p = params[i].split("=");
				
				if(p[0]=='date') p[0]='';
				
				if( p[0] == 'selected_from'){
				  param_found = true;
				  p[1] = val.toString();
				}
				
				if( p[0] == 'selected_to'){
				  param2_found = true;
				}
				
				if( p )
				if( p[0]!='undefined' && p[1]!='undefined' && p[0]!='' && p[1]!='' )
					new_uri = new_uri +'&'+ p[0]+'='+p[1];
			}
			if( !param_found ) new_uri = new_uri+'&selected_from='+val;
			if( !param2_found ) new_uri = new_uri+'&selected_to='+val2;
			document.location = new_uri;
		}
	);
	
	
	$('#trains_to').change(
		function(){
			var param_found = false;
			var param2_found = false;
			var x = document.getElementById('trains_from');
			var y = document.getElementById('trains_to');
			var val2 = y.options[y.selectedIndex].value; 
			var val = x.options[x.selectedIndex].value;
			var uri = document.location.toString().split('?');
			
			params = uri[1].split('&');
			new_uri = '?';
			max = params.length;
			for(var i=0; i < max; i++ ){
				p = params[i].split("=");
				
				if(p[0]=='date') p[0]='';
				
				if( p[0] == 'selected_from'){
				  param_found = true;
				}
				
				if( p[0] == 'selected_to'){
				  p[1] = val2.toString();
				  param2_found = true;
				}
				
				if( p )
				if( p[0]!='undefined' && p[1]!='undefined' && p[0]!='' && p[1]!='' )
					new_uri = new_uri +'&'+ p[0]+'='+p[1];
			}
			if( !param_found ) new_uri = new_uri+'&selected_from='+val;
			if( !param2_found ) new_uri = new_uri+'&selected_to='+val2;
			document.location = new_uri;
		}
	);
	

	LoadGoogleMap();
	
	$('.Cal').css('display','none');
	$('#tomorrow').click(
		function(){
			$('.DateFilter > li').removeClass("selected");
			$(this).addClass("selected");
			$('#dateFilter').attr('value','tomorrow');
			$('#ChooseDate').html(choosDateTxt);
			if( CalIsOpened ){
				$('.Cal').fadeOut("fast");
				CalIsOpened = false;
			}
			refreshTimestamp = tomorrowStamp;
			jQuery.get('?c=setdate&stamp='+tomorrowStamp, tomorrowStamp, function(){}, 'text' );
			$('#TransportResults').html(AjaxLoaderImg);
			RefreshData();
			return false;
		}
	);
	$('#today').click(
		function(){
			$('.DateFilter > li').removeClass("selected");
			$(this).addClass("selected");
			$('#dateFilter').attr('value','today');
			$('#ChooseDate').html(choosDateTxt);
			if( CalIsOpened ){
				$('.Cal').fadeOut("fast");
				CalIsOpened = false;
			}
			refreshTimestamp = todayStamp;
			jQuery.get('?c=setdate&stamp='+todayStamp, todayStamp, function(){}, 'text' );
			$('#TransportResults').html(AjaxLoaderImg);
			RefreshData();
			return false;
		}
	);
	$('#ChooseDate').click(
		function(){
			$('.DateFilter > li').removeClass("selected");
			$(this).parent().addClass("selected");
			if( CalIsOpened == false){
				$('.Cal').css('display','block');
				$('.Cal').hide();
				$('.Cal').fadeIn("fast");
				CalIsOpened = true;
			}else{
				$('.Cal').fadeOut("fast");
				$('.Cal').hide();
				CalIsOpened = false;
			}
			return false;
		}
	);
	AddResultsClickable();
}
);


function LoadGoogleMap(){
	if( GOOG_IS_LODED==false){
		if( typeof(GOOG_API_URL) != 'undefined' ){
		var fileref=document.createElement('script');
			fileref.setAttribute("type","text/javascript");
			fileref.setAttribute("src", GOOG_API_URL);
			if (typeof fileref!="undefined") document.getElementsByTagName("head")[0].appendChild(fileref);
			GOOG_IS_LODED = true;
		}
	}
}


var ThenRemoveOpenedStop = '';

function AddResultsClickable(){

	$('a.Reminder').click(
		function(){
			var txt = $(this).parent().attr('title');
			var smsdata = txt.split('@');
			try{
					//OpenSendSmsForm defined in main.js
					OpenSendSmsForm(userPhone, smsdata[0], smsdata[1], module);
			}
			catch(e){
				alert('Atvainojamies, bet šobrīd SMS atgādinājumu nav iespējams nosūtīt!');
			}
			return false;
		}
	);

	HiddenRunOpened = false;

	$('#HidenRunBox').click(
		function(){
			if( HiddenRunOpened == false ){
				$('tr.DontRun').fadeIn('slow');
				HiddenRunOpened = true;
			}
			else{ 
				$('tr[class="Stops"]').fadeOut(200);
				$('tr.DontRun').fadeOut(200);
				setTimeout("document.getElementById('HidenRunBox').parentNode.style.display='';",301);
				HiddenRunOpened = false;
			}			
			return false;
		}
	);



	$('#TransportResults table tr').css('cursor','pointer');

	
	$("#TransportResults .Current").attr('alt2','Current');
	
	
	$('#TransportResults table tr').click(
		function (){
			if( !$(this).attr("alt") || ($(this).attr("alt")=='') ){
				
				$(this).addClass("Selected");
				document.getElementById($(this).attr("id")).onmouseover = function(){
					 this.className = "Selected MouseOver";
				}
				document.getElementById($(this).attr("id")).onmouseout = function(){
					this.className = "Selected";
				}
				
				
				$(this).attr('alt','opened');
				$(this).after( '<tr class="Stops"><td id="opened_'+$(this).attr("id")+'" colspan="9">'+AjaxLoaderImg2+'</td></tr>' );
				$("#AjaxLoader").hide();
				$("#AjaxLoader").slideDown("fast");
				LoadDataTo = 'opened_'+$(this).attr("id");
				jQuery.get('?c=getstops&run='+$(this).attr("id")+'&selected_from='+from_id+'&selected_to='+to_id, null, function(data, textStatus){ 				
					$('#'+LoadDataTo).html(data);
					$('.Stops #'+LoadDataTo+' .StopsList').hide();
					$('.Stops #'+LoadDataTo+' .StopsList').slideDown("slow");
					google.load("maps", "2", {"callback" : LoadTrafficMap});
				},'html');
			}else{
			
				//bit tricky adding Current class
				var onMouseOutClass = '';
				if( $(this).attr('alt2') == 'Current' ){
					onMouseOutClass = 'Current';
				}
			
				document.getElementById($(this).attr("id")).onmouseover = function(){
					 this.className = 'MouseOver';
				}
				document.getElementById($(this).attr("id")).onmouseout = function(){
					this.className = ''+onMouseOutClass;
				}
			
				$('#opened_'+$(this).attr("id")).fadeOut(400);
				ThenRemoveOpenedStop =  'opened_'+$(this).attr("id");
				setTimeout('x = document.getElementById(ThenRemoveOpenedStop);x.parentNode.removeChild(x)',400);
				$(this).attr('alt','');
			}
		}
	);
}


var directions;
var newMarkers = new Array();
var map;
var new_marker = new Array();
var zoom;
var lookin;
var htmlPietura = new Array();

function LoadTrafficMap(){

	//return;

	if( !$("#TrafficPanel").html() ){  
	  return;
	}
	  
	  val = $("#TrafficPanel").html();
	  cv = new Array()
	  cp = val.split(';');
	  max = cp.length;
	  
	  zoomLevel = cp[0];
	  
	  for(var i=1; i<=max; i++){
	  	if( typeof(cp[i]) != 'undefined' ){
	  		if( cp[i]!= ''){
	  			cv[cv.length] = cp[i];
	  		}
	  	}
	  }
	  
	  
	markerIcon = new GIcon();
	markerIcon.image = "/img/mappoint2.png";
	markerIcon.iconSize = new GSize(21, 25);
	markerIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
	markerIcon.shadowSize = new GSize(37, 25);
	markerIcon.iconAnchor = new GPoint(10, 25);
	markerIcon.infoWindowAnchor = new GPoint(19, 3);
	
	  
 	  map = new GMap2(document.getElementById("TrafficMap"));
 	  map.disableContinuousZoom();
      map.disableDoubleClickZoom(); 
      try{
      	map.setCenter(new GLatLng(cv[0]), 5);
      }
      catch(err){
      }
      directionsPanel = document.getElementById("TrafficPanel");
      directions = new GDirections(map, directionsPanel);
      directions.loadFromWaypoints(cv);
      
      GEvent.addListener(directions,"load", function(){
        setTimeout(function() {
          for (var i=0; i < directions.getNumRoutes()+1; i++) {
            marker = directions.getMarker(i);
            new_marker[i] = new GMarker( marker.getLatLng(), markerIcon);
            map.removeOverlay(marker);
            
            if( ( i == 0 ) || (i == directions.getNumRoutes() ) ){
            	map.addOverlay(new_marker[i]);
            }
          }
          eval('map.setZoom('+zoomLevel+')');
        },0);
      });
      
      
      $('#TrafficMap').append('<div class="AlertMap">Attēlotais maršruts kartē var neatbilst realitātei!</div>');
      
}


function changeImage(i){
	
	var blueIcon = new GIcon(G_DEFAULT_ICON);
 	blueIcon.iconSize = new GSize(21,24);
 	blueIcon.shadowSize = new GSize(36,23);
  	blueIcon.image = "/img/marker.png";
  	markerOptions = { icon:blueIcon };
  	
	var marker = directions.getMarker(i);
	var latlng = marker.getLatLng();
	marker = new GMarker(latlng, markerOptions);
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml('Test');
        });
    newMarkers[i] = marker;
}


var refreshTimestamp;

function RefreshData(){
	jQuery.get('?c=refresh_results&selected_from='+from_id+'&selected_to='+to_id+'&stamp='+refreshTimestamp, 'x', LoadRefreshedData,'html');
}

function LoadRefreshedData(data, textStatus){
	$('#TransportResults').hide();
	document.getElementById('TransportResults').innerHTML = data;
	$('#TransportResults').fadeIn("def");
	AddResultsClickable();
}


function LoadDateHTML(data, textStatus){
	$('#ChooseDate').html(data);
	$('#ChooseDate').parent().addClass("selected");
	$('.Cal').fadeOut("fast");
	CalIsOpened = false;
	$('#dateFilter').attr('value','date');
}

function SetCalDate(elem,timestamp){
	
	refreshTimestamp = timestamp;
	
	$('.Cal table tr td').removeClass("selected");
	elem.parentNode.className = "selected";
	if( todayStamp == timestamp){
		$('.DateFilter > li').removeClass("selected");
		$('#today').addClass("selected");
		$('#ChooseDate').html(choosDateTxt);
	}
	if( tomorrowStamp == timestamp){
		$('.DateFilter > li').removeClass("selected");
		$('#tomorrow').addClass("selected");
		$('#ChooseDate').html(choosDateTxt);
	}
	jQuery.get('?c=setdate&stamp='+timestamp, timestamp, LoadDateHTML, 'text' );
	$('#TransportResults').html(AjaxLoaderImg);
	RefreshData();
	return false;
}

function LoadCalendar(timestamp){
	jQuery.get( '?c=getcal&stamp='+timestamp, timestamp, LoadCalHTML, 'text' );
	return false;
}

function LoadCalHTML(data, textStatus){
	$('.Cal').html(data);
	$('.Cal').hide();
	$('.Cal').fadeIn("fast");
}




