var lightId = undefined;
var apikey = null;
var apiversion = 'vnd.ddel.v1';
var CONN_REFRESH = 10000;
var currTimeout = 0;
var config;
var isFocused = false;

initApi();

// check if the browser window is hidden
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;
}

function isHidden() {
    var prop = getHiddenProp();
    if (!prop) return false;

    return document[prop];
}

var visProp = getHiddenProp();
if (visProp) {
  var evtname = visProp.replace(/[H|h]idden/,'') + 'visibilitychange';
  document.addEventListener(evtname, visChange);
}

/**
* Don't update when browser tap is hidden
*/
function visChange() {
        if (isHidden()) {
			CONN_REFRESH = 999999;
		} else {
		    //if visible
	        CONN_REFRESH = 10000;
			    if (currTimeout === 999999) {
				    if (window.location.pathname == "/connectivity.html") {
				  	  setTimeout(getConfiguration, 3000);
				    } else {
				  	  setTimeout(getConnectivity, 3000);
				    }
			    }
		}
}

/**
 * Init touch and small displays.
 */
function connectivityInit() {
    // check if this is mobile or desktop
    // and load custom js and css files
    if (Modernizr.touch) {
        loadjscssfile("mobile.css", "css");
        isDesktop = false;
    }
    else {
        isDesktop = true;
        loadjscssfile("desktop.css", "css");
    }

    if (Modernizr.touch) {
        clickevent = "touchend";
        pointerStart = "touchstart";
        pointerEnd = "touchend";
        pointerMove = "touchmove";
    }
}

/**
 * Init the base branding of the interface.
 */
function initBranding() {

    var customBrand = false;

    var navName = "Wireless Light";

    if (customBrand) {
        var navName = "CUSTOM <span style=\"position: relative; display: inline-block; bottom: 8px;\">&reg;</span>";
        var brand = '<span class="custom-brand">' + navName + '</span>';
        $(".navbar-inner .brand").html(brand);
    }
}

/**
 * map 0-255 lqi range into 5 classes
 */
function mapConnectivityToFive(obj) {
    if (!obj) {
        return;
    }

    if (obj.connectivity === undefined) {
        obj.connectivity = 0;
    }

    obj.connectivity = Math.ceil(obj.connectivity);

    if (obj.connectivity < 90) { //90
        obj.connectivity5 = "bad";
    } else if ((obj.connectivity >= 90) && (obj.connectivity < 170)) { // 90 170
		obj.connectivity5 = "bame";
	} else if ((obj.connectivity >= 170) && (obj.connectivity < 200)) { // 170 200
		obj.connectivity5 = "medium";
	} else if ((obj.connectivity >= 200) && (obj.connectivity < 230)) { // 200 230
		obj.connectivity5 = "mego";
	} else if (obj.connectivity >= 230) { // 230
		obj.connectivity5 = "good";
	}
}

/**
* adds html of the submenu to the page.
*/
function showConnectivitySubmenu(light) {
	clearAlert();
    var rowtxt="";

	rowtxt += '<div class="location span6" style="margin-left:0px; max-width:280px;">';
    rowtxt += '<div class="row-fluid" align="center">';
	rowtxt += '<span class="btn  identifyButton" data-lid="' + light.id + '" style="margin: 15px 0px;">identify</span>';
    rowtxt += detailedLightToHtml(light);
	rowtxt += '<a href="connectivity.html"><span class="btn  actionButton doneButton"'+
     	      'data-action="close" style="margin: 15px 0px;">done</span></a>';
	rowtxt += '</div>';
	rowtxt += '</div>';

	pageLightList.innerHTML = "";
    pageLightList.innerHTML += rowtxt;

    adjustLightNames();
}

