/*  
    View functionality and animation for the pollutant charts
  
    Requires the following variables from PHP:
    
        var baseurl = <?php echo base_url(); ?>;
        var hourdiff = <?php echo date('I'); ?>;
        var current = <?php echo $now; ?>;
        var maxtime = <?php echo $maxtime; ?>;
        var mintime = <?php echo $mintime; ?>;
        var webpath = '<?php echo $pm10webdir; ?>';
        var filename = '<?php echo $pm10filename; ?>';
        var show72h = false;
    
    (All times as Unix timestamp, the filename includes a '?' which
     will be substituted later with the date.)
      
    @author christian studer <christian.studer@meteotest.ch>
*/

var     animation = 0;
var     interval = 3600;
//reloadAfterImport();

// Reload page after next data import


// Language dependant texts
var lng_intervall   = new Array('Intervall', 'Intervalle');
var lng_animation   = new Array('Animation:', 'Animation:');
var lng_stunde      = new Array('Stunde', 'Heure');
var lng_tag         = new Array('Tag', 'Jour');


$(document).ready(function() {
    // Remove fallback button    
    $('#schadstoffwechsler').hide();
    $('#archivSchadstoffWechsler').hide();
    
    // Register Pollutant radio change events
    $(".pollutantRadio").click( function() {
        $("#pollutantChangeForm").submit();
    });
    $(".archivPollutantRadio").click( function() {
        $("#archivePollutantChangeForm").submit();
    });
    
    // Show maps in Dialog on start page
    if (show72h) {
        prepareMapDialog();
    }
    
    
	// Define language array offset
	langOffset = 0;
	q = $.parseQuery();
	if ( q.lang == 'fr') {
	    langOffset = 1;
	}
	
    // Add animation buttons
	$('#animationspan').html("<h3>"+lng_animation[0]+"</h3>"
            +"<p>"+lng_intervall[0]+":"
            +"<input type='radio' name='interval' id='interval_hour' value='3600' checked='checked'>"+lng_stunde[0]+" "
            +"<input type='radio' name='interval' id='interval_day' value='86400'>"+lng_tag[0]+"</p>"
            +"<p>"
            +"<input type='image' src='"+baseurl+"images/icons/control_play_blue_left.png' width='16' height='16' title='Animationrückwärts abspielen' id='playback'/>"
            +"&nbsp;"
            +"<input type='image' src='"+baseurl+"images/icons/control_pause.png' width='16' height='16' title='Animation Pause' id='playstop' />"
            +"&nbsp;"
            +"<input type='image' src='"+baseurl+"images/icons/control_play_blue.png' width='16' height='16' title='Animation vorwärts abspielen' id='playffw' />"
            +"</p>");
    $('#animationspan').show();
    	
   $('#playback').click(function() {
		play(-1);
		// turn to grey
		var src = $(this).attr("src");
		var src = src.replace("control_play_blue_left.png", "control_play_left.png");
		$(this).attr("src", src);
		// pause turn to blue
		var src = $('#playstop').attr("src");
		var src = src.replace("control_pause.png", "control_pause_blue.png");
		$('#playstop').attr("src", src);
		// play forward turn to grey
		var src = $('#playffw').attr("src");
		var src = src.replace("control_play_blue.png", "control_play.png");
		$('#playffw').attr("src", src);
        return false;
    });
    $('#playstop').attr('disabled', 'disabled').click(function() {
        play(0);
        var src = $('#playback').attr("src");
		var src = src.replace("control_play_left.png", "control_play_blue_left.png");
		$('#playback').attr("src", src);
		// pause turn to blue
		var src = $('#playstop').attr("src");
		var src = src.replace("control_pause_blue.png", "control_pause.png");
		$('#playstop').attr("src", src);
		// play forward turn to grey
		var src = $('#playffw').attr("src");
		var src = src.replace("control_play.png", "control_play_blue.png");
		$('#playffw').attr("src", src);
        return false;
    });
    $('#playffw').click(function() {
        play(1);
        var src = $(this).attr("src");
		var src = src.replace("control_play_blue.png", "control_play.png");
		$(this).attr("src", src);
		// pause turn to blue
		var src = $('#playstop').attr("src");
		var src = src.replace("control_pause.png", "control_pause_blue.png");
		$('#playstop').attr("src", src);
		// play forward turn to grey
		var src = $('#playback').attr("src");
		var src = src.replace("control_play_blue_left.png", "control_play_left.png");
		$('#playback').attr("src", src);
        return false;
    });
    
    // Prepare navigation buttons
    $('#hourback').click(function() {
        play(0);
        loadImage(-3600);
        return false;
    });
    $('#hourfw').click(function() {
        play(0);
        loadImage(3600);
        return false;
    });
    $('#dayback').click(function() {
        play(0);
        loadImage(-3600 * 24);
        return false;
    });
    $('#dayfw').click(function() {
        play(0);
        loadImage(3600 * 24);
        return false;
    });
    $('#monthback').click(function() {
        play(0);        
        loadImage(-3600 * 24 * monthJump(-1));
        return false;
    });
    $('#monthfw').click(function() {
        play(0);
        loadImage(3600 * 24 * monthJump(1));
        return false;
    });
    
    // Check for changes in the form fields
    $('#h').change(newCurrent);
	$('[name=interval]').change( function () {
		if ($('#interval_hour').attr('checked') == true) {
            interval = 3600;
        } else {
			interval = 86400;
		}
	});
    
    // Set up calendar    
    $('#datefield').datepicker({
        minDate: new Date(mintime * 1000),
        maxDate: new Date(maxtime * 1000),
        changeMonth: true,
        changeYear: true,
        duration: 'fast',
        hideIfNoPrevNext: true,
        onSelect: newCurrent,
        buttonImage: '/images/calendaricon.png',
        buttonImageOnly: true,
        buttonText: 'Kalender öffnen',
        showOn: 'both'
    });
    $('#datefield').blur( newCurrent ); // if changed without datepicker
    
    $('[name=pollutant_id]').change( function() {
        $('#pollutantChangeForm').submit();
    });
});


