/**
 * Updates the group parameters and display.
 * @param  {object} group the group data
 */
function updateGroup(group) {
    if (typeof(group) !== 'object') {
        console.log("unexpected data " + typeof(group));
        return;
    }

    curEdit.obj = group;
    curEdit.obj.id = groupId;
    curEdit.obj.type = TYPE_GROUP;
    curEdit.obj.state = group.action; // groups use "action" instead of "state"
    curEdit.obj.hasColor = true;
    curEdit.obj.hue = 0;
	
    curEdit.sat = curEdit.obj.state.sat;
    curEdit.hue = curEdit.obj.state.hue / 65535;
    mapLevelToPercent(curEdit.obj);
    mapSatToPercent(curEdit.obj);
    mapCtToPercent(curEdit.obj);
    showLightEditPage();
	$(".rgb_lvl").text("Group");
}

/**
 * Updates the light parameters and display.
 * @param  {object} light the light data
 */
function updateLight(light) {
    if (typeof(light) !== 'object') {
        console.log("unexpected data " + typeof(light));
        return;
    }

    curEdit.obj = light;
    curEdit.obj.id = lightId;
    curEdit.obj.type = TYPE_LIGHT;
    curEdit.obj.hasColor = light.hascolor;
    curEdit.obj.hue = 0;

    curEdit.sat = curEdit.obj.state.sat;
    curEdit.hue = curEdit.obj.state.hue / 65535;
    mapLevelToPercent(curEdit.obj);
    mapSatToPercent(curEdit.obj);
    mapCtToPercent(curEdit.obj);
    
	if (multiId === null) {
		showLightEditPage();
	}
}

/**
 * Updates the light parameters and display of multi device white channel.
 * @param  {object} light the light data
 */
function updateLight2(light) {
    if (typeof(light) !== 'object') {
        console.log("unexpected data " + typeof(light));
        return;
    }

    curEdit2.obj = light;
    if (multiId !== null) {
		curEdit2.obj.id = multiId;
	} else if (multiIds.length > 0) {
		curEdit2.obj.id = multiIds[0];
	}
    curEdit2.obj.type = TYPE_LIGHT;

    mapLevelToPercent(curEdit2.obj);
    
	showLightEditPage();
}

function loadGroup() {
    var etag = "unknown";

    if (curEdit && curEdit.obj && curEdit.obj.etag) {
        etag = '"' + curEdit.obj.etag + '"';
    }

    $.ajax({
        url: '/api/' + apikey + '/groups/' + groupId,
        type: 'GET',
        cache: false,
        headers: {
            //'If-None-Match': etag,
            'Accept': apiversion
        },
        success: function(json, status, xhr) {
            if (xhr.status === 304) {
                return;
            }
            updateGroup(json);
			
			if (multiIds.length > 0) {
			    loadWhiteChan(0, multiIds[0]);
		    }
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log("textStatus:", textStatus + ' ' + errorThrown);
            console.log(jqXHR.responseText);
            loadGroup();
        },
        timeout: 10000
    });
}

/**
 * Loads the lights state from the gateway.
 *
 * @param {number} round - The number this function is called.
 */
function loadLight(round) {
    var etag = "unknown";

    if (curEdit && curEdit.obj && curEdit.obj.etag) {
        etag = '"' + curEdit.obj.etag + '"';
    }

    queryState = (round === 0) ? 'on,bri,color' : '';

    console.log('loadLight(' + round + ') queryState: ' + queryState)

    $.ajax({
        url: '/api/' + apikey + '/lights/' + lightId,
        type: 'GET',
        cache: false,
        headers: {
            'If-None-Match': etag,
            'Accept': apiversion,
            'Query-State': queryState
        },
        success: function(json, status, xhr) {
            // on the first call we also requested a query real state from the light
            // after the delay the gateway may have new state data of the light
            if (round === 0) {
                setTimeout('loadLight(' + round + 1 + ')', 500);
            }

            if (xhr.status === 304) {
                // try again a last time
                if (round === 1) {
                    setTimeout('loadLight(' + round + 1 + ')', 500);
                }
                return;
            }
			
			updateLight(json);
			
			if (multiId !== null) {				
				loadWhiteChan(0, multiId);
			}
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log("textStatus:", textStatus + ' ' + errorThrown);
            console.log(jqXHR.responseText);
            loadLight(round);
        },
        timeout: 10000
    });
}

function loadWhiteChan(round, id) {
    var etag = "unknown";

    if (curEdit && curEdit.obj && curEdit.obj.etag) {
        etag = '"' + curEdit.obj.etag + '"';
    }

    queryState = (round === 0) ? 'on,bri' : '';

    console.log('loadWhiteChannel(' + round + ') queryState: ' + queryState)

    $.ajax({
        url: '/api/' + apikey + '/lights/' + id,
        type: 'GET',
        cache: false,
        headers: {
            'If-None-Match': etag,
            'Accept': apiversion,
            'Query-State': queryState
        },
        success: function(json, status, xhr) {
            // on the first call we also requested a query real state from the light
            // after the delay the gateway may have new state data of the light
            if (round === 0) {
                setTimeout('loadWhiteChan(' + round + 1 + ', '+ id + ')', 500);
            }

            if (xhr.status === 304) {
                // try again a last time
                if (round === 1) {
                    setTimeout('loadWhiteChan(' + round + 1 + ', '+ id + ')', 500);
                }
                return;
            }			
			updateLight2(json);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            console.log("textStatus:", textStatus + ' ' + errorThrown);
            console.log(jqXHR.responseText);
        },
        timeout: 10000
    });
}
/**
 * Handler than the user rotates the device.
 * In landscape mode we display a notification that this is not supported.
 */
