// indicates wether or not a screencast was recorded
var screencastRecorded = false;
var screencastUploaded = false;
var isRecording = false;
var timerWaiting = null;
var timerRecording = null;
var timerFlashing = null;
var seconds = 0;
var recordStartTime;
var requirementsErrorsList = "";
var orginalDocumentTitle = document.title;
var isDocumentFocused = true;
var pageLoadedTimestamp = new Date().getTime();
var startAppletTime = 0;
var recordAudio = false;
var timerFlashWarn = null;
var timerFlashError = null;
var timerJavaWarn = null;
var timerJavaError = null;
var g_afterUploadCallback;

$(document).ready(function() {
    var loadedTime = (new Date().getTime() - pageLoadedTimestamp)/1000.0;
    logger.info('The homepage was loaded in '+loadedTime.toFixed(2)+' seconds');

    // set a default text to the tweet textarea
    setDefaultText('tweetStatus','Watch my screen recording on #screenjelly');
    setDefaultText('shareEmailNote','Watch my screen recording on Screenjelly');

    // refresh the count of characters
    //updateCounter('tweetStatusRemaining',$('#tweetStatus'),108);
    addCounterField('tweetStatusRemaining','tweetStatus',108,'tweet-button');

    // add events handlers
    $(document).focus(onHomeFocus);
    $(document).blur(onHomeBlur);

    // add plugin detection
    PluginDetect.onDetectionDone('Java', onJavaDetection, '/jar/getJavaInfo.jar');
    PluginDetect.onDetectionDone('Flash', onFlashDetection);
    
    // if flash is not yet loaded
    if (!window.api) {
	    // add logs when flash is slow
	    timerFlashWarn = setTimeout(flashWarnSlow,15000);
	    timerFlashError = setTimeout(flashErrorSlow,30000);
	}

    // hide starts in 5 seconds in safari mac
    if (isSafariMac()) {
        $('.hide-safari').hide();
    }
});

window.displayRequirements = function() {
    if(requirementsErrorsList !== '') {
        $('#requirements-warning').show();
        // show recording panel
        if(requirementsErrorsList.indexOf('Java') != -1) {
            $('#java-not-installed').show();
        }
        if(requirementsErrorsList.indexOf('Flash') != -1) {
            $('#flash-not-installed').show();
        }
        $('#video-recorder #requirements-warning').show();
    }
};

window.onHomeFocus = function() {
    isDocumentFocused = true;

    // destroy timer
    if (timerFlashing !== null) {
        clearInterval(timerFlashing);
        timerFlashing = null;

        // restore original document title
        document.title = orginalDocumentTitle;
    }
};

window.onHomeBlur = function() {
    isDocumentFocused = false;
};

// when the user tries to quit the page
window.onbeforeunload = function(event) {
    if ((screencastRecorded && !screencastUploaded) || isRecording) {
        var e = e || window.event;

        var question = '';
        if (isRecording) {
            question = 'You are recording your screen. Your recording will be lost if you continue.';
        } else {
            question = 'If you continue, you will lose your recording.';
        }

        // For IE and Firefox
        if (e) {
              e.returnValue = question;
        }

        // For Safari
        return question;
    }
};

/****************************************************************************
 * Java & Flash detection stuff
 *****************************************************************************/

window.onFlashDetection = function(resultPluginDetect) {
    var flashVersion = resultPluginDetect.getVersion('Flash');
    var versionCheck = resultPluginDetect.isMinVersion('Flash','9,0,115');

    if (!flashVersion && versionCheck!==0) {
        onFlashNotInstalled();
        logger.warn('Plugin detection: flash is not installed, '+navigator.userAgent);
    } else if (versionCheck!=1 && versionCheck!==0) {
        onFlashTooOld();
        logger.warn('Plugin detection: flash version is too old, '+navigator.userAgent);
    } else {
        // Flash is loaded
    }

    // display requirements if needed
    displayRequirements();
};

