var recording_cycle;

function process_now_sleep(length) {
    can_cycle_yet = false;
    //$('#processnow').addClass('gray-text').blur();
    $('#process_now').addClass('disabled');
    if (length) {
        setTimeout("can_cycle_yet = true;$('#process_now').removeClass('disabled');",length);
    }
}

function toggle_slide(target) {
    $('#accesswarn').slideToggle();
}

function process_now_wake() {
    can_cycle_yet = true;
    $('#process_now').removeClass('disabled');
    //$('#processnow').removeClass('gray-text').blur();
}

function set_countdown(length) {
    globaldate = new Date();
    globaldate.setTime(globaldate.getTime()+length);
    $('#countdown').countdown('change',{until: globaldate,compact:true,layout:'{hnn}:{mnn}:{snn}'});
    //$('#duration').text("Out of "+ (length/60000)+(((length/60000)<=1)?" minute":" minutes"));
}

function cycle() {
    pauseVideo();
    unPauseVideo();
   
    //var d = new Date();
    //d.setTime(d.getTime()+(time_between_videos*60000));
    //$('#next-cycle').html(d.toString());
    set_countdown(time_between_videos*60000);

    clearTimeout(recording_cycle);
    clearTimeout(firstCycle);
    recording_cycle = setTimeout("cycle();",time_between_videos*60000);
}

var last_preview_url = "";
var new_vid_update_cycle;
var stoppedAjax = false;
function update_new_vids(retry) {
    globaldate = new Date();
    var url = '/channel/'+chanid+'/is_updated/'+now_ts+'/?'+(globaldate.getTime());
    $.get(url,function (data) { 
            if (parseInt(data)>=3) {
                $('#watch_recordings div').html('<strong>Several</strong> videos finished highlighting this session.');
                stoppedAjax =  true;
                //clearInterval(new_vid_update_cycle);
                return;
            } else {
                $('#watch_recordings div').html('<strong>'+data+'</strong> video'+((parseInt(data)==1)?'':'s')+' finished highlighting this session.');
            }
        });
    var gif_url = '/channel/'+chanid+'/latest_preview_gif/?'+(globaldate.getTime());
    $.get(gif_url, function (data) {
        if ((data.indexOf('gif')!=-1) && (data != last_preview_url) && !stoppedAjax) {
            //$('#latest-preview').html('Preview of latest highlight:<br/><a href="/channel/'+chanid+'/" target="_blank"> <img border="0" src="'+data+'"/></a>');
            $('#latest_preview a img').attr('src',data);
            last_preview_url = data;
        }
        });
    retry();
}

var checkRecycleRequestsCycle;

function checkRecycleRequest() {
    globaldate = new Date();
    var url = '/channel/'+chanid+'/check_recycle/?'+(globaldate.getTime());
    $.get(url,function (data) { 
        if (data.indexOf('1')!=-1) {
            // recycling
            process_video_now();
        }
        checkRecycleRequestsCycle = setTimeout("checkRecycleRequest();",20000);
    });
}

var firstCycle;
var frommin = 60;
var tomin = 60;