var orientationTimer;
function handleOrientation() {
    orientationTimer = undefined;
    if (Modernizr.mq('only all') && ('matchMedia' in window)) { // test if media queries are supported
        var mql = matchMedia("(orientation: portrait)");

        if (mql.matches) {
            if (!$('input').is(':focus')) {
                $('#pageLightEditLandscape').css('display', 'none');
            }
        }
        else {
            if (!$('input').is(':focus')) {
                $('#pageLightEditLandscape').css('display', 'block');
            }
        }
        adjustLevelEditPage();
    }
}

/**
 * Re/starts a delayed orientation handler to adjust size of elements
 * and if neccesary show landscape info to the user.
 */
function handleOrientationDelayed() {
    if (orientationTimer) {
        clearTimeout(orientationTimer);
    }

    orientationTimer = setTimeout(handleOrientation, 150);
}
		
$(document).ready(function() {
    lightControlInit();

    $('input').blur();

    // cache DOM values
    winInnerWidth = window.innerWidth;
    winInnerHeight = window.innerHeight;

    barSat = document.getElementById("barSat");
    barLevel = document.getElementById("barLevel");
    barLevelBig = document.getElementById("barLevelBig");
    closeEditLightsButton = document.getElementById("closeEditLightsButton");
    footer = document.querySelector('#pageLightEdit .footer');

    devNameLabel = document.getElementById('devNameLabel');

    $(devNameLabel).on('focus', function() {
       $(pageLightEdit).hide();
    });

    $(devNameLabel).on('blur', function() {
       setTimeout(function() {
            $(pageLightEdit).fadeIn(220);
            handleOrientationDelayed();
       }, 300);
    });

    if (Modernizr.sessionstorage) {
        if (sessionStorage.config) {
            config = JSON.parse(sessionStorage.config);
        }
    }

    initEditPage();
    adjustLevelEditPage();

    // show the page now (was hidden to prevent flickering while setup geometry of elements)

    if (Modernizr.mq('only all') && ('matchMedia' in window)) { // test if media queries are supported
        var mqOrientation = matchMedia("(orientation: portrait)");
        // The Listener will fire whenever this either matches or ceases to match
        // if (mqOrientation.addListener) {
        //     mqOrientation.addListener(handleOrientation);
        // }

        if (!mqOrientation.matches) {
            $('#pageLightEditLandscape').css('display', 'block');
        }
    }

    $(window).resize(handleOrientationDelayed);

    groupId = getURLParameter("group");
    lightId = getURLParameter("light");
	multiId = getURLParameter("multi");
	multiIds = JSON.parse(getURLParameter("multis"));
	
	if (((groupId === null) && (multiId !== null)) || (multiIds !== null && multiIds.length > 0)) {
		$('.multi-device').removeClass('hidden');
	}

    if (groupId !== null) {
        // load from cache
        if (typeof(config) === 'object') {
            if (config.groups) {
                if (groupId in config.groups) {
                    updateGroup(config.groups[groupId]);
                }
				if (multiIds[0] in config.lights) {
                    updateLight2(config.lights[multiIds[0]]);
                }
            }
        }

        loadGroup();
    }
    else if (lightId !== null) {
        // load from cache
        if (typeof(config) === 'object') {
            if (config.lights) {
                if (lightId in config.lights) {
                    updateLight(config.lights[lightId]);
                }
				if (multiId in config.lights) {
                    updateLight2(config.lights[multiId]);
                }
            }
        }
        loadLight(0);
    }

    // show the edit page after all elements have the proper size and position
    pageLightEdit.style.opacity=1;
});

// Support iOS virtual keyboard "done" button
function onLightEditBlur(e) {
    if (e.target.nodeName === "INPUT") {
		isFocused = false;
        setObjName(e.target);
    }
}

function onLightEditFocus(e) {
    if (e.target.nodeName === "INPUT") {
        isFocused = true;
    }
}	
  
$('body').on('keydown', '#devNameLabel', function(event) {
	if(event.keyCode == 13) {
		if (event.target.nodeName === "INPUT") {
			isFocused = false;
            event.target.blur();
			event.preventDefault();
			return false;
		}
	}
});

function doColorLoopSpeedModal(speed) {
	activateColorloop(speed);
    $('#colorLoopBtn').text('Stop Color Loop');
	$('#colorLoopBtn').addClass('colorLoopShadow');
	$('#selectColorLoopSpeedModal').modal('hide');
}
	