var bigMap = {
  "top": 0,
  "left": 0,
  "x": 0,
  "y": 0,
  "pageX": 0,
  "pageY": 0,
  "width": 0,
  "height": 0,
  "hue": 0,
  "sat": 0,
  "ct": 0,
  "level": 0
};

var groupId = undefined;
var lightId = undefined;
var multiId = undefined;
var mapMove = false;
var touches0 = undefined;
var touchStartEvent = undefined;

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

var canvas0ClientWidth = 0;
var canvas0ClientHeight = 0;
var canvasColorClientWidth = 0;
var canvasColorClientHeight = 0;

var devNameLabel = undefined;
var devNameLabelBig = undefined;
var satStateLabel = undefined;
var satStateLabelValue = undefined;
var levelStateLabel = undefined;
var levelStateLabelValue = undefined;
var colorMap = undefined;
var colorMapBig = undefined;
var colorPos;
var checkLongSendTimer = undefined;

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search)||[,""])[1].replace(/\+/g, '%20'))||null;
}

function findPos(obj) {
    var curleft = 0, curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj == obj.offsetParent);
        return { x: curleft, y: curtop };
    }
    return undefined;
}

function getTouchPos(e) {
    var t0 = e;
    // handle touch devices
    if (e.changedTouches !== undefined) {
        if (e.changedTouches.length === 0) {
            return;
        }

        t0 = e.changedTouches[0];
    }
	var mouseX = e.clientX;
    var dx = t0.pageX - bigMap.pageX;
    var dy = t0.pageY - bigMap.pageY;
    bigMap.pageX = t0.pageX;
    bigMap.pageY = t0.pageY;
    bigMap.x = t0.pageX - colorMapBig.offsetLeft;//; - bigMap.left;
    bigMap.y = t0.pageY - colorMapBig.offsetTop;

    if (isDesktop) {
        // bigMap.x -= bigMap.left;
    }

    if (moveType == MOVE_COLOR) {
        if (bigMap.x < 0) {
          bigMap.x = 0;
        }
        else if (bigMap.x > bigMap.width) {
          bigMap.x = bigMap.width;
        }

        if (bigMap.y < 0) {
          bigMap.y = 0;
        }
        else if (bigMap.y > bigMap.height) {
          bigMap.y = bigMap.height;
        }

        // hue
        if (bigMap.x > 0) {
          bigMap.hue = bigMap.x / bigMap.width;
        }
        else {
          bigMap.hue = 0;
        }

        // sat
        if (bigMap.y > 0) {
            var fak = (bigMap.y/ bigMap.height);
            bigMap.sat = 1 - (fak * fak);
        }
        else {
            bigMap.sat = 1 - 0;
        }

        if (colorEditMode === EDIT_MODE_COLOR) {
            sendHue = true;
            sendSat = true;
            curEdit.hue = bigMap.hue;
            curEdit.sat = Math.floor(bigMap.sat * 255);
        }
        else if (colorEditMode === EDIT_MODE_COLOR_TEMPERATURE) {
            sendColorTemp = true;
            // TODO the min max of ct is dependend on the light and shall not be fixed.
            // mired color temperature
            var ctMin = 153;
            var ctMax = 500;
            var ct = 1 - bigMap.hue;
            curEdit.ct = Math.floor((ct * (ctMax - ctMin)) + ctMin);
        }
    } else if (moveType === MOVE_LEVEL) {
		//click on main level slider
		var margin = $("#barLevelBigWrapper").css("margin-left");
		var wrapperX = ($("#barLevelBigWrapper").position().left) + parseInt(margin);
		var wrapperWidth = $("#barLevelBigWrapper").width();
		curEdit.levelPercent = ((mouseX - wrapperX) / wrapperWidth)*100;

		if (curEdit.levelPercent < 0)
			curEdit.levelPercent = 0;
		else if (curEdit.levelPercent > 100)
			curEdit.levelPercent = 100;

		curEdit.level = Math.floor(curEdit.levelPercent / 100 * 255);

		if (curEdit.level < 0)
		  curEdit.level = 0;
		else if (curEdit.level > 255)
		  curEdit.level = 255;

		curEdit.obj.levelPercent = curEdit.levelPercent
		curEdit.obj.level = curEdit.level

		// check if level changed on/off state
		if (curEdit.obj.state.on === true && curEdit.level === 0) {
			curEdit.obj.state.on = false;
		}
		else if (curEdit.obj.state.on === false && curEdit.level > 0) {
			curEdit.obj.state.on = true;
		}

		sendLevel = true;
		editNeedRender = true;

	//second level bar for multidevice whitechannel
	} else if (curEdit2.obj != undefined && moveType === MOVE_LEVEL_WHITE) {
		var margin2 = $("#barLevelBigWrapper2").css("margin-left");
		var wrapperX2 = ($("#barLevelBigWrapper2").position().left) + parseInt(margin2);
		var wrapperWidth2 = $("#barLevelBigWrapper2").width();

		curEdit2.levelPercent = ((mouseX - wrapperX2) / wrapperWidth2)*100;

		if (curEdit2.levelPercent < 0)
			curEdit2.levelPercent = 0;
		else if (curEdit2.levelPercent > 100)
			curEdit2.levelPercent = 100;

		curEdit2.level = Math.floor(curEdit2.levelPercent / 100 * 255);

		if (curEdit2.level < 0)
		  curEdit2.level = 0;
		else if (curEdit2.level > 255)
		  curEdit2.level = 255;

		curEdit2.obj.levelPercent = curEdit2.levelPercent
		curEdit2.obj.level = curEdit2.level

		// check if level changed on/off state
		if (curEdit2.obj.state.on === true && curEdit2.level === 0) {
			curEdit2.obj.state.on = false;
		}
		else if (curEdit2.obj.state.on === false && curEdit2.level > 0) {
			curEdit2.obj.state.on = true;
		}

		sendLevel2 = true;
		editNeedRender2 = true;
	}
}