window.onFlashNotInstalled = function() {
    requirementsErrorsList = requirementsErrorsList + 'onFlashNotInstalled';
};

window.onFlashTooOld = function() {
    requirementsErrorsList = requirementsErrorsList + 'onFlashTooOld';
};

window.onJavaDetection = function(resultPluginDetect) {
    var javaVersion = resultPluginDetect.getVersion('Java');
    var versionCheck = resultPluginDetect.isMinVersion('Java','1,5');

    if (versionCheck == -0.2) {
        onJavaDisabled();
        logger.warn('Plugin detection: java is not enable, '+navigator.userAgent);
    } else if (!javaVersion && versionCheck!==0) {
        onJavaNotInstalled();
        logger.warn('Plugin detection: java is not installed, '+navigator.userAgent);
    } else if (versionCheck!=1 && versionCheck!==0) {
        onJavaTooOld();
        logger.warn('Plugin detection: java version is too old, '+navigator.userAgent);
    } else {
        // Java is here
    }

    // display requirements if needed
    displayRequirements();
};

window.onJavaNotInstalled = function() {
    requirementsErrorsList = requirementsErrorsList + 'onJavaNotInstalled';
};

window.onJavaTooOld = function() {
    requirementsErrorsList = requirementsErrorsList + 'onJavaTooOld';
};

window.onJavaDisabled = function() {
    requirementsErrorsList = requirementsErrorsList + 'onJavaDisabled';
};

window.onJavaCertificateError = function() {
	// show original title
	document.title = orginalDocumentTitle;
	
    // show recording panel
    $('#video-recorder').children().hide();
    $('#video-recorder #certificate-error').show();
};

window.flashWarnSlow = function() {
	logger.warn('flash didn\'t load after 15 seconds');
};

window.flashErrorSlow = function() {
	logger.error('flash didn\'t load after 30 seconds');
};

window.javaWarnSlow = function() {
	logger.warn('java didn\'t load after 15 seconds');
};

window.javaErrorSlow = function() {
	logger.error('java didn\'t load after 30 seconds');
};

/****************************************************************************
 * User click functions
 *****************************************************************************/

window.onClickRecordAgain = function() {
    setTimeout(onRecordAgain,0);
};

window.onRecordAgain = function() {
    sendEvent('RECORD_AGAIN');
    window.location.href = g_homeUrl;
};

window.clickIgnoreRequirementsWarning = function() {
    // TODO : save that in cookie to avoid to show the warning again ?
    $('#video-recorder #requirements-warning').hide();
    requirementsErrorsList = '';
    clickStartRecorder();
};

//When the user clicks on record
window.onClickStartRecorder = function() {
    if (!window.api) {
        return;
    }

    try {
        // load the recorder
        api.loadRecorder();
    } catch (err) {
        showNotificationBar('error','An error occured when trying to load the recorder');
            throw err;
    }

    // prepare seconds remaining
    seconds = 5;
    $('#countdown-number').html(seconds);

    // change title
    document.title = 'Loading...';

    // show loading
    $('#video-recorder').children().hide();
    $('#video-recorder #loading').show();

    sendEvent('RECORD_VIDEO',null,'IncludeAudio='+recordAudio);
};

//When the user clicks on "cancel recording"
window.onClickCancelStartRecording = function() {
    // show recording panel
    $('#video-recorder').children().hide();
    $('#video-recorder #start').show();

    // destroy timer
    if (timerWaiting !== null) {
        clearInterval(timerWaiting);
        timerWaiting = null;
    }

    // send an event
    sendEvent('RECORD_CANCEL');

    // change window title
    document.title = orginalDocumentTitle;
};


// When the user clicks on "stop recording"
window.onClickStopRecording = function() {
     try {
         api.stopRecording();
     } catch(err) {
         showNotificationBar('error','An error occured when trying to stop recording.');
         throw err;
     }
};

