var ImgCount = 0;
var ErrorCount = 0;
var NrOfImages =0;
var RadarImages = new Array();
var ErrorImages = new Array();
var ServerURL = 'http://www.landi.ch/meteo/img_meteo/radar/ArchiveFrames/';
var activeAnimation;
var startDateTime;
var endDateTime;

//Called to set the inital date & time, start is today & now - 1 hours and stop is today & now
function SetDefaultDates() 
{
    var today = new Date();
    var earlier = new Date(Date.parse(today) - 3600000 )
    document.getElementById('dateStop').value  = formatDate(today);
    document.getElementById('timeStop').value  = formatTime(today);
    document.getElementById('dateStart').value = formatDate(earlier);
    document.getElementById('timeStart').value = formatTime(earlier);
}

//Set up the gobal variable for the various radar images
function PrepareAnimation() 
{
    window.clearTimeout(activeAnimation);
  
    var dateStart = document.getElementById('dateStart').value;
    var timeStart = checkTimeFormat(document.getElementById('timeStart').value);
    var dateStop  = document.getElementById('dateStop').value;
    var timeStop  = checkTimeFormat(document.getElementById('timeStop').value); 
    
    document.getElementById('timeStart').value = timeStart;
    document.getElementById('timeStop').value = timeStop;
    
    if (validateDate(dateStart) && validateTime(timeStart)
     && validateDate(dateStop)  && validateTime(timeStop)) {
        
        startDateTime = createDate(dateStart, timeStart);
        endDateTime   = createDate(dateStop, timeStop);
        if (startDateTime > new Date()) {
            //start date is in the future
            startDateTime = new Date();
        }
        if (endDateTime > new Date()) {
            //stop date is in the future
            endDateTime = new Date();
        }
        
        if (startDateTime > endDateTime) {
            startDateTime = endDateTime;
        }
        
        //round on 10 minutes elements
        startDateTime = roundDate(startDateTime);
        endDateTime   = roundDate(endDateTime);
       
        document.getElementById('dateStop').value  =  formatDate(endDateTime);
        document.getElementById('timeStop').value  =  formatTime(endDateTime);
        document.getElementById('dateStart').value =  formatDate(startDateTime);
        document.getElementById('timeStart').value =  formatTime(startDateTime);
       
        loadImages(startDateTime, endDateTime)
    }
}
 

 
//Load the various image into the RadaImages array (global variable)
function loadImages(fromTime, toTime)
{
    document.images["radar"].src = "http://www.landi.ch//img/loading.gif"   
    var startTicks = Date.parse(fromTime);
    var endTicks = Date.parse(toTime);
    NrOfImages = (endTicks - startTicks) / 600000

    ImgCount = 0
    ErrorCount = 0
    RadarImages = new Array();
    ErrorImages = new Array();
    y =0
    for (i = startTicks; i < endTicks + 1; i = i + 600000 ) {
        var testDate = new Date(i);      
        var img  = new Image;
        img.onload  = imageLoaded;
        img.onerror = imageError;
        img.src = createURLFromDate(testDate);
        RadarImages[y] = img;
        y++
    }   
}

//Round the time component to the tens of minutes ie. 15:13 => 15:10
function roundDate(date)
{
    var min = date.getMinutes();
    min = min-(min%10);
    date.setMinutes(min);
    return date;
}

function createURLFromDate(date)
{
    var tmpdate=  date.getFullYear();
    tmpdate +=  formatNr(date.getMonth() + 1);
    tmpdate +=  formatNr(date.getDate());

    var Url = ServerURL;
    Url += "" + tmpdate + "/radar__" + tmpdate + "_";
    Url +=  formatNr(date.getHours()); 
    Url +=  formatNr(date.getMinutes()); 
    Url += '.gif';
    return Url;

}

//Extract the date from the URL
function createDateFromURL(url)
{
    var imagename = url.substring(url.lastIndexOf("/radar__") + 1, url.length)
    var year = imagename.substr(7,4);
    var month = imagename.substr(11,2);
    var date= imagename.substr(13,2);
    var hour = imagename.substr(16,2);
    var minutes = imagename.substr(18,2);
    return date + '.' + month + '.' + year + ' ' + hour + ':' + minutes;
}

