
// a list of all lights
var lightArr = [];
var pageLightListScrollY = 0;

function recalcAllLevels(lights) {
    for (var i = 0; i < lights.length; i++) {
        mapLevelToPercent(lights[i]);
        mapSatToPercent(lights[i]);
    }
};

function copyLight(dst, src) {
    if (src.name !== undefined) {
        dst.name = src.name;
    }

    if (src.state.on !== undefined) {
        dst.state.on = src.state.on;
    }

    if (src.state.hue !== undefined) {
        dst.state.hue = src.state.hue;
    }

    if (src.state.sat !== undefined) {
        dst.state.sat = src.state.sat;
    }

    if (src.state.satPercent !== undefined) {
        dst.state.satPercent = src.state.satPercent;
    }

    if (src.state.bri !== undefined) {
        dst.state.bri = src.state.bri;
    }

    if (src.state.levelPercent !== undefined) {
        dst.state.levelPercent = src.state.levelPercent;
    }
};


// check for changes and update device list ui
function updateDeviceListUi() {
    for (var i = 0; i < lightArr.length; i++) {
        
        $('.light_item').each(function() {
            if (this.dataset.lidx !== undefined) {
                var lidx = this.dataset.lidx;
                var light = lightArr[lidx];
                var onOffButton = $('.onoff_button', this);
                var levelLabel = $('.light_level', this);

                if (light.state.on === true) {
					if (light.state.effect == "colorloop") {
						$(onOffButton).addClass('light_colorloop');
					} else {
						$(onOffButton).addClass('light_on');
					}
                }
                else {
                    $(onOffButton).removeClass('light_on');   
					$(onOffButton).removeClass('light_colorloop'); 
                }

                levelLabel.text(Math.ceil(light.state.levelPercent) + '%');

                var nameLabel = $('.name', this);
                if (nameLabel.text() !== light.name) {
                    nameLabel.text(light.name);
                }
            }
        });
    }
}

// update lights
function updateLights() {
    var lights = [];
    if (config && config.lights) {
        for (var id in config.lights) {
            var l = config.lights[id];
            l.type = TYPE_LIGHT;
            l.id = id;
            mapLevelToPercent(l);
            mapSatToPercent(l);
        }
    }
}

function getHiddenProp(){
    var prefixes = ['webkit','moz','ms','o'];
    
    // if 'hidden' is natively supported just return it
    if ('hidden' in document) return 'hidden';
    
    // otherwise loop over all the known prefixes until we find one
    for (var i = 0; i < prefixes.length; i++){
        if ((prefixes[i] + 'Hidden') in document) 
            return prefixes[i] + 'Hidden';
    }

    // otherwise it's not supported
    return null;
}

// check if lights are updated on the server
function checkUpdateLights() {
        return; // TODO reactivate with new API
};

function showLightListPage() {
    curPage = pageLightList;

    //pageLightList.style.visibility = 'visible';
    // pageLightList.style.display = 'block';
    $(pageLightList).removeClass("pageHide");

    if (needReload) {
        needReload = false;
        var forceGet = true;
        location.reload(forceGet);
    }
}

function hideLightListPage() {
    pageLightListScrollY = window.scrollY;
    //pageLightList.style.visibility = 'hidden';
    // pageLightList.style.display = 'none';
    $(pageLightList).addClass("pageHide");
}


/**
 * displays lights in undef location when they are in no group.
 */
function addLightToUndefLocation(l) {
	var disabled = "";
	var reachable = "";
	var href = "#addToGroupModal";
	var contains = false;
	if (l.state.reachable == false) {
		disabled = " disabled ";
		reachable = "not_reachable";
		href = "";
	}

	$("#undefContent tr").each(function() {
		if ($(this).attr("data-ulid") == l.id) {
			contains = true;
			return false;			
		}
	});
	
	if (contains == false) {
		//make new entry
		txt = '<tr class="undef '+ reachable +'" data-ulid="' + l.id + '">';
		txt += '<td class="undef-name" tyle="vertical-align: middle;white-space: normal;">';
		txt += l.name;
		txt += '</td>';
		if (l.modelid == "") {
			txt += '<td class="modelid" style="vertical-align: middle;white-space: normal;"><img src="img/loading.gif"/></td>';
			var lid = l.id;
			setTimeout(function(){
				if ($('tr.undef[data-ulid=' + lid + '] td:nth-child(2)').html().indexOf("img/loading.gif") != -1 ) {
					$('tr.undef[data-ulid=' + lid + '] td:nth-child(2)').html("Unknown");
				}
			},10000);
		} else {	
			txt += '<td class="modelid" style="vertical-align: middle;white-space: normal;">' + l.modelid + '</td>';
		}
		txt += '<td><a data-ulid="' + l.id + '" data-name="' + l.name + '" id="addToGroup" class="addToGroup' + disabled + '" style="margin-top:-5px;float:right;" href="' + href + '" data-toggle="modal"><div class="btn">+</div></a></td>';
		txt += '</tr>';
		$('#undefContent').append(txt);		
	} else if (contains == true && l.modelid != "") {
		//update modelid
		$('tr[data-ulid=' + l.id + '] td.modelid').html(l.modelid);
	}

	return false;	
}

/**
 * Check if light is in a group. If it is in no group, add it to #undefLocation <div>.
 */
function checkLightInGroup(light) {
	var lightInGroup = false;
	for (var gid in config.groups) {
		for (var lid in config.groups[gid].lights) {
			if (config.groups[gid].lights[lid] == light.id) {
				lightInGroup = true;
				$('tr.undef[data-ulid=' + light.id + ']').remove();
				break;
			}
		}
	}
	
	if (lightInGroup == false) {
		addLightToUndefLocation(light);
	}
	return false;
}

function adjustUndefLightNames() {
    $('#undefLocation').each(function(index) {
            var maxwidth = $(this).innerWidth() - 200;
            $('tr.undef td:nth-child(1)').each(function(index) {
                $(this).css('max-width', maxwidth + 'px');
            });
    });
}

/**
 * Check multi-devices and do something
 */
 
 