window.uploadAction = function(action, afterUploadCallback) {
    // set the action to do at the end
    g_afterUploadCallback = afterUploadCallback;
    if (!isRecording) {
        // check video
        if (screencastRecorded) {
            // set the action to do at the end
            //g_afterUploadCallback = afterUploadCallback;
            
            if(action == 'tweet') {
                openTwitterLoginIfNeeded(startUpload);
            } else if(action == 'post_to_facebook') {
                openFacebookLoginIfNeeded(startUpload);
            } else {
                openLoginIfNeeded('sign-in', startUpload);
            }
        } else {
            showNotificationBar('error','You have to create a recording first...');
        }
    } else {
        showNotificationBar('error','Please finish your recording first...');
    }
};

window.startUpload= function (success, data) {
    if (success) {
        if (!screencastUploaded) {
            // logged in, then start upload
            try {
                $('#uploadSharePrivate').attr('disabled', true);
                // upload the video
                api.upload($.cookie('PHPSESSID'));
            } catch(err) {
                showNotificationBar('error','An error occured when trying to upload the video.');
                    throw err;
            }
        } else {
            g_afterUploadCallback($('#videoBid').val());
        }
    }
};

window.onClickUploadAndShare = function() {
    $('#uploadShareDefError').html('');
    uploadAction('share', updateUploadedVideoInformations);
};

window.onClickUploadAndPostToFacebook = function() {
    $('#uploadFacebookDefError').html('');
    uploadAction('post_to_facebook', facebookPostVideo);
};

//When the user clicks on "tweet" but replying to somebody
window.onClickReplyVideo = function() {
    // remove errors
    $('#tweetStatusError').html('');
    // check form
    var status = $('#tweetStatus').val();
    if (status.length === 0) {
        $('#tweetStatusError').html('can\'t be empty');
        return false;
    }
    uploadAction('reply_tweet', replyTwitterStatus);
};

//When the user clicks on "tweet"
window.onClickTweetVideo = function() {
    // remove errors
    $('#tweetStatusError').html('');

    // check form
    var status = $('#tweetStatus').val();
    if (status.length === 0) {
        $('#tweetStatusError').html('can\'t be empty');
        return false;
    }

    if ($('#tweetStatus').val().length > 108) {
        return false;
    }
    uploadAction('tweet', updateTwitterStatus);
};

//When the user clicks on "send mail"
window.onClickMailVideo = function() {
    // remove errors
    $('#email-tab .error').html('');

    // check form
    var errors = false;
    var from = $('#shareEmailFrom').val();
    var to = $('#shareEmailTo').val();
    var note = $('#shareEmailNote').val();

    if (from.length === 0) {
        $('#shareEmailFromError').html('Required');
        errors = true;
    }

    if (to.length === 0) {
        $('#shareEmailToError').html('Required');
        errors = true;
    }
    uploadAction('email', sendMail);
};

window.onClickGetRecentVideos = function(pageNumber) {
    // call videoService to get page of videos
    ajaxCall({
             type: 'GET',
             async: true,
             url: g_getRecentVideosUrl,
             data: {
                 pageNum: pageNumber
             },
             cache: false,
             onSuccess: function(data){
                updateVideoList(data);
             },
             onError: function (code, error) {
             }
        });
};

window.onClickChangeAudioInput = function() {
    try {
        var selection = $('#audioInputs option:selected').html();
        if (selection == "Don't record audio") {
            api.setRecordAudio(false);
            recordAudio = false;
        } else {
            api.setRecordAudio(true);
            api.setAudioInput(selection);
            recordAudio = true;
        }
    } catch(err) {
        showNotificationBar('error','An error occured when trying to change the audio input.');
            throw err;
        }
};