//Check that the date is entered as dd.mm.yyyy or dd.mm.yy
function validateDate(field) 
{
    var RegExPattern = /([0-3][0-9]|[1-9])\.([1][0-2]|[1-9]|[0][1-9])\.\d{2,4}/;
    if ((field.match(RegExPattern)) && (field!='')) {
        document.getElementById('dateError').style.display = "none";
        return true;
    } else {
        document.getElementById('dateError').style.display = "block";
        field.focus();
        return false;
    } 
}

//Chech that the time is entered as hh:mm
function validateTime(field) 
{
    var RegExPattern = /([0-2][0-9]|[0-9])\:([0-5][0-9]|[1-9])/;
    if ((field.match(RegExPattern)) && (field!='')) {
       document.getElementById('timeError').style.display = "none";
       return true;
    } else {
       document.getElementById('timeError').style.display = "block";
       field.focus();
       return false;
    } 
}

//Return a date composed of the date and the time component
function createDate(dateString, timeString)
{    
    var dateArray =     dateString.split(".")
    var timeArray =     timeString.split(":")
    
    if (dateArray[2].length == 2) {
       // if year come on two digit then say it's year 20XX
	   dateArray[2] = '20' + dateArray[2];
    }         
    
    var dateTime = new Date(parseInt(dateArray[2])
                           ,dateArray[1]-1
                           ,dateArray[0]
                           ,timeArray[0]
                           ,timeArray[1]
                           ,0
                           ,0
                           );
	
    return dateTime;
}



function imageLoaded()
{
    ImgCount++; 
    if (ImgCount + ErrorCount   > NrOfImages){
        RadarAnimation(0);
    }
}

function imageError()
{
    ErrorImages[ErrorCount] = this.src;
    ErrorCount++; 
    if (ImgCount + ErrorCount  > NrOfImages) {
        RadarAnimation(0);
    }
}

function RadarAnimation(i)
{
    var dontShow = false;
    document.getElementById('noData').style.display = "none";	
    if (ImgCount - ErrorCount < 3) {
        if (ServerURL != 'http://www.landi.ch/meteodata/radar/') {
            ServerURL =  'http://www.landi.ch/meteodata/radar/'
            loadImages(startDateTime, endDateTime);
            return;
        } else {
            document.getElementById('noData').style.display = "block";
        }
    }
    if (i < RadarImages.length ) {
        for (n=0; n < ErrorImages.length; n++) { 
            if (RadarImages[i].src  == ErrorImages[n]) {
                dontShow = true;
            }
        }
        if (!dontShow) {
            //Uncomment this and the corresponding HTML code in order to dispaly the date of the image
            //document.getElementById("date").innerHTML = createDateFromURL(RadarImages[i].src);
            document.images["radar"].src = RadarImages[i].src;
        }
        i++;
        /*Loop such as it's a never ending animation*/
        if (i == RadarImages.length) {
            i = 0;
        }
        activeAnimation = window.setTimeout("RadarAnimation(" + i + ")" , 700);
   }
}

function formatNr(nr)
{
    nr = '0' + nr;
    if (nr.length > 2 ) {
        nr = nr.substring(1,3);
    }
    return nr;
}

//Print a date in the format dd.mm.yyyy
function formatDate(date)
{
    return  date.getDate() +  "." + (date.getMonth() +1) + "." +  date.getFullYear();
}

//Print a time in the format hh24:mi
function formatTime(date)
{
    return date.getHours() + ":" +  formatNr(date.getMinutes());
}


function checkTimeFormat(time)
{	
    time = time.replace(/\./,':');
	if (time.length == 3 && time.indexOf(":") < 0 ) {			
        time = time.substr(0, 1) + ":" + time.substr(1, 2);	
	}
	if (time.length == 4 && time.indexOf(":") < 0 ) {
		time = time.substr(0, 2) + ":" + time.substr(2, 2);		
	}
	return time
}

/*Only for debugging*/
function writeConsole(content)
{
    top.consoleRef=window.open('','myconsole',
                                  'width=350,height=250'
                                 +',menubar=0'
                                 +',toolbar=1'
                                 +',status=0'
                                 +',scrollbars=1'
                                 +',resizable=1');
    top.consoleRef.document.writeln(
                                  '<html><head><title>Console</title></head>'
                                 +'<body bgcolor=white onLoad="self.focus()">'
                                 +content
                                 +'</body></html>');
    top.consoleRef.document.close();
}