function renderBarLevelBig() {
	var wrapperWidth = $("#barLevelBigWrapper").width();

    barLevelBig.style["width"] = (wrapperWidth * (curEdit.levelPercent / 100)) + "px";
	if (multiIds !== null && multiIds.length > 0) {
		barLevelBig2.style["width"] = (wrapperWidth * (curEdit.levelPercent / 100)) + "px";
		if ($('#barLevelBig').css('background-color') == "rgb(161, 161, 161)") {
			$('#barLevelBig2').css('background-color','#A1A1A1');
		} else {
			$('#barLevelBig2').css('background-color','#ffffff');
		}
	}
}

function renderBarLevelBig2() {
	var wrapperWidth = $("#barLevelBigWrapper2").width();
	if (curEdit2.obj === undefined) {
		barLevelBig2.style["width"] = (wrapperWidth * (0.5)) + "px";
	} else {
		barLevelBig2.style["width"] = (wrapperWidth * (curEdit2.levelPercent / 100)) + "px";
	}
}

function checkLongSend() {
    if (moveType === MOVE_COLOR) {
        if (colorEditMode === EDIT_MODE_COLOR) {
            sendHue = true;
            sendSat = true;
            sendColorTemp = false;
        }
        else if (colorEditMode === EDIT_MODE_COLOR_TEMPERATURE) {
            sendHue = false;
            sendSat = false;
            sendColorTemp = true;
        }
    }
    else if (moveType === MOVE_LEVEL) {
        sendLevel = true;
    }

    if (sendCheckerActive) {
          checkLongSendTimer = setTimeout(checkLongSend, 2000);
    }
}

function updateColorPos(e) {

    if (moveType === MOVE_COLOR) {
        var rad = colorPos.offsetWidth / 2;
        var top = e.pageY;
        var left = e.pageX;
        var mapX = colorMapBig.offsetLeft;
        var mapY = colorMapBig.offsetTop;
        var mapX2 = mapX + colorMapBig.width;
        var mapY2 = mapY + colorMapBig.height;

        // check top/left
        top = (mapY > top) ? mapY : top;
        left = (mapX > left) ? mapX : left;
        // check bottom/right
        top = (mapY2 < top) ? mapY2 : top;
        left = (mapX2 < left) ? mapX2 : left;

        $(colorPos).css('top', top - rad).css('left', left - rad);
    }
}

