

/* global variables */

var header_height = 85;
var header_height_big = 117;
var logo_padding = 0;
var logo_padding_big = 15;
var userbutton_padding = 30;
var userbutton_padding_big = 17;

//da_sense layer options
var sensorType = 1;
var algo = 'heatmapRect';
var from = new Date();//'01.02.2011 20:00';    from.getDate()+'.'+from.getMonth()+1+'.'+from.getFullYear()+' 00:00';
var to = new Date();
var provider = 'gps';

var sidebar_is_visible = false;
var mainbar_is_visible = true;
var site_content_is_visible = false;
var last_site_content = 'empty';
var seriesMenuOpen = false;


/* IDLE TIMER */
// http://paulirish.com/2009/jquery-idletimer-plugin/
    // idleTimer() takes an optional argument that defines the idle timeout
    // timeout is in milliseconds; defaults to 30000
    //$.idleTimer(21098);

    // function you want to fire when the user goes idle
    $(document).bind("idle.idleTimer", function(){
        if(!site_content_is_visible){
            hideMainbar();
            hideSidebar();
        }        
    });

    // function you want to fire when the user becomes active again
    $(document).bind("active.idleTimer", function(){        
        if(!site_content_is_visible){
            showMainbar();
            //toggleSidebar();
        }
    });
    
    

