var ambiant = document.getElementById('ambiant-value');
var askedValue = $('input[name=left-air]').val();

var Climatronic = 
{
    ventilateur: typeof $.cookie('ventilateur') === "undefined" ? false : $.cookie('ventilateur'),
    StopColdVar: typeof $.cookie('StopColdVar') === "undefined" ? true : $.cookie('StopColdVar'),
    activeAutoWideWasherVar: typeof $.cookie('activeAutoWideWasherVar') === "undefined" ? false : $.cookie('activeAutoWideWasherVar'),
    activeLightAutoVar: typeof $.cookie('activeLightAutoVar') === "undefined" ? false : $.cookie('activeLightAutoVar'),
    ambiantArduino: 20,
    initialize: function() 
	{
        document.addEventListener('deviceready', this.onDeviceReady, false);
        Climatronic.onDeviceReady();
    },
    activeAuto_defrost: function(state) 
	{
        if (typeof state === 'undefined')
            Climatronic.activeAuto_defrostVar = Climatronic.activeAuto_defrostVar ? false : true;
        else
            Climatronic.activeAuto_defrostVar = state;

        if (Climatronic.activeAuto_defrostVar) {
            $('#auto_defrost').addClass('active_icon');
            $('.auto_defrost').addClass('active_icon');
        } else {
            $('#auto_defrost').removeClass('active_icon');
            $('.auto_defrost').removeClass('active_icon');
        }

        $.cookie('activeAuto_defrostVar', Climatronic.activeAutoWideWasherVar);
    },
    activeLightAuto: function(state) 
	{
        if (typeof state === 'undefined')
            Climatronic.activeLightAutoVar = Climatronic.activeLightAutoVar ? false : true;
        else
            Climatronic.activeLightAutoVar = state;

        if (Climatronic.activeLightAutoVar) {
            $('#detect_night').addClass('active_icon');
            $('.detect_night').addClass('active_icon');
        } else {
            $('#detect_night').removeClass('active_icon');
            $('.detect_night').removeClass('active_icon');
        }
        $.cookie('activeLightAutoVar', Climatronic.activeLightAutoVar);
    },
    activeAutoWideWasher: function(state) 
	{
        if (typeof state === 'undefined')
            Climatronic.activeAutoWideWasherVar = Climatronic.activeAutoWideWasherVar ? false : true;
        else
            Climatronic.activeAutoWideWasherVar = state;

        if (Climatronic.activeAutoWideWasherVar) {
            $('#detect_rain').addClass('active_icon');
            $('.detect_rain').addClass('active_icon');
        } else {
            $('#detect_rain').removeClass('active_icon');
            $('.detect_rain').removeClass('active_icon');
        }

        $.cookie('activeAutoWideWasherVar', Climatronic.activeAutoWideWasherVar);
    },
    StopCold: function(state) 
	{
        Climatronic.StopColdVar = state;

        if (!Climatronic.StopColdVar) {
            $('#clima').addClass('active_icon');
            $('.clima').addClass('active_icon');
            $('.clima').effect("bounce", {
                times: 1
            }, "slow");
        } else {
            $('#clima').removeClass('active_icon');
            $('.clima').removeClass('active_icon');
        }

        $.cookie('StopColdVar', Climatronic.StopColdVar);
    },
    activeVentilation: function(state) 
	{
        if (typeof state === 'undefined')
            Climatronic.ventilateur = Climatronic.ventilateur ? false : true;
        else
            Climatronic.ventilateur = state;


        if (!Climatronic.ventilateur) {
            Climatronic.StopCold(true);
        }

        $.cookie('ventilateur', Climatronic.ventilateur);

        if (Climatronic.ventilateur) {
            $("#left-air,#right-air").fadeOut("slow").fadeIn("slow", function() {
                $('.rs-block .rs-inner').attr('style', 'background-image:url(assets/images/power8.png);background-size: 47px; background-repeat: no-repeat; background-position: center;');
            });


            // Send data to arduino
        } else {
            $("#left-air,#right-air").fadeOut("slow").fadeIn("slow", function() {
                $('.rs-block .rs-inner').attr('style', 'background-image:url(assets/images/power7.png);background-size: 47px; background-repeat: no-repeat; background-position: center;');
            });

            // Send data to arduino
        }
    },
    startDashboard: function(calback) 
	{
        $('#container').fadeIn("slow", function() {
            var i = 0;
            $(".car-img").animate({
                "left": "-14px"
            }, {
                duration: 2000,
                step: function() {
                    i++;

                    if (i == 100) $(".indicateurs").fadeIn("slow", function() {
                        $('#ambiant, #spanzone1, #spanzone2').fadeIn("slow");
                    });
                },
                complete: function() {
                    $("#left-air,#right-air").animate({
                        "bottom": "0px"
                    }, {
                        duration: 150
                    });
                }
            });

            calback();
        });
    },
    requestingData: function() 
	{
        return;
        var ambiant = document.getElementById('ambiant-value');

        var askedValue = $('input[name=left-air]').val();

        var errorCallback = function(message) {
            alert('Error: ' + message);
        };

        serial.open({
                baudRate: 9600
            },
            function(successMessage) 
			{
                open = true;

                serial.registerReadCallback(function success(data) 
				{
                        // decode the received message
                        var view = new Uint8Array(data);

                        if (view.length >= 1) 
						{
                            var str = '';

                            for (var i = 0; i < view.length; i++) 
							{
                                // if we received a \n, the message is complete, display it
                                if (view[i] == 13) {
                                    var value = parseInt(str);
                                    alert(value);

                                    $('#ambiant-value').text(value + ' C')

                                    str = '';
                                }
                                // if not, concatenate with the begening of the message
                                else {
                                    var temp_str = String.fromCharCode(view[i]);
                                    var str_esc = escape(temp_str);
                                    str += unescape(str_esc);
                                }
                            }
							
							var sys_Clima, sys_wider, sys_lights;
							
                            if (Climatronic.ventilateur)
                                sys_Clima = 1;
                            else
                                sys_Clima = 2;

                            if (askedValue > Climatronic.ambiantArduino) {
                                Climatronic.StopCold(false);
                                sys_Clima = 3;
                            } else if (askedValue < Climatronic.ambiantArduino) {
                                Climatronic.StopCold(true);
                                sys_Clima = 4;
                            } else if (askedValue = Climatronic.ambiantArduino) {
                                Climatronic.activeVentilation(false);
                                Climatronic.StopCold(true);
                                sys_Clima = 5;
                            }
							
							if (activeAutoWideWasherVar)
							{
								sys_Clima = 6;
							}
							else
							{
								sys_Clima = 7;
							}
							
							if (activeLightAutoVar)
							{
								sys_lights = 8;
							}
							else
							{
								sys_lights = 9;
							}
							
							serial.write(sys_Clima+sys_wider+sys_lights,
								function(successMessage) 
{
									alert(successMessage);
								},errorCallback
							);
                        }
                    },
                    errorCallback
                );
            },
            errorCallback
        );
    },
    onDeviceReady: function() 
	{
        window.screen.orientation.lock('landscape');

        //cordova.plugins.autoStart.enable();

        $("#left-air").roundSlider({
            radius: 85,
            sliderType: "min-range",
            value: typeof $.cookie('valueLeft') === "undefined" ? 22 : $.cookie('valueLeft'),
            endAngle: 210,
            create: function(args) {
                if (args.value == 25) {
                    $('#spanzone1').text("High Flow").addClass('hot').removeClass("normal");
                } else if (args.value == 18) {
                    $('#spanzone1').text("Low Flow").addClass('cold').removeClass("normal").removeClass('cold').removeClass('hot');;
                } else {
                    $('#spanzone1').text(args.value + ' °C').addClass("normal");
                }
            },
            change: function(args) {
                if (args.value == 25) {
                    $('#spanzone1').text("High Flow").addClass('hot').removeClass("normal").removeClass('cold');
                } else if (args.value == 18) {
                    $('#spanzone1').text("Low Flow").addClass('cold').removeClass("normal").removeClass('hot');
                } else {
                    $('#spanzone1').text(args.value + ' °C').removeClass('cold').removeClass('hot').addClass("normal");
                }

                if (!Climatronic.ventilateur) Climatronic.activeVentilation();

                if (args.value < Climatronic.ambiantArduino) Climatronic.StopCold(false);
                else if (args.value > Climatronic.ambiantArduino) Climatronic.StopCold(true);
                else {
                    Climatronic.activeVentilation(false);
                    Climatronic.StopCold(true);
                }

                $.cookie('valueLeft', args.value, 7);

                console.log($.cookie('valueLeft'));

            },
            min: 18,
            max: 25
        });

        $("#right-air").roundSlider({
            radius: 85,
            sliderType: "min-range",
            value: typeof $.cookie('valueRight') === "undefined" ? 22 : $.cookie('valueRight'),
            endAngle: 210,
            create: function(args) {
                if (args.value == 25) {
                    $('#spanzone2').text("High Flow").addClass('hot').removeClass("normal").removeClass('cold');;
                } else if (args.value == 18) {
                    $('#spanzone2').text("Low Flow").addClass('cold').removeClass("normal").removeClass('hot');;
                } else {
                    $('#spanzone2').text(args.value + ' °C').addClass("normal").removeClass('hot').removeClass('cold');
                }
            },
            change: function(args) {
                if (args.value == 25) {
                    $('#spanzone2').text("High Flow").addClass('hot').removeClass("normal").removeClass('cold');
                } else if (args.value == 18) {
                    $('#spanzone2').text("Low Flow").addClass('cold').removeClass("normal").removeClass('hot');
                } else {
                    $('#spanzone2').text(args.value + ' °C').removeClass('cold').removeClass('hot').addClass("normal");
                }

                if (!Climatronic.ventilateur) Climatronic.activeVentilation();

                $.cookie('valueRight', args.value);

                /*if(args.value < Climatronic.ambiantArduino) Climatronic.StopCold(false) ;
                else if(args.value > Climatronic.ambiantArduino) Climatronic.StopCold(true);
                else {Climatronic.activeVentilation(false); Climatronic.StopCold(true);}*/
            },
            min: 18,
            max: 25
        });

        Climatronic.startDashboard(function() {
            setInterval(function() {
                Climatronic.requestingData();
            }, 1000);


            $('body').on('click', '.auto_defrost', function() {
                $(this).effect("bounce", {
                    times: 1
                }, "slow");
                Climatronic.activeAuto_defrost();
            });

            $('body').on('click', '.detect_night', function() {
                $(this).effect("bounce", {
                    times: 1
                }, "slow");
                Climatronic.activeLightAuto();
            });

            $('body').on('click', '.detect_rain', function() {
                $(this).effect("bounce", {
                    times: 1
                }, "slow");
                Climatronic.activeAutoWideWasher();

            });

            $('body').on('click', '.rs-inner', function() {
                Climatronic.activeVentilation();
            });



            $('body').on('click', '.car-img', function() {
                $('#container').fadeOut('slow', function() {
                    $('#container').css({
                        'background': 'url(assets/images/bg2.png)'
                    });

                    $('#sub_container_1').hide();
                    $('#sub_container_2').show();
					$('#sub_container_3').hide();
                    setTimeout(function() {
                        $('#container').fadeIn('slow');
                    }, 500);

                });
            });

            $('body').on('click', '.retour', function() {
                $('#container').fadeOut('slow', function() {
                    $('#container').css({
                        'background': 'url(assets/images/bg.png)'
                    });

                    $('#sub_container_2').hide();
                    $('#sub_container_1').show();
					$('#sub_container_3').hide();
                    setTimeout(function() {
                        $('#container').fadeIn('slow');
                    }, 500);

                });
            });
			
			
			$('body').on('click', '.car-front', function() {
                $('#container').fadeOut('slow', function() {
                    
					
					$('#sub_container_1').hide();
                    $('#sub_container_2').hide();
                    $('#sub_container_3').show();
                    setTimeout(function() {
                        $('#container').fadeIn('slow');
                    }, 500);

                });
            });
			
			
			



        });
    }
};

Climatronic.initialize();