function onBigMapTouchStart(e) {
    stopSendCheck();
    sendCheckerActive = true;
    sendCheck();

    touchStartEvent = e;
    getTouchPos(e);

    if (e.target == colorMapBig || e.target == colorPos) {
        setIsEditing(true);
        mapMove = true;
        moveType = MOVE_COLOR;
        updateColorPos(e);
        $(colorPos).addClass('draggingPos');
        e.preventDefault();
    }
    else if (e.target.nodeName === "INPUT" || e.target.nodeName === "IMG") {

    }
    else if (e.target.nodeName === "BUTTON" || e.target.nodeName === "SELECT") {

    }

    else if (e.pageY > barLevelBig.offsetParent.offsetTop && e.pageY < barLevelBig2.offsetParent.offsetTop && e.target.nodeName !== "SPAN") {
        setIsEditing(true);
        mapMove = true;
        moveType = MOVE_LEVEL;
        e.preventDefault();
    } else if (e.pageY > barLevelBig2.offsetParent.offsetTop && e.pageY < barLevelBig2.offsetParent.offsetTop + 48) {
        setIsEditing(true);
        mapMove = true;
        moveType = MOVE_LEVEL_WHITE;
        e.preventDefault();
    }
}

function onBigMapTouchEnd(e) {
    mapMove = false;
    $(colorPos).removeClass('draggingPos');

    if (touchStartEvent === undefined) {
      return;
    }

    if (e.target === touchStartEvent.target) {
        if (e.target.nodeName == "INPUT") {
            e.target.focus();
            return;
        }

        var action = $(e.target).data("action");
        setIsEditing(false);

        if (action !== undefined) {
            if (action === "close") {
              //history.back();
              stopSendCheck();
              location.href = '/'; // go back but reload dynamic data
              return;
            }
        }
    }

    if (moveType !== MOVE_NONE) {
        getTouchPos(e);
        updateColorPos(e);
        e.preventDefault();
        sendState();
    }

    moveType = MOVE_NONE;
}

function onBigMapTouchMove(e) {
  if (mapMove) {
    getTouchPos(e);
    updateColorPos(e);
    e.preventDefault();
  }
}

function renderBigMap(t) {
    if (editNeedRender) {
        editNeedRender = false;
        renderBarLevelBig();
    }
	if (editNeedRender2) {
        editNeedRender2 = false;
        renderBarLevelBig2();
    }

    //if (curPage === pageLightEditMap) {
        requestAnimationFrame(renderBigMap);
    //}
}

/**
 * Draws the hue/saturation or color temperature map into the canvas.
 */
function drawMap() {
    var ctx0 = colorMapBig.getContext("2d");
    var can = ctx0.canvas;
    var p = can.parentElement;

    if (isDesktop) {
       bigMap.height = 320;
       can.style.width =  100 + "%";
       can.style.height = bigMap.height + "px";
    }
    else {
       bigMap.height = 260;
       can.style.width =  100 + "%";
       can.style.height = bigMap.height + "px";
    }

    //bigMap.width = can.clientWidth - 24;
    bigMap.width = can.clientWidth - 0;

    can.width = bigMap.width;
    can.height = bigMap.height;

    if (curEdit.obj && curEdit.obj.hasColor) {
        if (colorEditMode === EDIT_MODE_COLOR) {
            var gradH0 = ctx0.createLinearGradient(0, 0, bigMap.width, 0);
            gradH0.addColorStop(0,'hsl(0,100%,50%)');
            var hue = 0;
            var step = 0;
            for (hue; hue < 360; hue++) {
                step = hue / 360;
                gradH0.addColorStop(step,'hsl(' + hue + ',100%,50%)');
            }
            ctx0.fillStyle = gradH0;
            ctx0.fillRect(0, 0, bigMap.width, bigMap.height);

            // fading
            grad0 = ctx0.createLinearGradient(0, 0, 0, bigMap.height);
            grad0.addColorStop(0,'hsla(0,0%,100%,0)');
            grad0.addColorStop(0.3,'hsla(0,0%,100%,0)');
            grad0.addColorStop(1,'hsla(0,0%,100%,1)');
            ctx0.fillStyle = grad0;
            ctx0.fillRect(0, 0, bigMap.width, bigMap.height);
        }
        else if (colorEditMode === EDIT_MODE_COLOR_TEMPERATURE) {
            var gradH0 = ctx0.createLinearGradient(0, 0, bigMap.width, 0);
            gradH0.addColorStop(0,'hsl(37,85%,70%)');
            gradH0.addColorStop(1,'hsl(240,100%,70%)');
            ctx0.fillStyle = gradH0;
            ctx0.fillRect(0, 0, bigMap.width, bigMap.height);
        }
    }

    var pos = findPos(can);
    if (pos !== undefined) {
      bigMap.left = pos.x;
      bigMap.top = pos.y;
    }
}