function startedRecording() {
    $('.initial').fadeOut("normal",function() {
            $('.mainclient').fadeIn("normal");
            });
    $('#process_now').click(process_video_now);

    // CLEAR RECYCLE REQUEST
    var url = '/channel/'+chanid+'/check_recycle/?'+(globaldate.getTime());
    $.get(url,function (data) { });

    //$('#countdown').countdown({until: 0, format: 'MS'});
    $('#countdown').countdown({until: 0,compact:true,layout:'{hnn}:{mnn}:{snn}'});
    /*$('#instructions').fadeOut("slow",function() {
        $('#webcamad').fadeOut("normal");
        $('#control-buttons').fadeIn("slow");
        $('#actions').fadeIn("slow");});*/

    //motion_alerts_enabled = $('#motion_alerts_state').hasClass('on');

    $('#show_meter').attr('checked',true);
    
    $('#alert_sensitivity option[value='+$('#client').get(0).getMotionLevel()+']').attr('selected','selected');
    $('#alert_sensitivity').change(function () {
            document.getElementById('client').setMotionLevel(parseInt($('#alert_sensitivity option:selected').val()));
    });

    // handle toggle of motion alerts on/off
    $('#motion_alert_toggle_button').click(function(){  
    
        if($('#motion_alert_state').hasClass('on'))
        {      
            $('#motion_alert_state').removeClass('on').html('off').addClass('off');
            $(this).html('turn on');
            $('#motion-alerts-on').click(); //should turn off
	    if ($('#motion_alert_state').hasClass('triggered')) {
		    motion_alert_cleanup();
	    }
        }
        else
        {
            // this is temporary, just so we have a way to test the alert. this will
            // fire when we actually cross an activity threshold.
            //fire_alert();
            //
           
            $('#motion_alert_state').removeClass('off').html('on').addClass('on');
            $(this).html('turn off');
            // run callback to turn alerts on here
            $('#motion-alerts-on').attr('checked')
            $('body').effect('highlight', {color:'#4dc344'}, 3000);
        }
        return false;  
    });

   

    dormant_motion_alert = true;
    setTimeout("dormant_motion_alert = false;",4000);

    set_countdown(60000);

    firstCycle = setTimeout("pauseVideo();unPauseVideo();startCycle();",60000);

    //new_vid_update_cycle = setInterval("update_new_vids()",20000);
    $.smartPoller(10000,update_new_vids);

    $('select.time_limit').change(function () {
	frommin = (parseInt($('div#limit_from select.hour option:selected').val())+(($('div#limit_from select.ampm option:selected').val()=='pm')?12:0))*60 + parseInt($('div#limit_from select.minutes option:selected').val());
	tomin = (parseInt($('div#limit_to select.hour option:selected').val())+(($('div#limit_to select.ampm option:selected').val()=='pm')?12:0))*60 + parseInt($('div#limit_to select.minutes option:selected').val());
		    });
    
}


function startCycle() {
    checkRecycleRequestsCycle = setTimeout("checkRecycleRequest();",10000);

    set_countdown(time_between_videos*60000);

    recording_cycle = setTimeout("cycle();",time_between_videos*60000);
}

function pauseVideo() {
    document.getElementById('client').pause();
    globaldate = new Date();
    //$('#notification li').css('color','#757575');
    //$('#notification').prepend("<li style='color: #cc0000;'>Started processing another video segment at "+d.toString()+"</li>");
    datestr = globaldate.toLocaleDateString().substr(0,3)+" "+globaldate.toLocaleTimeString();
    $('#processed').html("Started highlighting latest recording at "+datestr);
   
}

function unPauseVideo() {
    dormant_motion_alert = true;
    setTimeout("dormant_motion_alert = false;",4000);
    document.getElementById('client').unpause();
}

function resetTimeLimit() {
	$('.hour').val(0);
	$('.minutes').val(0);
	$('.ampm').val('am');
}

function withinTimeLimit() {
	tempd = new Date();
	curmin = tempd.getHours()*60+tempd.getMinutes();
	if (curmin > 1440)
		curmin -= 1440;

	if (tomin == frommin)
		return true;
	else if (tomin > frommin) // if from before to
		return (curmin>=frommin) && (curmin<=tomin);
	else // if to before from
		return ((curmin>=frommin) && (curmin<=1440)) || ((curmin<=tomin) && (curmin>=0));
}


//var motion_alerts_enabled = false;
//var motion_alerts_triggered = false;
var motion_alert_occured = false;
var motion_alert_timeout;
var dormant_motion_alert = false;