window.updateVideoList = function(data) {
    // Rebuild video list with data
    // Remove previous divs and links
    $("div[@class='videos-flow']").children().remove();
    $("a[@class='video-pagination-link']").remove();
    if($("div[@class='hidden-arrow']").length >0) {
        $("div[@class='hidden-arrow']").remove();
    }
    // Previous page link
    if(data.pageNum != data.previousPage) {
        // Add link
        var previousArrow = "<a class='video-pagination-link' href='javascript:' onclick='onClickGetRecentVideos(" + data.previousPage +");'><div class='left-arrow'> </div></a>";
        $("div[@class='videos-flow']").before(previousArrow);
    } else {
        $("div[@class='videos-flow']").before("<div class=\"hidden-arrow\"> </div>");
    }
    // Add videos
    $.each(data.videos, function(i,video) {
        if (data.videos.length > 0) {
            var bubbleStr = "";
            if (video.status_message != null && video.status_message != '') {
                bubbleStr = "<div class=\'description hidden\' id=\'video-bid-desc-" + video.video_bid + "\'>" + "<span class=\'green-text\'>" + video.display_name + "</span>:<div class='description' id='status_message_"+ video.video_bid +"'></div></div>";
            } else {
                bubbleStr = "<div class=\'hidden\' id=\'video-bid-desc-" + video.video_bid + "\'>" + "<span class=\'italic-text\'>Posted by <span class=\'green-text\'>" + video.display_name + "</span></span></div>";
            }
            $("div[@class='videos-flow']").append(bubbleStr);
            $("#status_message_" + video.video_bid).text(' '+video.status_message).html();
            var videoStr = "<div class=\'panel-white video\'>"
            +"<div class=\'white-background\'/>"
            +"<div class=\'white-top-left png\'></div>"
            +"<div class=\'white-top\'></div>"
            +"<div class=\'white-top-right png\'> </div>"
            +"<div class=\'white-left\'> </div>"
            +"<div class=\'white-right\'> </div>"
            +"<div class=\'white-bottom-left png\'> </div>"
            +"<div class=\'white-bottom\'> </div>"
            +"<div class=\'white-bottom-right png\'> </div>"
            +"<div class=\'white-middle\'>"
            +"<div class=\'white-content\'>"
            +"<div id=\'video-bid-desc-" + video.video_bid + "\' class=\'hidden\'/>"
            +"<a href=\'/watch/" + video.video_bid +"\'>"
            +"<img alt=\"Video recording\" src=\'" + video.base_url +"/" + video.video_bid +"/thumbnail.jpg\' onmouseout=\'hideTooltip();\' onmouseover=\"showTooltip(\'video-bid-desc-" + video.video_bid +"\',this);\"/>"
            +"</a>"
            +"<span class=\'hidden\'/>"
            +"<div class=\'clearfix\'/></div>"
            +"</div>"
            +"</div>";
            $("div[@class='videos-flow']").append(videoStr);
        } else {
            $("div[@class='videos-flow']").append('nothing');
        }
    });
    // Next page link
    if(data.pageNum != data.lastPage) {
        // Add link
        //$("#last-videos-panel").$("div[@class='bgreen-middle']").hide();
        var nextArrow = "<a class='video-pagination-link' href='javascript:' onclick='onClickGetRecentVideos(" + data.nextPage +");'><div class='right-arrow'> </div></a>";
        $("div[@class='videos-flow']").after(nextArrow);
    } else {
        $("div[@class='videos-flow']").after("<div class=\"hidden-arrow\"> </div>");
    }
};

/****************************************************************************
 * Actions
 *****************************************************************************/

// redirect to the video page when the upload is finished
window.updateUploadedVideoInformations = function(videoBid) {
    $.cookie('last_recorded_video_bid', videoBid);
    // change the publish status if needed
    var published = !($('#uploadSharePrivate').is(':checked'));   
    screenjelly.saveVideo(videoBid, $('#upload-description').val(), published,
        // Success callback
        function(data){
           window.location = g_displayVideoUrl+videoBid+'?showTab=share';
        },
        // Error callback
        function (code, error) {
           // enable back buttons
           enableButton('tweet-button');
           enableButton('send-email-button');
           enableButton('upload-share-button');
        }
    );    
};