/* jQuery on document ready */
$(document).ready(function() {
    
        //set date:
        from.setFullYear(2012, 1, 1);
    
        
        //add select lib
        $("#measurement-series-select").select2({
            width: 'resolve'
            //allowClear: true
        });
        
        $('#showSeries').click(function(){
            seriesMenuOpen = !seriesMenuOpen;
            if(!seriesMenuOpen){
                $("#measurement-series-select").select2("close");
                document.getElementById('seriesDiv').style.display = 'none';
            }else{
                document.getElementById('seriesDiv').style.display = 'block';
                document.getElementById('seriesDiv').style.visibility = 'hidden';
                $("#measurement-series-select").select2("open");
            }
        });
        
        //check if user uses touch device -> changeUIToTouchDevices()
        if (!!('ontouchstart' in window) || !!('onmsgesturechange' in window) ||
            navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPhone/i)) {
            //changeUIToTouchDevices();
        }
        
        
        //last page == http://www.da-sense.de/ -> show info box
        if( document.referrer == 'http://www.da-sense.de/' ||
            document.referrer == 'http://da-sense.de/'){
            //loadAjaxContent('?action=welcome');
            setTimeout(setCookie, 10000);
        }
        
        //jqBootstrapValidation        
        $("#login_form input").not("[type=submit]").jqBootstrapValidation(
        {
            preventSubmit: true,            
            submitError: function($form, event, errors) {},
            submitSuccess: function($form, event){                      
                $.get('./api.php?call=account&action=login&username='+$('#bt_login_user').val()+'&password_sha='+$.sha1($('#bt_login_password').val())+'&password_md5='+hex_md5($('#bt_login_password').val()), function (data) {
                    if(data == 1){
                        //set cookie
                        if(document.getElementById('remember_me').checked == true){                            
                            var cookie = 'remember=true&username='+$('#bt_login_user').val()+'&password_sha='+$.sha1($('#bt_login_password').val())+'&password_md5='+hex_md5($('#bt_login_password').val());
                            $.cookie("rememberMe", cookie, { expires: 365 });
                        }
                        window.location.href = location.href.replace(/#/g, "");
                    } else {
                        $('.help-block').html("Login not successfull.</br> User & Password combination wrong.")
                    }                    
                });
                event.preventDefault();
            }            
        });

        //logout user
        $('#logout_user_top, #logout_user_sidebar').click(function (e) {
            $.get('./api.php?call=account&action=logout', function (data) {
                    $.removeCookie('rememberMe');
                    window.location.href = location.href.replace(/#/g, "");
            });
        });
        
        //show login box
        $('#show_login_box').click(function (e) {
            document.getElementById('show_login_form').click();
        });
        
        //place cursor in login field
        $('#show_login_form').click(function (e) {
            //TODO: implement
        });
         
       
        //add eventListener for key events
        addEventListener("keydown", function(e){
            handleKeyEvents(e.which, e);
        });
    
        //prevent login menu from being closed whenever user clicks inside
        $('.dropdown-menu').find('form').click(function (e) {
            e.stopPropagation();
        });
    
	// hide timepicker
	$('.filter-time .bootstrap-timepicker-component').hide();
        
        //hide site-content-wrapper
        $('#site-content-wrapper').slideUp('fast');

	// populate filter with first value
	$('div.btn-group.dasense-filter ul.dropdown-menu').each(function () {
		$(this).find('a').first().populateDasenseFilter();
	});

	// populate filter and get options after selection
	$('div.btn-group.dasense-filter ul.dropdown-menu a').click(function () {
		if($(this).attr('sensorType') != null){
			sensorType = $(this).attr('sensorType');
		}
		if($(this).attr('algo') != null){
			algo = $(this).attr('algo');
		}
                
		$(this).populateDasenseFilter();
		//call update function -> will generate the new da_sense_layer
		updateLayer();
	});

	// add timepicker
	$('.filter-add-time a').click(function () {
		$(this).parent().hide();
		$(this).parent().next('.bootstrap-timepicker-component').show();
	});

        //handle links
        $(document).on("click", "a", function(){
            if($(this).hasClass('blank')){
                $('#site-content-wrapper').slideUp('slow');
                site_content_is_visible = false;
                showNavbarControls();
                removeNavActive();
            }
            
        });

	// handle navigation link click
	$('#navigation-left ul li a, #user-button .dropdown-menu li a').click(function () {
                //show/hide navbar controls
                if($(this).is('#map-link')){
                    showNavbarControls();
                    toggleSidebar();
                }else{
                    if(!$(this).is('#show_login_box')){
                        hideNavbarControls();
                    }
                }
            
		toggleNavActive(this);
                
		if($(this).hasClass('filter')) {
			showNavBarFilter();
		} else {
			hideNavBarFilter();
		}
                
                
		if($(this).hasClass('blank')) {
			$('#site-content-wrapper').slideUp('slow');
                        site_content_is_visible = false;
		} else {
                        if(last_site_content !== $(this).attr('url') || !site_content_is_visible){
                            loadAjaxContent($(this).attr('url'));
                            last_site_content = $(this).attr('url');
                        }
                        
		}
		return false;
	});

        //toggle navbars
	$('a.brand, #toggle-sidebar').click(function(e){
            toggleSidebar();
        });
        $('#toggle-mainbar').click(function(e){
            toggleMainbar();
        });

	// initialize date- and timepickers
	$('.filter-date').datepicker();
        $('#date_from').datepicker("setValue", from); //date_to = current date
	$('#date_to').datepicker("setValue", to); //date_to = current date

	$('.filter-date').datepicker().on('changeDate', function(obj){
		if($(this).attr('id') == 'date_from'){
			from = new Date(obj.date.valueOf());
		}
		if($(this).attr('id') == 'date_to'){
			to = new Date(obj.date.valueOf());
		}

		updateLayer();

	});
	$('.timepicker-default').timepicker({
		showMeridian : false
	});

});

// extend jQuery
$.fn.extend({

	// populate twitter-bootstrap dropdowns
	populateDasenseFilter: function () {
		$(this).parents('div.btn-group').find('a.dropdown-toggle span.dropdown-text').text($(this).text());
	}

});



/*################################################################################################################################################################
 *
 *                                                              FUNCTIONS
 *      
 *################################################################################################################################################################
 */





/*
* Updates da_sense_layer
*/
function updateLayer(){
        var from_wired_timestamp = from.getDate()+'.'+(from.getMonth()+1)+'.'+from.getFullYear()+' 00:00';
        var to_wired_timestamp = to.getDate()+'.'+(to.getMonth()+1)+'.'+to.getFullYear()+' 23:59';
    
	$DS.updateSenseLayer(sensorType, algo, from_wired_timestamp, to_wired_timestamp, provider);
        
        if(sidebar_is_visible){
            $('.leaflet-control-legend').css('left', '210px');
        }
}

/*
* Loads html from the url and puts it into the content div
*/
function loadAjaxContent(url) {
        var dataTmp;
	$.get(url, function (data) {
                dataTmp = data;
                bodyelem = $("html,body");
                bodyelem.animate({scrollTop: 0});
	}).complete(function() {
            $('#site-content-wrapper').slideUp({duration: 'slow',
            complete: function(){
                $('#site-content').html(dataTmp);
                $('#site-content-wrapper').slideDown('slow');
                site_content_is_visible = true;
            }});
        }); 
}

/*
 *  Function changes some stuff, so our page will look better on touch devices / tablets
 *
 */
function changeUIToTouchDevices(){
     var oldlink = document.getElementById('cssFile');
     var newlink = document.createElement("link")
        newlink.setAttribute("rel", "stylesheet");
        newlink.setAttribute("type", "text/css");
        newlink.setAttribute("href", "dasense/page/new_default_page/css/dasenseTouch.css");
        document.getElementsByTagName("head").item(0).replaceChild(newlink, oldlink);
}
            

/*
 * Handling given keyEvents
 */
function handleKeyEvents(keyCode, event){
    
        //no key events if input has focus
        if($("*:focus").is('input') || $("*:focus").is('textarea')){
            return;
        }
    
    
        //esc-key -> show map, hide navbars
        // n-key -> show navbars
        if(keyCode == 27 || keyCode == 78){
            event.preventDefault();
            event.stopPropagation();
            if(site_content_is_visible){
                $('#site-content-wrapper').slideUp('slow');
                site_content_is_visible = false;
            }
            
            if(sidebar_is_visible || mainbar_is_visible){
                hideSidebar();
                hideMainbar();
            } else {
                if(keyCode == 78){
                    showSidebar();
                }
                showMainbar();
            }
            showNavbarControls();
            removeNavActive();
        }                


       /*
        //+ zoom in
        if(keyCode == 43){//does not work
        }
        //- zoom out
        if(keyCode == 45){//does not work
        }

        //A < move map
        if(keyCode == A || keyCode == LEFT){}
        //W /\ move map
        if(keyCode == W || keyCode == UP){}
        //S \/ move map
        if(keyCode == S || keyCode == DOWN){}
        //D > move map
        if(keyCode == D || keyCode == RIGHT){}
    */
}

/*
* Shows the left navigation bar with a slide effect
*/
function showSidebar() {
        $('#toggle-sidebar i').removeClass('icon-chevron-right').addClass('icon-chevron-left');
        $('#navigation-left-wrapper').animate({left: '0px'}, 'slow');
        $('#toggle-sidebar').animate({left: '200px'}, 'slow');
        $('.leaflet-control-legend').animate({left: '210px'}, 'slow');
        sidebar_is_visible = true;
}

/*
* Hides the left navigation bar with a slide effect
*/
function hideSidebar() {
	$('#toggle-sidebar i').removeClass('icon-chevron-left').addClass('icon-chevron-right');
	$('#navigation-left-wrapper').animate({left: '-200px'}, 'slow');
        $('#toggle-sidebar').animate({left: '0px'}, 'slow');
        $('.leaflet-control-legend').animate({left: '10px'}, 'slow');
	sidebar_is_visible = false;
        removeNavActive();
        showNavbarControls();
}

function toggleSidebar() {
	if(sidebar_is_visible) hideSidebar();
	else showSidebar();
}

/*
 * Shows the top navigatio bar with a slide effect
 */
function showMainbar() {
        $('#toggle-mainbar i').removeClass('icon-chevron-down').addClass('icon-chevron-up');
        $('#main-navbar').animate({top: '0px'}, 'slow');
        //document.getElementById('site-content-wrapper').style.top = '117';
        mainbar_is_visible = true;
}

/*
* Hides the left navigation bar with a slide effect
*/
function hideMainbar() {
	$('#toggle-mainbar i').removeClass('icon-chevron-up').addClass('icon-chevron-down');
	$('#main-navbar').animate({top: '-117px'}, 'slow');
        //document.getElementById('site-content-wrapper').style.top = '0';
	mainbar_is_visible = false;
        showNavbarControls();
}

function toggleMainbar() {
	if(mainbar_is_visible) hideMainbar();
	else showMainbar();
}

/*
 * Shows the semicircles for showing/hiding navbars
 */
function showNavbarControls(){
    document.getElementById('toggle-mainbar').style.visibility = 'visible';
    document.getElementById('toggle-sidebar').style.visibility = 'visible';
}

/*
 * Hides the semicircles for showing/hiding navbars
 */
function hideNavbarControls(){
    document.getElementById('toggle-mainbar').style.visibility = 'hidden';
    document.getElementById('toggle-sidebar').style.visibility = 'hidden';
}


/*
* Toggles 'active' class on navigation links
*/
function toggleNavActive(elem) {
	$('#navigation-left ul.nav li.active').removeClass('active');
	$(elem).parent().addClass('active');
}

/*
 * Removes 'active' class on navigation links
 */
function removeNavActive(){
    $('#navigation-left ul.nav li.active').removeClass('active');
}

/*
* Hides filter elements on top navigation bar
*/
function hideNavBarFilter() {
	$('.filter-container').hide();
	$('a.brand img').css({
		paddingTop : logo_padding,
		paddingBottom : logo_padding
	});
	$('#user-button').css({
		marginTop : userbutton_padding_big
	});
	$('#navigation-left, #wrapper').css({
		top : header_height
	});
}

/*
* Shows filter elements on top navigation bar
*/
function showNavBarFilter() {
	$('.filter-container').show();
	$('a.brand img').css({
		paddingTop : logo_padding_big,
		paddingBottom : logo_padding_big
	});
	$('#user-button').css({
		marginTop : userbutton_padding
	});
}

function createCookie(name,value,days) {
    $.cookie(name, value, { expires: days });
}


function setCookie(){
    /*bootbox.classes("bootbox");
    bootbox.confirm("Soll das neue Design dauerhaft aktiviert werden?", "Nein", "Ja",
        function(check){
            if (check == true){
                createCookie("design", "new", 22);
            }
        });*/
    
    //TODO remove!
    
}

function selectSeries(){
    var seriesID    = $('#measurement-series-select').val();
    var name        = $('#measurement-series-select option[value="'+seriesID+'"]').text();
    alert("measurementSeriesID: "+seriesID+" name: "+name);
    document.getElementById('seriesDiv').style.display = 'none';
    document.getElementById('seriesName').innerHTML = name;
    
}