/**
* adds html to the connectivity index page.
* adds new data or updates table row if connectivity changed.
*/
function showConnectivity(light) {
	clearAlert();

    var rowtxt="";
	var reachableClass = light.reachable ? " " : "not_reachable ";
	var connStorageKey = "connectivity"+light.id;
	var connStorageObject = {};
	var conn_img = "";

	mapConnectivityToFive(light);

	if (light.connectivity5 === "bad") {
		conn_img = "conn1.png";
	} else if (light.connectivity5 === "bame") {
		conn_img = "conn2.png";
	} else if (light.connectivity5 === "medium") {
		conn_img = "conn3.png";
	} else if (light.connectivity5 === "mego") {
		conn_img = "conn4.png";
	} else {
		conn_img = "conn5.png";
	}

	if (light.reachable === false) {
		conn_img = "conn0.png";
	}

	if (Modernizr.sessionstorage) {
		connStorageObject = JSON.parse(sessionStorage.getItem(connStorageKey));
	}

	light.conn_img = conn_img;

	if (connStorageObject.conn_img === undefined) {
	//make new entry
		rowtxt += '<div class="location span6" style="margin-left:0px;">';
		rowtxt += '<div class="row-fluid">';
		rowtxt += lightToHtml(light);
		rowtxt += '</div>';
		rowtxt += '</div>';

		$("#pageLightList").append(rowtxt);
		adjustLightNames();

	} else if (connStorageObject.conn_img != conn_img) {
	//update light
		$("[data-lid='"+ light.id +"']").removeClass("not_reachable");
		$("[data-lid='"+ light.id +"']").addClass(reachableClass);
		$("[data-lid='"+ light.id +"'] > .light_level").html("<img src=\"/img/" + light.conn_img + "\">");
		adjustLightNames();
	} else {
	//do nothing
	}

	connStorageObject.conn_img = conn_img;

	if (Modernizr.sessionstorage) {
		sessionStorage.setItem(connStorageKey, JSON.stringify(connStorageObject));
	}
}

/**
* light-connectivity-information to html for the connectivity-main-page
*/
function lightToHtml(light) {
	var reachableClass = light.reachable ? " " : "not_reachable ";
    var txt = "";

	txt += '<table>';
    txt += '<tbody>';
    txt += "<tr class=\"" + reachableClass + "light_item\" data-lid=\"" + light.id + "\">";
    txt += "<td class=\"onoff_button light_on\" data-lid=\"" + light.id + "\"></td>";
	txt += "<td class=\"light_level\"><img src=\"/img/" + light.conn_img + "\"></td>";
    txt += "<td class=\"name\">" + light.name + "</td>";
    txt += "<td class=\"edit_button\" data-lid=\"" + light.id + "\"></td>";
    txt += "</tr>";
	txt += '</tbody>';
    txt += '</table>';

    return txt;
}

/**
* detailed light-connectivity-information to html for the submenu
*/
function detailedLightToHtml(light) {
	mapConnectivityToFive(light);

	if (light.connectivity5 === "bad") {
		conn_img = "conn1.png";
	} else if (light.connectivity5 === "bame") {
		conn_img = "conn2.png";
	} else if (light.connectivity5 === "medium") {
		conn_img = "conn3.png";
	} else if (light.connectivity5 === "mego") {
		conn_img = "conn4.png";
	} else {
		conn_img = "conn5.png";
	}

	var key, countNeighbours = 0;
	for(key in light.neighbours) {
	  if(light.neighbours.hasOwnProperty(key)) {
		countNeighbours++;
	  }
	}
    var txt = "";
	txt += '<table border="0" style="max-width:280px;"><thead><th></th><th></th></thead>';
    txt += '<tbody>';
	txt += "<tr>";
	txt += "<td colspan=\"2\" align=\"center\"><form class=\"navbar-form\"><input id=\"devNameLabelBig\" type=\"text\" " +
  	       "style=\"margin-left:0px; max-width:200px;\" maxlength=\"32\" value=\"" + light.name + "\"></form></td>";
	txt += "</tr>";
	txt += "<tr>";
	//txt += "<td colspan=\"2\">ID: " + light.id + "</td>";
	txt += "</tr>";
	txt += "<tr><td> &nbsp; </td></tr>";
	txt += "<tr>";
    txt += "<td>gateway connectivity: </td><td align=\"center\"><img src=\"/img/" + conn_img + "\"></td>";
    txt += "</tr>";
	//txt += "<tr>";
    //txt += "<td>number of routes: </td><td align=\"center\">" + light.routesToGateway + "</td>";
    //txt += "</tr>";
	txt += "<tr><td> &nbsp; </td></tr>";
	txt += "<tr>";
    txt += "<td>neighbours: </td><td align=\"center\">" + ((countNeighbours == 0) ? "0" : " ") + "</td>";
    txt += "</tr>";

	for(key in light.neighbours){
		mapConnectivityToFive(light.neighbours[key]);

		if (light.neighbours[key].connectivity5 === "bad") {
			conn_img = "conn1.png";
		} else if (light.neighbours[key].connectivity5 === "bame") {
			conn_img = "conn2.png";
		} else if (light.neighbours[key].connectivity5 === "medium") {
			conn_img = "conn3.png";
		} else if (light.neighbours[key].connectivity5 === "mego") {
			conn_img = "conn4.png";
		} else {
			conn_img = "conn5.png";
		}

		txt += "<tr>";
		txt += "<td>&nbsp;&nbsp; &#9830; " + light.neighbours[key].name + ": </td><td><img src=\"/img/" + conn_img + "\">";
		txt += "</tr>";
	}
	txt += '</tbody>';
    txt += '</table>';

    return txt;
}