window.facebookPostVideo = function(videoBid) {
    $.cookie('last_recorded_video_bid', videoBid);
    // change the publish status if needed
    var published = !($('#uploadSharePrivate').is(':checked'));   
    FB.Connect.showPermissionDialog("publish_stream", function(x){
        screenjelly.facebookPostVideo(videoBid, 'Watch my recording on Screenjelly!', $('#facebook-description').val(), published,
            // Success callback
            function(data){
               window.location = g_displayVideoUrl+videoBid+'?showTab=facebook';
            },
            // Error callback
            function (code, error) {
               // enable back buttons
               enableButton('facebook-button');
               enableButton('tweet-button');
               enableButton('send-email-button');
               enableButton('upload-share-button');
            },
            false
        );   
    });
};


//update the twitter status for a reply
window.replyTwitterStatus = function(videoBid) {
    // get the published state
    var published = !($('#uploadSharePrivate').is(':checked'));
    // update the user status
    ajaxCall({
        type: 'GET',
        url: g_twitterReplyUrl,
        data: {
            status: $('#tweetStatus').val(),
            videoBid: videoBid,
            published: published,
            replyVideoBid: $('#replyVideoBid').val()
        },
        cache: false,
        showSuccess: false,
        onSuccess: function(data){
            window.location = data.videoUrl;
        },
        onError: function (code, error) {
            // enable back buttons
            enableButton('tweet-button');
            enableButton('send-email-button');
            enableButton('upload-share-button');

            // show preview panel
            $('#video-recorder').children().hide();
            $('#video-recorder #preview').show();
        }
     });
};

/**
 * Update the twitter status
**/
window.updateTwitterStatus = function(videoBid) {
    var published = !($('#uploadSharePrivate').is(':checked'));
    // Description <- Status
    screenjelly.tweetVideo(videoBid, $('#tweetStatus').val(), $('#tweetStatus').val(), published, 
        function(data){
            window.location = data.videoUrl;
        },
        function (code, error) {
            // enable back buttons
            enableButton('tweet-button');
            enableButton('send-email-button');
            enableButton('upload-share-button');

            // show preview panel
            $('#video-recorder').children().hide();
            $('#video-recorder #preview').show();
        },
        false
    );
};

/**
* Send email
**/
window.sendMail = function(videoBid) {
    var published = !($('#uploadSharePrivate').is(':checked'));
    screenjelly.emailVideo(videoBid, $('#shareEmailFrom').val(), $('#shareEmailTo').val(), 
                                $('#shareEmailNote').val(), published, 
                                function(data){
                                    window.location = data.videoUrl;
                                    // add the success message in a cookie that will be displayed later
                                    if (response.successMessage) {
                                        $.cookie('successMessage',response.successMessage,{path: '/'});
                                    }
                                },
                                function (code, error) {
                                    // enable back buttons
                                    enableButton('tweet-button');
                                    enableButton('send-email-button');
                                    enableButton('upload-share-button');
                        
                                    // show preview panel
                                    $('#video-recorder').children().hide();
                                    $('#video-recorder #preview').show();
                                }, false);
};

/****************************************************************************
 * API functions
 *****************************************************************************/

