/*
 * Copyright (C) 2014 Profile Music
 * 
 * UNITED KINGDOM
 * Mobile: 07984 44 5555 | Direct: 08701 99 5544 | Ext 99
 * 19 Portland Place, London, W1B 1PX
 * 
 * AUSTRALIA
 * Mobile: 0421 44 5555 | Reception: 1300 913 099
 * Level 9, 440 Collins Street, Melbourne, Victoria, 3000
 * 
 * http://www.audimator.com
 *
 * Audimator
 * developed by Andrea Coiutti (aka ACX) & Simone De Gregori (aka Orion)
 *
 */


// ====================================================================================================
// Global GUI Array
// ====================================================================================================

var GUI = {
	DBentry: ['', '', ''],
	DBupdate: 0,
	activePlayer: '',
	browsemode: 'file',
    currentClock: null,
	currentDBpos: [0,0,0,0,0,0,0,0,0,0,0],
	currentknob: null,
	currentpath: '',
	title: null,
	json: 0,
	libraryhome: '',
	mode: 'websocket',
	noticeUI: {},
    onlinetimer: null,
	playlist: null,
	plugin: '',
	serverTime: '',
    status: '',
	stepVolumeDelta: 0,
	stepVolumeInt: 0,
	stream: '',
    timeOffset: 0,
    timerRunning: false,
	visibility: 'visible',
	volume: null
};



// ====================================================================================================
// FUNCTIONS
// ====================================================================================================

// send a MPD playback control command
function sendCmd(inputcmd) {
	var request = new XMLHttpRequest();
	request.open('GET', '/api/' + inputcmd, true);
	request.onreadystatechange = function() {
		if (this.readyState === 4){
		// TODO: check this
			if (this.status >= 200 && this.status < 400){
				// Success! resp = this.responseText;
			} else {
				// Error
			}
		}
	};
	request.send();
	request = null;
}

// check WebSocket support
function checkWebSocket(){
	if (window.WebSocket){
		// console.log('WebSockets supported');
		return 'websocket';
	} else {
		// console.log('WebSockets not supported');
		return 'longpolling';
	}
}

// check HTML5 Workers support
function checkWorkers(){
	if ((window.Worker && window.Blob) || (Modernizr.webworkers && Modernizr.blobconstructor)) {
		// console.log('WebWorkers supported');
		return true;
	} else {
		// console.log('WebWorkers not supported');
		return false;
	}
}

// request a status update from Audimator
function statusRequest() {
	alert('STOP!');
}

function watchCountdown(periods) {
    if (GUI.json.mode !== 'scheduled') {
        var elapsed = periods[5]*60 + periods[6];
        var total = parseInt(GUI.json.total/1000);
        if (elapsed === (total + 2) || elapsed === (total + 10)) {
            sendCmd('renderui');
            // console.log('renderui');
        }
    }
}

// update countdown
function refreshTimer(startFrom, status) {
	// console.log('startFrom = ', startFrom);
	// console.log('status = ', status);
	var display = $('#time-elapsed-clock');
	display.countdown('destroy');
	display.countdown({ since: ((status === 'playing' && status !== undefined)? -(startFrom/1000) : 0), compact: true, format: 'MS', onTick: watchCountdown });
	// display.countdown({ until: 30, compact: true, format: 'MS', onExpiry: statusRequest });
	if (status !== 'playing'){
		// console.log('startFrom = ', startFrom);
		display.countdown('pause');
	}
}

// update playback progress knob
function refreshKnob() {
	window.clearInterval(GUI.currentKnob);
	var initTime = parseInt(GUI.json.percent, 10)*10;
	var total = parseInt(GUI.json.total, 10) / 1000;
	var step = parseInt(1000/total, 10);
	// console.log('initTime = ' + initTime + ', total = ' + total + ', step = ' + step);
	var timeknob = $('#time-elapsed-knob');
	timeknob.val(initTime).trigger('change');
    if (GUI.status === 'playing') {
		GUI.currentKnob = setInterval(function() {
			initTime = initTime + ((GUI.visibility !== 'visible') ? step : 1);
			timeknob.val(initTime).trigger('change');
		}, total);
	}
}

