var seconds=0
var minutes=0
var hours=0
var counter
var seconds_OG=0
var minutes_OG=0
var hours_OG=0
var inprogress=false

function startbutton(){
    if (inprogress){
        stopcounter()
        inprogress=false
        document.control.cs.value="Start Timer"
    }
    else{
        startcounter()
        inprogress=true
        document.control.cs.value="Stop Timer"
    }
}

function resetbutton(){
    resetcounter()
}

function startcounter(){
    setcounter()
    counter=setInterval(countdown,1000)
}

function stopcounter(){
    clearInterval(counter)
}

function resetcounter(){
    seconds=seconds_OG
    minutes=minutes_OG
    hours=hours_OG
    display()
}

function setcounter(){
    seconds=document.clock.s.value-0
    minutes=document.clock.m.value-0
    hours=document.clock.h.value-0
    seconds_OG=seconds
    minutes_OG=minutes
    hours_OG=hours
}

function finishcounter(){
    stopcounter()
    alertuser()
    resetcounter()
    inprogress=false
    document.control.cs.value="Start Timer"
}

function countdown(){
    if (seconds+minutes+hours<=0){
        finishcounter()
        return
    }
    seconds-=1
    if (seconds<0){
        seconds=59
        minutes-=1
    }
    if (minutes<0){
        minutes=59
        hours-=1
    }
    if (seconds+minutes+hours<=0){
        finishcounter()
    }
    display()
}

function alertuser(){
    alert("Timer has finished!")
}

function display(){
    document.clock.h.value=format00(hours)
    document.clock.m.value=format00(minutes)
    document.clock.s.value=format00(seconds)
}

function format00(val){
    var newval
    if (val<=9){
        newval="0"+val
    }
    else {
        newval=val
    }
    return newval
}