//When SWF is ready, load recorder
window.onApiReady = function(audioSettings) {
    api = document.getElementById('apiObject');

    // remove timers
    clearTimeout(timerFlashWarn);
    clearTimeout(timerFlashError);
    
    // calculate load time
    var loadedTime = (new Date().getTime() - pageLoadedTimestamp)/1000.0;
    logger.info('The flash recorder was loaded in '+loadedTime.toFixed(2)+' seconds');

    if (!audioSettings.hasMicrophone) {
        $('#audioInputs').append('<option selected="selected">No microphone detected</option>');
    } else {
        $('#audioInputs').html('');
        if (audioSettings.recordAudio) {
            $('#audioInputs').append('<option>Don\'t record audio</option>');
            recordAudio = true;
        } else {
            $('#audioInputs').append('<option selected="selected">Don\'t record audio</option>');
        }
        $('#audioInputs').removeAttr('disabled');
    }

    jQuery.each(audioSettings.audioInputs, function() {
        if (audioSettings.recordAudio && this == audioSettings.audioInput) {
            $('#audioInputs').append('<option selected="selected">'+this+'</option>');
        } else {
            $('#audioInputs').append('<option>'+this+'</option>');
        }
    });
};

window.onAppletAdded = function() {
    // get the timestamp for stats
    startAppletTime = new Date().getTime();
    
    timerJavaWarn = setTimeout(javaWarnSlow,15000);
    timerJavaError = setTimeout(javaErrorSlow,30000);
};

window.onAppletReady = function(port) {
    // save java port
    httpPort = port;
    
    // remove timers
    clearTimeout(timerJavaWarn);
    clearTimeout(timerJavaError);
    
    // log the time that it took to load
    var loadedTime = (new Date().getTime() - startAppletTime)/1000.0;
    logger.info('The java recorder was loaded in '+loadedTime.toFixed(2)+' seconds');
};

//When recorder is ready, start the countdown
window.onRecorderReady = function() {
    // if safari on mac then skip the countdown
    if (isSafariMac()) {
        // start the recoding
        try {
            api.startRecording();
        } catch(err) {
            showNotificationBar('error','An error occured when trying to start the recording.');
                throw err;
        }

    } else {
        // Cancelled ?
        if(seconds >= 0) {
            // prepare seconds remaining
            seconds = 5;
            $('#countdown-number').html(seconds);

            // change window title
            document.title = 'Starts in '+seconds+'s';

            // show countdown
            $('#video-recorder').children().hide();
            $('#video-recorder #countdown').show();

            timerWaiting = setInterval(onTimerWaiting, 1000);
        }
    }
    
    // Preload player
    $('#preview').html('<object type="application/x-shockwave-flash" data="'+g_playerBaseUrl+'/swf/SJPlayer.swf" width="1" height="1">'
            +'<param name="movie" value="'+g_playerBaseUrl+'/swf/SJPlayer.swf"/><param name="allowscriptaccess" value="always"/><param name="allowfullscreen" value="true"/>'
            +'<param name="wmode" value="opaque"/><param name="flashvars" value="preload=true"/>'
            +'</object>');
};

//When recording starts
window.onRecordingStart = function() {
    screencastUploaded = false;
    isRecording = true;

    // show recording panel
    $('#video-recorder').children().hide();
    $('#video-recorder #recording').show();

    // Recording start Time
    var d = new Date();
    recordStartTime = d.getTime();

    // destroy timer
    if (timerRecording != null) {
        clearInterval(timerRecording);
        timerRecording = null;
    }

    // launch timer
    onTimerRecording();
    timerRecording = setInterval(onTimerRecording, 1000);
};

//When recording stops
window.onRecordingStop = function(duration, fileSize, hasAudio) {
    $('#video-recorder').children().hide();
    $('#preview').show();

    screencastRecorded = true;
    isRecording = false;

    // add player
    var httpPort = 0;
    try {
        httpPort = api.getHttpPort();
    } catch (err) {
        showNotificationBar('error','An error occured when trying to add the player');
            throw err;
    }

    // Erase previous player
    $('#preview').html('<object type="application/x-shockwave-flash" data="'+g_playerBaseUrl+'/swf/SJPlayer.swf" width="577" height="403">'
            +'<param name="movie" value="'+g_playerBaseUrl+'/swf/SJPlayer.swf"/><param name="allowscriptaccess" value="always"/><param name="allowfullscreen" value="true"/>'
            +'<param name="wmode" value="opaque"/><param name="flashvars" value="redoCallback=onClickRecordAgain&localHttpPort='+httpPort+'&videoDuration='+duration+'&hasAudio='+hasAudio+'"/>'
            +'</object>');

    // change window title
    document.title = orginalDocumentTitle;

    if (!isDocumentFocused) {
        timerFlashing = setInterval("onTimerFlashTitle('Recording finished')", 1000);
    }

    // destroy timer
    if (timerRecording != null) {
        clearInterval(timerRecording);
        timerRecording = null;
    }

    $('#preview').show();
};