function showLightEditMapPage() {
  //$(pageLightEditMap).removeClass("pageHide");
  //adjustWindowSize();
  moveType = MOVE_NONE;
  detectVendorPrefixes();
  drawMap();
  editNeedRender = true;
  touchStartEvent = undefined;

  //curPage = pageLightEditMap;

  sendLevel = false;
  sendSat = false;
  sendHue = false;
  sendColorTemp = false;
  devNameLabelBig.value = curEdit.obj.name;
  curEdit.levelPercent = curEdit.obj.levelPercent;
  if (curEdit2.obj !== undefined) {
	curEdit2.levelPercent = curEdit2.obj.levelPercent;
  }
  curEdit.satPercent = curEdit.obj.satPercent;
  curEdit.hue = curEdit.obj.state.hue;
  curEdit.sat = curEdit.obj.state.sat;
  curEdit.ct = curEdit.obj.state.ct;

    if (curEdit.obj.hasColor) {
        colorMapBig.style.visibility = "";
        colorPos.style.visibility = "";
    }
    else {
        // hide but space is occupied
        colorMapBig.style.height = "160px";
        colorMapBig.style.visibility = "hidden";
        colorPos.style.visibility = "hidden";
    }

  editNeedRender = true;
  requestAnimationFrame(renderBigMap);

//   $(colorMap).removeClass('colorMapHidden');

   document.addEventListener("blur", onLightEditBlur, true);
   document.addEventListener("keyup", onLightEditKeyup, true);

   sendCheckerActive = true;
   sendCheck();
   checkLongSend();

   $(barLevelBig).fadeIn(200);
   renderBarLevelBig();

   if (curEdit2.obj !== undefined && multiIds === null) {
       if (Modernizr.localstorage && (localStorage.getItem("whitebar-"+lightId) != undefined)) {
	       var whitebar = localStorage.getItem("whitebar-"+lightId);
		   if (whitebar == "hidden") {
		       $('#barLevelBigWrapper2').addClass('hidden');
			   $('.hide-white-bar-btn').removeClass('active');
			   //$('.hide-white-bar-btn').text('show White Channel');
		   } else {
		       $('#barLevelBigWrapper2').removeClass('hidden');
			   $('.hide-white-bar-btn').addClass('active');
			   //$('.hide-white-bar-btn').text('hide White Channel');
			   renderBarLevelBig2();
		   }
	   } else {
		   $('#barLevelBigWrapper2').removeClass('hidden');
		   renderBarLevelBig2();
	   }
   } else if (multiIds !== null && multiIds.length > 0) {
       if (Modernizr.localstorage && (localStorage.getItem("whitebarGroup-"+groupId) != undefined)) {
	       var whitebar = localStorage.getItem("whitebarGroup-"+groupId);
		   if (whitebar == "hidden") {
		       $('#barLevelBigWrapper2').addClass('hidden');
			   $('.hide-white-bar-btn').removeClass('active');
			   //$('.hide-white-bar-btn').text('show White Channel');
		   } else {
		       $('#barLevelBigWrapper2').removeClass('hidden');
			   $('.hide-white-bar-btn').addClass('active');
			   //$('.hide-white-bar-btn').text('hide White Channel');
			   renderBarLevelBig2();
		   }
	   } else {
		   $('#barLevelBigWrapper2').removeClass('hidden');
		   renderBarLevelBig2();
	   }
   } else {
	   $('.hide-white-bar-btn').addClass('hidden');
   }


    var nx = 0;
    var ny = 0;

    if (colorEditMode === EDIT_MODE_COLOR) {
        nx = curEdit.obj.state.hue / 65535;
        ny = curEdit.obj.state.sat / 255;
    }
    else if (colorEditMode === EDIT_MODE_COLOR_TEMPERATURE) {
        ctMin = 153;
        ctMax = 500;

        console.log(curEdit.obj.state.ct);

        if (curEdit.obj.state.ct >= ctMin && curEdit.obj.state.ct <= ctMax) {
          nx = 1 - ((curEdit.obj.state.ct - ctMin) / (ctMax - ctMin));
        }
        ny = 0.7;
    }

    // calc back quadratic sat
    var fak = Math.sqrt(1 - ny);
    var y = fak * colorMapBig.offsetHeight;

    var e1 = {
        "pageX": (nx * colorMapBig.offsetWidth) + colorMapBig.offsetLeft,
        "pageY": y + colorMapBig.offsetTop
    };

    moveType = MOVE_COLOR;
    updateColorPos(e1);
    moveType = MOVE_NONE;
}