function motion_alert(level) {
    if (!$('#motion_alert_state').hasClass('on') && !dormant_motion_alert) { // motion alerts are off, but we have exceeded threshold
        //$('#activity').css('background',"url('/site_media/ma-b.png') no-repeat");
        //setTimeout("$('#activity').css('background',\"url('/site_media/ma-g.png') no-repeat\");",4000);
        fire_alert("test");
        return false;
    }
    if (($('.time_limit').length!=0)&&(!withinTimeLimit())) {
	fire_alert("outside_limit");
	return false;
    }
	if (!$('#motion_alert_state').hasClass('triggered') && !dormant_motion_alert) { // motion alerts are on, but haven't been triggered, and we are not dormant
		// start motion alert mode
        $('#motion_alert_state').addClass('triggered');
        $('body').effect('highlight', {color:'#EE3B3B'}, 2000);
        setTimeout("$('body').effect('highlight', {color:'#EE3B3B'}, 2000);",2100);
        setTimeout("$('body').effect('highlight', {color:'#EE3B3B'}, 2000);",4200);
        setTimeout("$('body').addClass('alert_mode_background');",6100);

        // prevent the Process Now button from being operational
        can_cycle_yet = false;
        $('#process_now').addClass('disabled');

        clearTimeout(firstCycle); // makes sure that the initial cycle never occurs
        clearTimeout(recording_cycle); // makes sure the regular cycle stops

        motion_alert_occured = false;

        // start timeout cycle
        set_countdown(60000);
        motion_alert_timeout = setTimeout("motion_alert_cycle()",60000);
        //$('#activity').css('background',"url('/site_media/ma-r.png') no-repeat");
        fire_alert();
        globaldate = new Date();
        clog("Triggering motion alert: "+'/channel/'+chanid+'/motion_alert/?'+(globaldate.getTime()));
        $('#motion-alert-status').load('/channel/'+chanid+'/motion_alert/?'+(globaldate.getTime())); // this causes the motion alert email to be sent
        $.get('/channel/'+chanid+'/motion_alert/?'+(globaldate.getTime())); // this causes the motion alert email to be sent
	} else if (!dormant_motion_alert) { 
        motion_alert_occured = true; // we've started the mode, just need to note we triggered again
        //$('#activity').css('background',"url('/site_media/ma-r.png') no-repeat");
	}
}

function kill_alert_mode() {
    clearTimeout(motion_alert_timeout); 
    $('#motion_alert_state').removeClass('triggered');
    $('body').removeClass('alert_mode_background');
    can_cycle_yet = true;
    $('#process_now').removeClass('disabled');
}

function motion_alert_cleanup() {
	kill_alert_mode();
        //$('#activity').css('background',"url('/site_media/ma-g.png') no-repeat");
	pauseVideo();
	unPauseVideo();
        startCycle();
}

function motion_alert_cycle() {
    if (!motion_alert_occured) { // this means no motion alerts happened this minute
        motion_alert_cleanup();
        return;
    } else if (!dormant_motion_alert) { // a motion alert happened this minute, and we are not dormant 
        pauseVideo();
        unPauseVideo();
        dormant_motion_alert = true;
        setTimeout("dormant_motion_alert = false;",4000);
        set_countdown(60000);
        motion_alert_occured = false; 
        motion_alert_timeout = setTimeout("motion_alert_cycle()",60000); // run this again in 60secs
    }
}


var can_cycle_yet = true;
function process_video_now() {
    if (can_cycle_yet) {
        clearTimeout(firstCycle);
        clearTimeout(recording_cycle);
        if (!checkRecycleRequestsCycle)
            checkRecycleRequestsCycle = setTimeout("checkRecycleRequest();",5000);
        cycle();
        process_now_sleep(10000);

    }
}

function pauseButton() {
    pauseVideo();
    process_now_sleep();
    set_countdown(0);
    clearTimeout(recording_cycle);
    clearTimeout(firstCycle)

}

function unPauseButton() {
    unPauseVideo();
    set_countdown(time_between_videos*60000);
    recording_cycle = setTimeout("cycle();",time_between_videos*60000);
    process_now_wake();
}