/**
 * Helper to adjust the size of the name field to not exceed the table size.
 */
function adjustLightNames() {
    $('.location').each(function(index) {
        if (index > 0) {
            var maxwidth = $(this).innerWidth() - 180;
            $('.light_item td:nth-child(3)').each(function(index) {
                $(this).css('max-width', maxwidth + 'px');
            });
        }
    });
}

/**
* /lights/id/state
* @param id {String} id of the light
* @param onoff {bool} sets state lslect or none
*/
function identifyLight(id,onoff) {
	var params;
	if (onoff === true) {
		params = '{ "alert" : "lselect" }';
	} else {
		params = '{ "alert" : "none" }';
	}

    $.ajax({
        url: 'api/' + apikey + '/lights/' + id + '/state',
        dataType: 'json',
        type: 'PUT',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        headers: { 'Accept': apiversion },
        data: params,
        success: function(json) {
			if (onoff === true) {
				$("td[data-lid='" + id + "']:first-child").removeClass("light_on");
				$("td[data-lid='" + id + "']:first-child").addClass("light_blink");
				$(".identifyButton").html("stop blinking");
			} else {
				$("td[data-lid='" + id + "']:first-child").removeClass("light_blink");
				$("td[data-lid='" + id + "']:first-child").addClass("light_on");
				$(".identifyButton").html("identify");
			}
        },
        error: function(jqXHR, textStatus, errorThrown) {
            showAlert('alert-error', '<b>Error!</b>');
        }
    });
}

/**
* /lights/id/connectivity
* @param lid {String} the light id
*/
function getConnectivity(lid) {
var curId = ""
	if (!lightId || lightId === undefined){
		curId = lid;
	} else {
		curId = lightId;
	}
    $.ajax({
        url: 'api/' + apikey + '/lights/' + curId + '/connectivity',
        dataType: 'json',
        type: 'GET',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        headers: { 'Accept': apiversion },
        data: '',
        success: function(json, status, xhr) {
			curEdit.obj = json;
			curEdit.obj.id = curId;
			curEdit.obj.type = TYPE_LIGHT;

			//make available for caching
			if (Modernizr.sessionstorage) {
				if (sessionStorage.getItem("connectivity"+lid) === null || sessionStorage.getItem("connectivity"+lid) === undefined) {
					sessionStorage.setItem("connectivity"+lid, xhr.responseText);
				}
            }

			if (!lightId || lightId == undefined){
				showConnectivity(curEdit.obj);
			} else {
				if (on_off === false && isFocused === false)  {
					showConnectivitySubmenu(curEdit.obj);
				}
					currTimeout = CONN_REFRESH;
					setTimeout(getConnectivity, CONN_REFRESH);
			}
        },
        error: function(jqXHR, textStatus, errorThrown) {
            switch (jqXHR.status) {
            case 403:
              window.location.assign("/pwa/login.html");
              break;

            case 404: // not found go back
              window.location.assign("/");
              break;

            default:
              setTimeout(getConnectivity, 3000);
              showAlert('alert-error', '<b>Error!</b> Loading data, retry in three seconds ...');
              break;
            }
        },
		timeout: 10000
    });
}

/**
* get configuration, then get connectivity for each light in configuration.
* /api/apikey
*/
function getConfiguration() {
	$.ajax({
        url: 'api/' + apikey,
        dataType: 'json',
        type: 'GET',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        headers: { 'Accept': apiversion },
        success: function(json, status, xhr) {
            config = json;
            config.etag = xhr.getResponseHeader("ETag");

			var key = 0;
			for(key in config.lights) {
			  if(config.lights.hasOwnProperty(key)) {
				getConnectivity(key);
			  }
			}
			currTimeout = CONN_REFRESH;
			setTimeout(getConfiguration, CONN_REFRESH);
        },
        error: function(jqXHR, textStatus, errorThrown) {
            switch (jqXHR.status) {
            case 403:
                window.location.assign("/pwa/login.html");
                break;

            default:
                setTimeout(getConfiguration, 3000);
                showAlert('alert-error', '<b>Error!</b> Lost connection, retry in one second ...');
                break;
            }
        },
        timeout: 10000
    });
}

// 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;
    }
}

$(document).on('keydown', '.navbar-form #devNameLabelBig', function(event) {
	if(event.keyCode == 13) {
		if (event.target.nodeName === "INPUT") {
			isFocused = false;
            event.target.blur();
			event.preventDefault();
			return false;
		}
	}
});