function hideLightEditMapPage() {
    sendCheckerActive = false;
    $(pageLightEditMap).addClass("pageHide");
    document.removeEventListener("blur", onLightEditBlur, true);
    document.removeEventListener("keyup", onLightEditKeyup, true);

    document.removeEventListener(pointerStart, onBigMapTouchStart, false);
    document.removeEventListener(pointerEnd, onBigMapTouchEnd, false);
    document.removeEventListener(pointerMove, onBigMapTouchMove, false);
};

function loadGroup() {
    $.ajax({
        url: '/api/' + apikey + '/groups/' + groupId,
        type: 'GET',
        cache: false,
        dataType: 'json',
        success: function(json) {
            clearAlert();
            curEdit.obj = json;
            curEdit.obj.type = TYPE_GROUP;
            curEdit.obj.state = json.action; // groups use "action" instead of "state"
            curEdit.obj.hasColor = true;
            mapLevelToPercent(curEdit.obj);
            mapSatToPercent(curEdit.obj);
            mapCtToPercent(curEdit.obj);

			if (window.matchMedia("(max-width: 712px)").matches) {
				  $('#colorLoopDiv2').removeClass('hidden');
			  } else {
				  $('#colorLoopDiv').removeClass('hidden');
			  }
			  if (curEdit.obj.state.effect == "colorloop") {
			      $('#colorLoopBtn').text('Stop Color Loop');
				  $('#colorLoopBtn2').text('Stop Color Loop');
				  $('#colorLoopBtn').addClass('colorLoopShadow');
				  $('#colorLoopBtn2').addClass('colorLoopShadow');
			  }
			if (multiIds.length == 0) {
			    showLightEditMapPage();
		    } else {
			    loadWhiteChannel(multiIds[0]);
		    }
        },
        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(loadGroup, 1000);
              showAlert('alert-error', '<b>Error!</b> Loading data, retry in one second ...');
              break;
            }
        },
        timeout: 10000
    });
};

function loadLight() {
    $.ajax({
        url: '/api/' + apikey + '/lights/' + lightId,
        type: 'GET',
        cache: false,
        dataType: 'json',
        success: function(json) {
          clearAlert();
          curEdit.obj = json;
          curEdit.obj.id = lightId;
          curEdit.obj.type = TYPE_LIGHT;
          curEdit.obj.hasColor = (json.state.colormode !== undefined);

		  if (curEdit.obj.hasColor && curEdit.obj.state.colormode !== "ct") {
			  if (window.matchMedia("(max-width: 712px)").matches) {
				  $('#colorLoopDiv2').removeClass('hidden');
			  } else {
				  $('#colorLoopDiv').removeClass('hidden');
			  }
			  if (curEdit.obj.state.effect == "colorloop") {
			      $('#colorLoopBtn').text('Stop Color Loop');
				  $('#colorLoopBtn2').text('Stop Color Loop');
				  $('#colorLoopBtn').addClass('colorLoopShadow');
				  $('#colorLoopBtn2').addClass('colorLoopShadow');
			  }
		  }
          // detect color temperature light
          var showColorTemperature = false;

          if (json.state.colormode === undefined) {
              $('#colorEditModeButtonGroup').addClass('hidden')
          }

          if (json.state.colormode && json.state.colormode === 'xy') {

              var x = json.state.xy[0];
              var y = json.state.xy[1];
              var z = 1.0 - x - y;

              //var Y = json.state.bri / 254; // brightness
              var Y = 1; // brightness
              var X = (Y / y) * x;
              var Z = (Y / y) * z;

              // sRGB D65 conversion
              var r =  X * 3.2406 - Y * 1.5372 - Z * 0.4986;
              var g = -X * 0.9689 + Y * 1.8758 + Z * 0.0415;
              var b =  X * 0.0557 - Y * 0.2040 + Z * 1.0570;

              if (r > b && r > g && r > 1.0) {
                  // red is too big
                  g = g / r;
                  b = b / r;
                  r = 1.0;
             }
             else if (g > b && g > r && g > 1.0) {
                // green is too big
                r = r / g;
                b = b / g;
                g = 1.0;
             }
             else if (b > r && b > g && b > 1.0) {
                // blue is too big
                r = r / b;
                g = g / b;
                b = 1.0;
             }

             // reverse gamma correction
              r = r <= 0.0031308 ? 12.92 * r : (1.0 + 0.055) * Math.pow(r, (1.0 / 2.4)) - 0.055;
              g = g <= 0.0031308 ? 12.92 * g : (1.0 + 0.055) * Math.pow(g, (1.0 / 2.4)) - 0.055;
              b = b <= 0.0031308 ? 12.92 * b : (1.0 + 0.055) * Math.pow(b, (1.0 / 2.4)) - 0.055;

             if (r < 0) r = 0;
             if (g < 0) g = 0;
             if (b < 0) b = 0;

              console.log(r + ", " +  g + ", " + b);

              var hsv = rgb2hsv(String(r*255), String(g*255), String(b*255));
              console.log(hsv);

              json.state.hue = hsv[0] / 360.0 * 65535;
              json.state.sat = hsv[1] * 255.0;

          }
          if (json.state.colormode && json.state.colormode === 'ct') {
              showColorTemperature = true;
          }
          else if (json.modelid.indexOf("FLS-H") !== -1) {
              showColorTemperature = true;
          }

          if (showColorTemperature) {
              switchMapColorEditMode(EDIT_MODE_COLOR_TEMPERATURE);
              $('button[value=ct]').button('toggle');
          }

          mapLevelToPercent(curEdit.obj);
          mapSatToPercent(curEdit.obj);
          mapCtToPercent(curEdit.obj);
          if (multiId === null) {
			  showLightEditMapPage();
		  } else if (multiId !== null) {
			  loadWhiteChannel(multiId);
		  }
        },
        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(loadLight, 1000);
              showAlert('alert-error', '<b>Error!</b> Loading data, retry in one second ...');
              break;
            }
        },
        timeout: 10000
    });
}