/**
 * Calculate next import time
 * @return Date
 */
function getNextImportTime() {
    var now = new Date();
    var ret = new Date();
    if (now.getMinutes() >= 25) {
	ret.setMinutes(25);
	ret.setTime(ret.getTime() + 3600000);
    } else {
	ret.setMinutes(25);
    }
    return ret;
}


// Calculate new current from form fields and call to load new image
function newCurrent() {
    var dateTextParts = $('#datefield').val().split('.');
    play(0);
    newDate = Date.UTC(dateTextParts[2], dateTextParts[1] - 1, dateTextParts[0], $('#h').val(), 0, 0);
	newDate = newDate - ((hourdiff + 1) * 3600000); // Localtime from UTC
	current = Math.round(newDate / 1000);
    loadImage(0);
}

// Change image, replace it with this offset
function loadImage(offset) {
    current += offset;
    if(current > maxtime) {
        $('#errormsg').show();
        play(0);
        current = maxtime;
    } else if(current < mintime) {    
        $('#errormsg').show();
        play(0);
        current = mintime;
    } else {
        $('#errormsg').hide();
    }            
    thisDate = new Date(current * 1000);     
           
    // JavaScript has NO formatting functions (I know of), so let's do this by hand...
    y = thisDate.getUTCFullYear();
    m = thisDate.getUTCMonth(); // Who came up with this idea?
    d = thisDate.getUTCDate();
    h = thisDate.getUTCHours();
    
    
    h = h + 1; // UTC -> MEZ
	h = h + hourdiff; // Daylight saving time
	if (h >= 24) {
		h = h - 24;
		d = parseInt(d, 10) + 1;
		m = parseInt(m, 10);
		daysOfMonth = new Date(y, m+1, 0).getDate();
		if (d > daysOfMonth) {
			d = 1;
			m++;
		    if (m >= 11) {
                y = y + 1;
                m = 0;
            }
		}
	}
	
	// Display month is 1 higher than what we use for dealing with date objects
	m++;
	
	// Assert leading zero and convert to string
    if(h < 10) {
        h = "0" + h.toString();
    } else {
        h = h.toString();
    }    
    if(d < 10) {
        d = "0" + d.toString();
    } else {
        d = d.toString();
    }
    if(m < 10) {
        m = "0" + m.toString();
    } else {
        m = m.toString();
    }
    y = y.toString();
    
    newDateString = y + m + d + "_" + h;
    newFilename = webpath + filename.replace(/\?/, newDateString);
    
    
    $.ajax({ 
        type: "GET", 
        url: newFilename, 
        success: function(msg){ 
            $('#Schadstoff-Karte').attr('src', newFilename); 
        }, 
        error: function(msg){
            $('#Schadstoff-Karte').attr('src', baseurl + 'images/maps/empty_map.png');
        }
    });
    
    
    $('#h').val(h);  
    $('#datefield').val(d+'.'+m+'.'+y);
}

// Playback function
function play(direction) {
    animation = direction; 
	
	$(document).stopTime();
	   
    switch(animation) {
        case -1:
            $('#playback').attr('disabled', 'disabled');
            $('#playstop').removeAttr('disabled');
            $('#playffw').removeAttr('disabled');
            $(document).everyTime('2s', function() { loadImage(-interval); });
            
            break;
        case 1:
            $('#playffw').attr('disabled', 'disabled');
            $('#playstop').removeAttr('disabled');
            $('#playback').removeAttr('disabled');
            $(document).everyTime('2s', function() { loadImage(interval); });
            
            break;
        default:
            $('#playstop').attr('disabled', 'disabled');
            $('#playffw').removeAttr('disabled');
            $('#playback').removeAttr('disabled');
            
            break;
    }
}

 
// Calculates a jump in days for a month forward or backwards
function monthJump(direction)
{
    var dateTextParts = $('#datefield').val().split('.');
    
	var days;
	var year = dateTextParts[2];
	var month = dateTextParts[1] - 1;
		
	switch(direction) {
		case -1:
			if(month == 0) {
				year--;
				month = 11;
			} else {
				month--;
			}
            days = 32 - new Date(year, month, 32).getDate();
            break;
        case 1:
        default:
            days = 32 - new Date(year, month, 32).getDate();
            break;
	}
   return days;
}

// Show maps in Dialog
function prepareMapDialog() {
    $('.stationArea').click(function() {
        $('#verlaufsgraph').attr('src', $(this).attr('rel'));
        $('#archivLink').attr('href', $(this).attr('href'));
        $('#verlauf_72h').dialog('open');
        $('#archivLink').attr('style', 'color:#CC0000;');
        $('#archivLink').blur();
        
        return false;
    });
    $("#verlauf_72h").dialog({
        autoOpen: false,
        maxWidth: false,
        width: 500,
        position: 'center'
    });
}


/**
 * Reload the window on next import time. That way we always have the current data.
 * @return void
 */
function reloadAfterImport() {
    var now = new Date();
    var nextImportTime = getNextImportTime();
    if (now.getMinutes() == nextImportTime.getMinutes()) {
	// This prevents the function from reloading nonstop at importTime.
	nextImportTime.setTime(nextImportTime.getTime() + 3600000);
    }
    var millies = nextImportTime.getTime() - now.getTime();
    window.setTimeout("location.reload(true)", millies);
    return;
}