window.onUploadStart = function() {
    // disable buttons
    disableButton('tweet-button');
    disableButton('send-email-button');
    disableButton('upload-share-button');

    // show recording panel
    $('#video-recorder').children().hide();
    $('#video-recorder #uploading').show();

    $('#uploadPercentage').html('0%');
};


window.onUploadProgress = function(current,total) {
    var percentage = parseInt( (total == 0) ? 0 : current*100/total );
    $('#uploadPercentage').html(percentage+'%');
};


window.onUploadSuccess = function(videoBid) {
    screencastUploaded = true;
    $('#uploadPercentage').html('100%');
    $('#videoBid').val(videoBid);

    g_afterUploadCallback(videoBid);
};


window.onUploadError = function(data) {
    // show preview panel
    $('#video-recorder').children().hide();
    $('#video-recorder #preview').show();
    $('#uploadSharePrivate').attr('disabled', false);

    // enable back buttons
    enableButton('tweet-button');
    enableButton('send-email-button');
    enableButton('upload-share-button');

    if(data.indexOf('session_expired') != -1) {
        onClickSignOut();
        showNotificationBar('error','Session expired. Please login and try to upload again.');
    } else {
        showNotificationBar('error','An error occured while uploading your recording. Please try again later.');
    }
};

/****************************************************************************
 * Timers to update the texts
 *****************************************************************************/

window.onTimerRecording = function() {
    var d= new Date();
    var elapsedTime = Math.round((d.getTime() - recordStartTime) / 1000);
    seconds = (3*60) - elapsedTime;

    var text = '';
    if (seconds%60 >= 10) { 
        text = parseInt(seconds/60)+':'+seconds%60;
    } else {
        text = parseInt(seconds/60)+':0'+seconds%60;
    }

    // Update count on the page
    $('#remain-time').html(text);
    top.document.title = text;

    // change window title
    document.title = text+' remaining';

    if (seconds <= 0) {
        // Update count on the page
        $('#remain-time').html(text);

        // focus if safari on mac
        if (isSafariMac()) {
            window.focus();
        }

        // stop recording
        try {
            api.stopRecording();
        } catch(err) {
            showNotificationBar('error','An error occured while trying to stop recording.');
            throw err;
        }

        // focus the window
        window.focus();

        // destroy timer
        if (timerRecording != null) {
            clearInterval(timerRecording);
            timerRecording = null;
        }
    }
};

window.onTimerWaiting = function() {
    // Remove one second
    seconds--;

    // change window title
    document.title = 'Starts in '+seconds+'s';

    // Update count on the page
    $('#countdown-number').html(''+seconds);

    // add or not the final S to seconds
    if (seconds == 1) {
        $('#countdown-seconds').html('SECOND');
    } else {
        $('#countdown-seconds').html('SECONDS');
    }

    if (seconds <= 0) {
        // start recording
        try {
            api.startRecording();
        } catch(err) {
            showNotificationBar('error','An error occured while trying to start recording.');
            throw err;
        }

        // destroy timer
        if (timerWaiting != null) {
            clearInterval(timerWaiting);
            timerWaiting = null;
        }
    }
};

window.onTimerFlashTitle = function(title) {
    // flash title
    if (title == document.title) {
        document.title = orginalDocumentTitle;
    } else {
        document.title = title;
    }
};

window.onClickDemo = function(demo_id) {
    showPopup(demo_id);
};