// time conversion
function timeConvert(ms) {
    seconds = ms / 1000;
	var minutes = Math.floor(seconds / 60);
	seconds = Math.round(seconds - minutes * 60);
    // console.log(seconds);
	var mm = (minutes < 10) ? ('0' + minutes) : minutes;
	var ss = (seconds < 10) ? ('0' + seconds) : seconds;
	return mm + ':' + ss;
}
function timeConvert2(ss) {
	var hr = Math.floor(ss/3600);
	var mm = Math.floor((ss -(hr * 3600))/60);
	ss = Math.floor(ss -(hr*3600) -(mm * 60));
	if (hr > 0) {
		if (hr < 10){
			hr = '0' + hr;
		}
		hr += ':';
	} else {
		hr = '';
	}
	if (mm < 10) { mm = '0' + mm; }
	if (ss < 10) { ss = '0' + ss; }
	return hr + mm + ':' + ss;
}

// reset countdown
function countdownRestart(startFrom) {
	var display = $('#time-elapsed-clock').countdown('destroy');
	display.countdown({since: -(startFrom), compact: true, format: 'MS'});
}

// pad zeroes
function padNum(n) {
    return (n < 10) ? ('0' + n) : n;
}

// main screen clock
function startClock(id, serverTime, offset, seconds) {
    var h, m, s, today;
    today = new Date(serverTime);
    today.setSeconds(today.getSeconds() + offset);
    h = padNum(today.getHours());
    m = today.getMinutes();
    s = today.getSeconds();
    m = padNum(m);
    s = padNum(s);
    document.getElementById(id).innerHTML = h + ((s % 2 === 0) ? ':' : '<span>:</span>') + m + ((seconds) ? ((s % 2 === 0) ? ':' : '<span>:</span>') + s : '');
    // GUI.clock1 = setTimeout(function(){
        // offset += 1;
        // startClock(id, serverTime, offset, seconds);
    // }, 1000);
}

// time setup clock
function setupClock(offset) {
    var now = new Date();
    var h, m, s = now.getSeconds();
    if( !offset ){
        h = now.getHours();
        m = now.getMinutes();
    } else {
        var hh_mm = offset.split( ':', 2 );
        h = parseInt( hh_mm[0] );
        m = parseInt( hh_mm[1] );
        if( s === 0 ){
            m++;
        }
        if( m === 60 ){
            h++;
            m = 0;
        }
        if( h === 24 ){
            h = 0;
        }
    }
    h = padNum( h );
    m = padNum( m );
    s = padNum( s );
    document.getElementById('time-local-clock').value = h +':'+ m +':'+ s;
}
function updateClock(){
    setupClock(document.getElementById('time-local-clock').value);
    // call this function again in 1000ms
    setTimeout(updateClock, 1000);
}

function getLocalDate() {
    var today, month, d, m, y;
    today = new Date();
    month = today.getMonth();
    d = padNum(today.getDate());
    m = padNum(month + 1);
    y = today.getFullYear();
    return y + '-' + m + '-' + d;
}

function currentTime() {
    var yyyy, MM, dd, h, m, s, today;
    today = new Date();
    yyyy = padNum(today.getFullYear());
    MM = padNum(today.getMonth() + 1);
    dd = padNum(today.getDate());
    hh = padNum(today.getHours());
    mm = today.getMinutes();
    ss = today.getSeconds();
    m = padNum(m);
    s = padNum(s);
    // yyyy-MM-dd hh:mm:ss
    return yyyy+ '-' + MM + '-' + dd + ' ' + hh + ':' + mm + ':' + ss;
}

// kill all the running timeouts
function startClocks(servertime, reset) {
    if (reset) {
        // console.log('GUI.currentClock = ', GUI.currentClock);
        window.clearTimeout(GUI.currentClock);
        GUI.timeOffset = 0;
        // console.log('Clock reset');
    }
    GUI.currentClock = setInterval(function(){
        startClock('clock', servertime, GUI.timeOffset);
        startClock('info-clock', servertime, GUI.timeOffset, true);
        GUI.timeOffset += 1;
        // console.log(GUI.timeOffset);
        // console.log('GUI.currentClock = ', GUI.currentClock);
    }, 1000);
}