function loadWhiteChannel(id) {
    $.ajax({
        url: '/api/' + apikey + '/lights/' + id,
        type: 'GET',
        cache: false,
        dataType: 'json',
        success: function(json) {
          clearAlert();
          curEdit2.obj = json;
          curEdit2.obj.id = id;
          curEdit2.obj.type = TYPE_LIGHT;

          mapLevelToPercent(curEdit2.obj);
          showLightEditMapPage();
        },
        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("/");
			  curEdit2.obj = {}; //dummy
			  var state = {};
			  state.bri = 0;
			  state.on = false;
			  curEdit2.obj.state = state;
			  curEdit2.obj.id = id;
			  curEdit2.obj.type = TYPE_LIGHT;
			  mapLevelToPercent(curEdit2.obj);
			  showLightEditMapPage();
			  removeMultiDeviceFromGroup(id);
			  break;

            default:
              setTimeout(loadLight, 1000);
              showAlert('alert-error', '<b>Error!</b> Loading data, retry in one second ...');
              break;
            }
        },
        timeout: 10000
    });
}

/**
 * Handler for orientation changes.
 * @param  {MediaQueryList} mql the the media query result
 */
function handleOrientation(mql) {
    // if in editing mode do nothing
    if (document.activeElement === devNameLabelBig) {
        return;
    }

    // reload the page so the map will be regenerated
    location.reload(true);
}

/**
 * Color edit mode switcher.
 * @param  {Number} mode the new color edit mode.
 */
function switchMapColorEditMode(mode) {
    colorEditMode = mode;

    // abort ongoing sending
    sendHue = false;
    sendSat = false;
    sendLevel = false;
    sendColorTemp = false;
    moveType = MOVE_NONE;
    drawMap();
}

/**
 * Handler color edit mode switcher.
 * @param  {Event} event the button pressed event.
 */
function handleSwitchColorEditMode(event) {
	event.stopImmediatePropagation();
    if (this.value === 'ct') {
		$('[value=color]').removeClass('active');
		$(this).addClass('active');
        switchMapColorEditMode(EDIT_MODE_COLOR_TEMPERATURE);
    }
    else if (this.value === 'color') {
		$('[value=ct]').removeClass('active');
		$(this).addClass('active');
        switchMapColorEditMode(EDIT_MODE_COLOR);
    } else if (this.value === 'white') {
		if ($('#barLevelBigWrapper2').hasClass('hidden')) {
			$('#barLevelBigWrapper2').removeClass('hidden');
			$('.hide-white-bar-btn').addClass('active');
			if (Modernizr.localstorage) {
				if (multiIds !== null && multiIds.length > 0) {
					localStorage.setItem("whitebarGroup-" + groupId, "visible");
				} else {
					localStorage.setItem("whitebar-" + lightId, "visible");
				}
			}
		} else {
			$('#barLevelBigWrapper2').addClass('hidden');
			$('.hide-white-bar-btn').removeClass('active');
			if (Modernizr.localstorage) {
				if (multiIds !== null && multiIds.length > 0) {
					localStorage.setItem("whitebarGroup-" + groupId, "hidden");
				} else {
					localStorage.setItem("whitebar-" + lightId, "hidden");
				}
			}
		}
	}
}

$(document).ready(function() {
  lightControlInit();
  lightEditReset();

  $('input').blur();
  $(document).on('vmousedown', onBigMapTouchStart);
  $(document).on('vmousemove', onBigMapTouchMove);
  $(document).on('vmouseup', onBigMapTouchEnd);
  $('#colorLoopBtn').click(function(){
      var speed = $('#colorLoopSel').val();
	  if ( $('#colorLoopBtn').text() == "Start Color Loop") {
		  activateColorloop(speed);
		  $('#colorLoopBtn').text('Stop Color Loop');
		  $('#colorLoopBtn').addClass('colorLoopShadow');
	  } else {
		  activateColorloop(0);
		  $('#colorLoopBtn').text('Start Color Loop');
		  $('#colorLoopBtn').removeClass('colorLoopShadow');
	  }
  });
  $('#colorLoopBtn2').click(function(){
      var speed = $('#colorLoopSel2').val();
	  if ( $('#colorLoopBtn2').text() == "Start Color Loop") {
		  activateColorloop(speed);
		  $('#colorLoopBtn2').text('Stop Color Loop');
		  $('#colorLoopBtn2').addClass('colorLoopShadow');
	  } else {
		  activateColorloop(0);
		  $('#colorLoopBtn2').text('Start Color Loop');
		  $('#colorLoopBtn2').removeClass('colorLoopShadow');
	  }
  });

    $( 'body' ).on( 'click', '#colorEditModeButtonGroup .btn', handleSwitchColorEditMode);
	//$( 'body' ).on( 'click', '#hide-white', hideBar);

    devNameLabel = document.getElementById('devNameLabel');
    devNameLabelBig = document.getElementById('devNameLabelBig');

    colorMap = document.getElementById("colorMap");
    colorMapBig = document.getElementById("colorMapBig");
    colorPos = document.getElementById("colorPos");

    drawMap(); // initial to get real size
    $(colorMapBig).fadeIn(300);

    var mqOrientation = window.matchMedia("(orientation: portrait)");
    if (mqOrientation.addListener) {
        // The Listener will fire whenever this either matches or ceases to match
        mqOrientation.addListener(handleOrientation);
    }

    groupId = getURLParameter("group");
    lightId = getURLParameter("light");
	multiId = getURLParameter("multi");
	multiIds = JSON.parse(getURLParameter("multis"));

    if (groupId !== null) {
        loadGroup();
    }
    else if (lightId !== null) {
        loadLight();
    }

});

function hideBar() {
	if ($('#barLevelBigWrapper2').hasClass('hidden')) {
		$('#barLevelBigWrapper2').removeClass('hidden');
		$('.hide-white-bar-btn').addClass('active');
		if (Modernizr.localstorage) {
			localStorage.setItem("whitebar-" + lightId, "visible");
		}
	} else {
		$('#barLevelBigWrapper2').addClass('hidden');
		$('.hide-white-bar-btn').removeClass('active');
		if (Modernizr.localstorage) {
			localStorage.setItem("whitebar-" + lightId, "hidden");
		}
	}
}

function removeMultiDeviceFromGroup(id) {
    $.ajax({
        url: '/api/' + apikey + '/groups/' + groupId,
        type: 'GET',
        cache: false,
        dataType: 'json',
        success: function(json) {
			var lights = json.lights;
			var mutiIds = json.multideviceIds;

			//removeMultiDeviceFromGroupStep2(id);
        },
        error: function(jqXHR, textStatus, errorThrown) {

        },
        timeout: 10000
    });
}