function fitTrack() {
    // console.log('Resize!');
    // console.log('open');
    var lineHeight = $('#queue-list li').height();
    lineHeight = (lineHeight) ? lineHeight : $('body').height()/10;
    // console.log(lineHeight);
    $('#queue-list .track').css({
        'line-height' : lineHeight + 'px',
        'font-size' : (lineHeight * 0.3) + 'px'
    });
}
function fitPlaylist() {
    // console.log('Resize!');
    // console.log('open');
    var lineHeight = $('#playlists-list li').height();
    lineHeight = (lineHeight) ? lineHeight : $('body').height()/10;
    // console.log(lineHeight);
    $('#playlists-list .playlist').css({
        'line-height' : lineHeight + 'px',
        'font-size' : (lineHeight * 0.3) + 'px'
    });
}

// launch the Playback UI refresh from the data response
function renderUI(text){
	GUI.json = text[0];
    // console.log(GUI.json);
	GUI.status = GUI.json.status;
    var elapsed = (GUI.json.elapsed !== '' && GUI.json.elapsed !== undefined)? GUI.json.elapsed : 0;
	var time = (GUI.json.time !== '' && GUI.json.time !== undefined && GUI.json.time !== null)? GUI.json.time : 0;
	if (GUI.status === 'playing') {
        refreshKnob();
        $('.loading').removeClass('hide');
        $('#time-total').html((GUI.json.total !== undefined)? timeConvert(GUI.json.total) : '00:00');
        refreshTimer(parseInt(elapsed, 10), GUI.json.status);
        var playermode = '';
        switch(GUI.json.mode) {
            case 'fallback1':
                playermode = 'weekly';
                break;
            case 'fallback2':
                playermode = 'vault';
                break;
            default:
                playermode = GUI.json.mode;
        }
        $('#player-mode').html('<i class="fa fa-play sx"></i> ' + playermode);
	} else {
        $('.loading').addClass('hide');
		$('#countdown-display').countdown('destroy');
		$('#time-total').html('00:00');
		$('#time-elapsed-knob').val(0).trigger('change');
        $('#player-mode').html('<i class="fa fa-stop sx"></i> stopped');
	}
    var artist = GUI.json.artist;
    var title = GUI.json.title;
    $('#artist').html((artist === null || artist === undefined || artist === '') ? '<span class="notag">[no artist]</span>' : artist);
    $('#title').html((title === null || title === undefined || title === '') ? '<span class="notag">[no title]</span>' : title);
    // force the clock update
    $.ajax({
        type: 'GET',
        url: 'api/gettime',
        dataType: 'text',
        success: function(response){
            var servertime = response.replace(/"/g, '');
            startClocks(servertime, true);
        }
    });
}

function renderNotify(text){
    msg = text[0];
    if (typeof msg.body == 'undefined')
        msg.body = '';
    new PNotify({
        title: msg.title,
        text: msg.body,
        delay: 2000,
        icon: 'fa fa-exclamation-circle',
    });
}

function parseQueue(data){
    // console.log(data);
    // var current = parseInt(GUI.json.song, 10) + 1;
    // var status = GUI.status;
    var i, line, lines = data.split('\n');
    var pos = 1;
    var tracks = []; // array containing all the tracks
    var track = {}; // base model
    for (i = 0; (line = lines[i]); i += 1) {
        track.current = (line.charAt(1) === '1');
        // line = line.slice(3, -4);
        line = line.slice(3);
        line = line.replace('.mp3', '');
        var infos = line.split(' - ');
        track.artist = infos[0];
        track.title = infos[1];
        track.pos = pos++;
        tracks.push(track);
        track = {};
    }
    return tracks;
}

function buildQueue(tracks){
    var html = '';
    var loader = '<div class="loading"><div class="loading-1"></div><div class="loading-2"></div><div class="loading-3"></div><div class="loading-4"></div><div class="loading-5"></div><div class="loading-6"></div></div>';
    for (i = 0; (i < tracks.length); i += 1) {
        track = tracks[i];
        if (track.artist && track.title) {
            html += '<li' + ((track.current) ? ' class="current"' : '') +'><span class="track track-' + i + '">' + ((track.current) ? loader : '') + '<span class="trackartist">' + track.artist + '</span> - <span class="tracktitle">' + track.title + '</span></span></li>';
        } else {
            html += '<li' + ((track.current) ? ' class="current"' : '') +'><span class="track track-' + i + '">-</span></li>';
        }
    }
    document.getElementById('queue-list').innerHTML = html;
}

function renderQueue(text) {
    text = text[0];
    // console.log(text);
    if (text.length > 3) {
        var queueTracks = parseQueue(text);
        buildQueue(queueTracks);
    }
    if ($('#overlay-queue').hasClass('open') || $('#overlay-playlists').hasClass('open')) {
        fitTrack();
        fitPlaylist();
    }
}

// open the Status channel
function statusChannel(){
	var pushstream = new PushStream({
		host: window.location.hostname,
		port: window.location.port,
		modes: GUI.mode,
		reconnectOnChannelUnavailableInterval: 5000
	});
	pushstream.onmessage = renderUI;
	pushstream.onstatuschange = function(status) {
		console.log('[nginx pushtream module] status = ', status);
		if (status === 2) {
			sendCmd('renderui'); // force UI rendering (backend-call)
		} else {
			console.log('[nginx pushtream module] status change (' + status + ')');
			if (status === 0) {
				console.log('[nginx pushtream module] status disconnected (0)');
			}
		}
	};
	pushstream.addChannel('status');
	pushstream.connect();
}

// open the Queue channel
function queueChannel(){
	var pushstream = new PushStream({
		host: window.location.hostname,
		port: window.location.port,
		modes: GUI.mode,
		reconnectOnChannelUnavailableInterval: 5000
	});
	pushstream.onmessage = renderQueue;
    pushstream.onstatuschange = function(status) {
		// console.log('[nginx pushtream module] status = ', status);
		if (status === 2) {
			sendCmd('queue'); // force Queue rendering (backend-call)
		}
	};
	pushstream.addChannel('queue');
	pushstream.connect();
}

// open the Queue channel
function notifyChannel(){
	var pushstream = new PushStream({
		host: window.location.hostname,
		port: window.location.port,
		modes: GUI.mode,
		reconnectOnChannelUnavailableInterval: 5000
	});
	pushstream.onmessage = renderNotify;
	pushstream.addChannel('notify');
	pushstream.connect();
}

// AJAX online status check
function onlineStatus() {
    $.ajax({
        type: 'GET',
        url: 'api/onlinestatus',
        dataType: 'text',
        success: function(response){
            if (response === '"online"') {
                $('#connection-status').html('<i class="fa fa-globe sx"></i> online').addClass('online');
            } else {
                $('#connection-status').html('<i class="fa fa-warning sx"></i> offline').removeClass('online');
            }
        },
        error: function(){
            $('#connection-status').html('<i class="fa fa-warning sx"></i> offline').removeClass('online');
        },
    });
    GUI.onlinetimer = setTimeout(onlineStatus, 60000);
}

// page redirect
function pageRedirect(url, delay) {
    delay = delay || 3000;
    $('#loader').removeClass('hide');
    setTimeout(function(){
        window.location.href = url;
    }, delay);
}

// retrieve Eth0 infos
function getNICinfoEth0() {
    $.ajax({
        type: 'GET',
        url: 'api/netconfig/eth0',
        dataType: 'text',
        cache: false,
        success: function(data) {
            var nic = JSON.parse(data);
            // in Network section, switch correctly the DHCP select menu
            if ($('#section-network').length) {
                console.log(nic.dhcp);
                if (nic.dhcp === '0') {
                    $('#dhcp').val(0);
                }
            }
            // console.log(nic);
            nic.status = (nic.ip) ? '<i class="fa fa-check green sx"></i>connected' : '<i class="fa fa-times red sx"></i>disconnected';
            nic.type = (nic.name === 'eth0') ? 'wired network' : 'wireless network';
            nic.dhcp = (nic.dhcp === '0') ? 'Static IP' : 'DHCP';
            nic.proxy = (nic.proxy) ? nic.proxy : '<em>no proxy configured</em>';
            nic.proxyport = (nic.proxyport) ? nic.proxyport : '<em>no proxy configured</em>';
            if ($('#section-network').length) {
                $('#nictable-name').html(nic.name);
                $('#nictable-type').html(nic.type);
                $('#nictable-status').html(nic.status);
                $('#nictable-dhcp').html(nic.dhcp);
                $('#nictable-ip').html(nic.ip);
                $('#nictable-gw').html(nic.gw);
                $('#nictable-netmask').html(nic.netmask);
                $('#nictable-dns1').html(nic.dns1);
                $('#nictable-dns2').html(nic.dns2);
                $('#nictable-speed').html(nic.speed);
                $('#nictable-proxy').html(nic.proxy);
                $('#nictable-proxyport').html(nic.proxyport);
            } else if ($('#section-index').length) {
                $('#info-table-ip').html(nic.ip);
            }
        }
    });
}

// retrieve Wlan0 infos
function getNICinfoWlan0() {
    $.ajax({
        type: 'GET',
        url: 'api/netconfig/wlan0',
        dataType: 'text',
        cache: false,
        success: function(data) {
            var nic = JSON.parse(data);
            // in Network section, switch correctly the Operating mode select menu
            if ($('#section-wireless').length) {
                if (nic.mode === 'client') {
                    $('#wifimode').val(1);
                }
            }
            // in Network section, switch correctly the DHCP select menu
            if ($('#section-wireless').length) {
                if (nic.dhcp === '0') {
                    $('#dhcp').val(0);
                }
            }
            console.log(nic);
            nic.status = (nic.ip) ? '<i class="fa fa-check green sx"></i>connected' : '<i class="fa fa-times red sx"></i>disconnected';
            nic.dhcp = (nic.dhcp === '0') ? 'Static IP' : 'DHCP';
            nic.proxy = (nic.proxy) ? nic.proxy : '<em>no proxy configured</em>';
            nic.proxyport = (nic.proxyport) ? nic.proxyport : '<em>no proxy configured</em>';
            if ($('#section-wireless').length) {
                $('#nictable-name').html(nic.name);
                $('#nictable-type').html(nic.type);
                $('#nictable-status').html(nic.status);
                $('#nictable-dhcp').html(nic.dhcp);
                $('#nictable-ip').html(nic.ip);
                $('#nictable-gw').html(nic.gw);
                $('#nictable-netmask').html(nic.netmask);
                $('#nictable-dns1').html(nic.dns1);
                $('#nictable-dns2').html(nic.dns2);
                $('#nictable-speed').html(nic.speed);
                $('#nictable-proxy').html(nic.proxy);
                $('#nictable-proxyport').html(nic.proxyport);
                $('#nictable-wifimode').html(nic.mode);
            }
        }
    });
}
        
// trigger home overlays
function overlayTrigger(overlayID) {
    // var triggerBttn = $('#overlay-social-open'),
        // overlay = $('#overlay-social'),
        // closeBttn = $('button.overlay-close');
    var overlay = $(overlayID),
        triggerBttn = $(overlayID + '-open'),
        closeBttn = $(overlayID + '-close');
        transEndEventNames = {
            'WebkitTransition': 'webkitTransitionEnd',
            'MozTransition': 'transitionend',
            'OTransition': 'oTransitionEnd',
            'msTransition': 'MSTransitionEnd',
            'transition': 'transitionend'
        };
        // transEndEventName = transEndEventNames[ Modernizr.prefixed( 'transition' ) ],
        // support = { transitions : Modernizr.csstransitions };
    function toggleOverlay() {
        if (overlay.hasClass('open')) {
            overlay.removeClass('open');
            overlay.addClass('closed');
            var onEndTransitionFn = function(ev) {
                if (support.transitions) {
                    if (ev.propertyName !== 'visibility') {
                        return;
                    }
                    this.removeEventListener( transEndEventName, onEndTransitionFn );
                }
                overlay.removeClass('closed');
            };
            // if (support.transitions) {
                // overlay.addEventListener( transEndEventName, onEndTransitionFn );
            // }
            // else {
                // onEndTransitionFn();
            // }
        }
        else if (overlay.hasClass('closed')) {
            overlay.addClass('open');
            overlay.removeClass('closed');
        }
    }
    triggerBttn.click(function(){
        toggleOverlay();
    });
    closeBttn.click(function(){
        toggleOverlay();
    });
}

if ($('#section-index').length) {

// ====================================================================================================
// PLAYBACK SCREEN
// ====================================================================================================

    jQuery(document).ready(function($) { 'use strict';
        
        // INITIALIZATION
		// ----------------------------------------------------------------------------------------------------
		
		// check WebSocket support
		GUI.mode = checkWebSocket();
		// init knob
        $('#time-elapsed-knob').knob();
        
		// first connection with Audimator daemon
		// open Audimator status channel;
		statusChannel();
        // open Audimator queue channel;
        queueChannel();
        // open Audimator notify channel;
        notifyChannel();
        
        // check and output online status periodically
        GUI.onlinetimer = setTimeout(onlineStatus, 1000);
        
        // clock
        GUI.serverTime = $('#clock').data('time');
        startClocks(GUI.serverTime);
        
        // check visibility of the window
        ifvisible.on('blur', function(){
            // console.log('BLUR');
            GUI.visibility = 'hidden';
        });
        ifvisible.on('focus', function(){
            // console.log('FOCUS');
            GUI.visibility = 'visible';
        });
        
        // init overlays
        overlayTrigger('#overlay-queue');
        overlayTrigger('#overlay-info');
        overlayTrigger('#overlay-playlists');
        
        // show the device's IP
        getNICinfoEth0();
        getNICinfoWlan0();
        
        // remove the 300ms click delay on mobile browsers
        FastClick.attach(document.body);
        
        // playlists overlay
        // $('.playlist').fitText(1.2, {minFontSize: '13px', maxFontSize: '20px'});
        // $('.track').fitText(1.2, {minFontSize: '13px', maxFontSize: '20px'});
        $(window).resize(function() {
            if ($('#overlay-queue').hasClass('open') || $('#overlay-playlists').hasClass('open')) {
                fitTrack();
                fitPlaylist();
            }
        });
        $('#overlay-queue-open').click(function(){
            fitTrack();
        });
        $('#overlay-playlists-open').click(function(){
            fitPlaylist();
        });
        // load manual playlist
        $('#playlists-list').on('click', 'li', function(e) {
            var el = $(this);
            var playlistName = el.find('span.playlist-name').attr('id').replace('pl-', '') + ' ' + el.find('span.playlist-name').html();
            if (playlistName.indexOf('schedule') > -1) {
                playlistName = 'schedule';
            }
            // console.log(playlistName);
            $.ajax({
                type: 'POST',
                url: 'api/load',
                data: {plname: playlistName}
            });
            $('#overlay-playlists-close').trigger('click');
        });
        
    });

} else {

// ====================================================================================================
// OTHER SECTIONS
// ====================================================================================================

	jQuery(document).ready(function($){ 'use strict';
    
        // Bootstrap-select
        $('.selectpicker').selectpicker();
        
        if ($('#section-setup').length || $('#section-setup-repeat').length) {
            // open Audimator notify channel;
            notifyChannel();
        
            var setup_mask_format = '####-###-######-#######';
            var setup_code_field = $('#pinpad-code');
            var setup_code_field_copy = $('#pinpad-code-copy');
            setup_code_field_copy.mask(setup_mask_format, {placeholder: setup_mask_format});
            var setup_code = setup_code_field.val();
            var setup_code_submit = $('#pinpad-submit');
            
            if (setup_code.length === 20) {
                setup_code_submit.removeClass('disabled');
            }
            $('.btn-pinpad').click(function(){
                if (setup_code.length < 20) {
                    setup_code += $(this).val();
                    setup_code_field.val(setup_code);
                    setup_code_field_copy.val(setup_code).keyup();
                    if (setup_code.length === 20) {
                        setup_code_submit.removeClass('disabled');
                    }
                    // console.log(setup_code.length);
                }
            });
            $('#pinpad-cancel').click(function(){
                setup_code_submit.addClass('disabled');
                setup_code = setup_code_field.val();
                setup_code = setup_code.substring(0, setup_code.length - 1);
                setup_code_field.val(setup_code);
                setup_code_field_copy.val(setup_code).keyup();
            });
            $('.btn-pinpadsubmit').click(function(){
                if ($('body').is('#section-setup')) {
                    var activationcode = $('#pinpad-code').val();
                    $.ajax({
                        type: 'POST',
                        url: 'api/startconfig',
                        data: {code: activationcode }
                    }).done(function(response) {
                        // console.log(response);
                        if (response) {
                            pageRedirect('/setup-repeat', 1000);
                        } else {
                            alert('No response from backend');
                        }
                    });
                } else if ($('body').is('#section-setup-repeat')) {
                    var inputcode = $('#pinpad-code').val();
                    var tempcode = $('#pinpad-code-first').val();
                    // console.log(inputcode);
                    // console.log(tempcode);
                    if (inputcode === tempcode) {
                        pageRedirect('/time');
                    } else {
                        // $('#error-display').removeClass('hide');
                        $('#code-mismatch').modal();
                    }
                }
            });
            
        }
                
        if ($('#section-setup-time').length) {
            // open Audimator notify channel;
            notifyChannel();
            
            // clock
            setupClock();
            updateClock();
            // clockpicker
            $('.clockpicker').clockpicker({
                donetext: 'Set time',
                'default': 'now',
                afterDone: function(e) {
                    setupClock( $('#time-local-clock').val() );
                }
            });
            // datepicker
            $('#datepicker input').datepicker({
                format: 'MM dd, yyyy',
                todayHighlight: true,
                todayBtn: true
            }).datepicker('update', new Date()).on('changeDate', function(date){
                $('#datepicker-date').val(date.format('yyyy-mm-dd'));
            });
            // set date in hidden field
            $('#datepicker-date').val(getLocalDate());
            
            $('#time-setup-submit').click(function(){
                var data = {
                    timezone:   $('#timezone-select').val()
                };
                if (data.timezone !== '') {
                    var localdate = $('#datepicker-date').val();
                    var localtime = $('#time-local input').val();
                    // formatting date for system cmd
                    // # timedatectl set-time "yyyy-MM-dd hh:mm:ss"
                    data.date = localdate + ' ' + localtime;
                    console.log(data.date);
                    $.ajax({
                        type: 'POST',
                        url: 'api/settime',
                        data: data
                    }).done(function(response) {
                        // console.log(response);
                        if (response) {
                            if ($('#time-setup-submit').data('activated') === 'yes') {
                                pageRedirect('/');
                            } else {
                                pageRedirect('/setup-complete');
                            }
                        } else {
                            alert('No response from backend');
                        }
                    });
                } else {
                    $('button[data-id="timezone-select"]').addClass('btn-danger');
                    // console.log('Select a timezone');
                }
            });
            $('button[data-id="timezone-select"]').click(function(){
                $(this).removeClass('btn-danger');
            });
            
        }
        
        if ($('#section-setup-complete').length) {
            // open Audimator notify channel;
            notifyChannel();
            
            var clicks = 0;
            
            $('#congratulations').click(function() {
                ++clicks;
                // console.log(clicks);
                if (clicks === 5) {
                    var activationcode = $(this).data('code');
                    $.ajax({
                        type: 'POST',
                        url: 'api/activation',
                        data: {
                            code: activationcode
                        }
                    }).done(function(response) {
                        // console.log(response);
                        $('#setup-complete-submit').addClass('hide');
                        $('#reboot-redirect-msg').removeClass('hide');
                        if (response) {
                            pageRedirect('/', 1000);
                        } else {
                            alert('No response from backend');
                        }
                    });
                }
            });
            
            $('#setup-complete-submit').click(function() {
                var activationcode = $(this).data('code');
                $.ajax({
                    type: 'POST',
                    url: 'api/activation',
                    data: {
                        code: activationcode,
                        reboot: 1
                    }
                }).done(function(response) {
                    // console.log(response);
                    $('#setup-complete-submit').addClass('hide');
                    $('#reboot-redirect-msg').removeClass('hide');
                    if (response) {
                        pageRedirect('/', 40000);
                    } else {
                        alert('No response from backend');
                    }
                });
            });
            
        }
        
        if ($('#section-network').length) {
            // open Audimator notify channel;
            notifyChannel();
            
            // dinamically populate the "Interface properties" table
            getNICinfoEth0();

            // show/hide static network configuration based on select value
            var netManualConf = $('#network-manual-config');
            if ($('#dhcp').val() === '0') {
                netManualConf.removeClass('hide');
            }
            $('#dhcp').change(function(){
                if ($(this).val() === '0') {
                    netManualConf.removeClass('hide');
                }
                else {
                    netManualConf.addClass('hide');
                }
            });

        }
        
        if ($('#section-wireless').length) {
            // open Audimator notify channel;
            notifyChannel();
            
            // dinamically populate the "Interface properties" table
            getNICinfoWlan0();

            // show/hide wireless mode configuration based on select value
            var wirelessClientConf = $('#wireless-client-config');
            if ($('#wifimode').val() === '1') {
                wirelessClientConf.removeClass('hide');
            }
            $('#wifimode').change(function(){
                if ($(this).val() === '0') {
                    wirelessClientConf.addClass('hide');
                }
                else {
                    wirelessClientConf.removeClass('hide');
                }
            });
            
            // show/hide static network configuration based on select value
            var netWlan0ManualConf = $('#wireless-manual-config');
            if ($('#dhcp').val() === '0') {
                netWlan0ManualConf.removeClass('hide');
            }
            $('#dhcp').change(function(){
                if ($(this).val() === '0') {
                    netWlan0ManualConf.removeClass('hide');
                }
                else {
                    netWlan0ManualConf.addClass('hide');
                }
            });
            
        }
        
        if ($('#section-network-complete').length) {
            // open Audimator notify channel;
            notifyChannel();
            
            $('#network-complete-submit').click(function(){
                var netconfig = {};
                netconfig.dhcp      = $('input[name="dhcp"]').val();
                netconfig.ip        = $('input[name="ip"]').val();
                netconfig.netmask   = $('input[name="netmask"]').val();
                netconfig.gw        = $('input[name="gw"]').val();
                netconfig.dns1      = $('input[name="dns1"]').val();
                netconfig.dns2      = $('input[name="dns2"]').val();
                netconfig.proxy     = $('input[name="proxy"]').val();
                netconfig.proxyport = $('input[name="proxyport"]').val();
                console.log(netconfig);
                $.ajax({
                    type: 'POST',
                    url: 'api/netconfig/eth0',
                    data: netconfig
                }).done(function(response) {
                    $('#network-complete-submit').addClass('hide');
                    $('#reboot-redirect-msg').removeClass('hide');
                    if (response) {
                        pageRedirect('/', 40000);
                    } else {
                        alert('No response from backend');
                    }
                });
            });
        }
        
        if ($('#section-wireless-complete').length) {
            // open Audimator notify channel;
            notifyChannel();
            
            $('#wireless-complete-submit').click(function(){
                var wificonfig = {};
                wificonfig.name = $('input[name="name"]').val();
                wificonfig.wireless = $('input[name="wireless"]').val();
                wificonfig.wifimode = $('input[name="wifimode"]').val();
                wificonfig.ssid = $('input[name="ssid"]').val();
                wificonfig.ssid_hidden = $('input[name="ssid_hidden"]').val();
                wificonfig.pass = $('input[name="pass"]').val();
                wificonfig.dhcp      = $('input[name="dhcp"]').val();
                wificonfig.ip        = $('input[name="ip"]').val();
                wificonfig.netmask   = $('input[name="netmask"]').val();
                wificonfig.gw        = $('input[name="gw"]').val();
                wificonfig.dns1      = $('input[name="dns1"]').val();
                wificonfig.dns2      = $('input[name="dns2"]').val();
                wificonfig.proxy = $('input[name="proxy"]').val();
                wificonfig.proxyport = $('input[name="proxyport"]').val();
                console.log(wificonfig);
                $.ajax({
                    type: 'POST',
                    url: 'api/netconfig/wlan0',
                    data: wificonfig
                }).done(function(response) {
                    $('#network-complete-submit').addClass('hide');
                    $('#reboot-redirect-msg').removeClass('hide');
                    if (response) {
                        pageRedirect('/', 40000);
                    } else {
                        alert('No response from backend');
                    }
                });
            });
        }
        
        if ($('#section-service').length) {
            // open Audimator notify channel;
            notifyChannel();
            
            // check and output online status periodically
            GUI.onlinetimer = setTimeout(onlineStatus, 1000);
            
            $('button').click(function(){
                var endpoint = $(this).attr('data-endpoint');
                if (typeof endpoint !== typeof undefined && endpoint !== false) {
                    $.ajax({
                        type: 'GET',
                        url: 'api/' + endpoint
                    }).done(function(response) {
                        console.log(response);
                    });
                }
            });
            
        }
        
        if ($('#section-login').length) {
            
            $('#modal-login').modal();
            
        }
    
    });

}
