dojo.require("dojo.parser");
dojo.require("dojo.dnd.move");
var cropX = 30;
var cropY = 156;
var cropW = 600;
var cropH = 600;

var locationImageCycleInterval = 10; // in seconds

var maps = {
    "map25x": {
        "file": "map25x.gif",
        "scale": 2.5,
        "dotscale": 2.5,
        "w": 1484,
        "h": 1375,
        "x": Math.round(1484/2-cropX-(cropW-50)/2),
        "y": Math.round(1375/2-cropY-(cropH-10)/2),
        "dotOffsetX": 0,
        "dotOffsetY": 0,
        "draggable": true,
        "node": ""
    },
    "map15x": {
        "file": "map15x.gif",
        "scale": 1.5,
        "dotscale": 1.5,
        "w": 891,
        "h": 825,
        "x": Math.round(891/2-cropX-(cropW-50)/2),
        "y": Math.round(825/2-cropY-(cropH-10)/2),
        "dotOffsetX": 0,
        "dotOffsetY": 0,
        "draggable": true,
        "node": ""
    },
    "map1x": {
        "file": "map1x.gif",
        "scale": 1,
        "dotscale": 1.5,
        "w": 600,
        "h": 600,
        "x": Math.round(600/2-cropX-(cropW-0)/2),
        "y": Math.round(600/2-cropY-(cropH-0)/2),
        "dotOffsetX": 3,
        "dotOffsetY": 1,
        "draggable": false,
        "node": ""
    }
};


/**
 * initialize draggable maps and their clippings
 */
var initMaps = function() {
    var mapcontNode = dojo.byId("mapcontainer");
    
    if (dojo.isIE > 0) {
        dojo.style(mapcontNode, "zIndex", "4900");
    }
    
    for (mapName in maps) {
        //console.debug(mapName);
        /*if (mapName != "map15x") {
            continue;
        }*/
        var mapNode = dojo.byId(mapName);
        
        if (dojo.style(mapNode, "display") == "none") {
            dojo.style(mapNode, "display", "block");
            displayNone = true;
        } else {
            displayNone = false;
        }
        
        mapW = maps[mapName]["w"];
        mapH = maps[mapName]["h"];
        mapX = maps[mapName]["x"];
        mapY = maps[mapName]["y"];
        dojo.style(mapNode, "top", (0-mapY).toString()+"px");
        dojo.style(mapNode, "left", (0-mapX).toString()+"px");
        dojo.style(mapNode, "width", mapW.toString()+"px");
        dojo.style(mapNode, "height", mapH.toString()+"px");
        dojo.style(mapNode, "clip", "rect("+(mapY+cropY)+"px, "+(mapX+cropX+cropW)+"px, "+(mapY+cropY+cropH)+"px, "+(mapX+cropX)+"px)");
        
        if (maps[mapName]["draggable"] == true) {
            dojo.style(mapNode, "cursor", "move");
            
            maps[mapName]["node"] = new dojo.dnd.move.boxConstrainedMoveable(mapNode, {
                box: {
                    l: mapcontNode.offsetLeft - (mapNode.offsetWidth - mapcontNode.offsetWidth),
                    t: mapcontNode.offsetTop - (mapNode.offsetHeight - mapcontNode.offsetHeight),
                    w: mapNode.offsetWidth - mapcontNode.offsetWidth,
                    h: mapNode.offsetHeight - mapcontNode.offsetHeight
                },
                within: false
            } );
            
            
            // watching a particular moveable instance
            dojo.connect(maps[mapName]["node"], "onMove", function(mover){ 
                //console.debug("Moving m500 with this mover:", mover);
                //console.debug(dojo.byId("map500").style.clip);
                //console.debug(mover.host.node.offsetLeft, " ", mover.host.node.offsetTop);
                Ctop = 0 - mover.host.node.offsetTop + mapcontNode.offsetTop;
                Cleft= 0 - mover.host.node.offsetLeft + mapcontNode.offsetLeft;
                Cright = Cleft + mapcontNode.offsetWidth;
                Cbottom = Ctop + mapcontNode.offsetHeight;
                dojo.style(mover.host.node, "clip", "rect("+Ctop+"px, "+Cright+"px, "+Cbottom+"px, "+Cleft+"px)");
                //console.debug("mover: ", dojo.byId(mover.host.node).id, " ", dojo.byId(mover.host.node).style.clip);
            });
            dojo.connect(maps[mapName]["node"], "onMoveStart", function(mover){ 
                //console.debug("Start moving m500 with this mover:", mover);
                dojo.style(mover.host.node, "cursor", "-moz-grabbing");
            });
            dojo.connect(maps[mapName]["node"], "onMoveStop", function(mover){ 
                //console.debug("Stop moving m500 with this mover:", mover); 	
                dojo.style(mover.host.node, "cursor", "move");
            });
            
        } /* end if draggable */
        
        if (displayNone == true) {
            dojo.style(mapNode, "display", "none");
        }
        
    } /* end for each maps */
    
    mapShow("map25x");
    
};
dojo.addOnLoad(initMaps);


/**
 * position the dots via JavaScript
 */
var initLocations = function () {
    guideShowDotsByCategory(guideActiveCatMain, "");
    for (var locId in locations) {
        guidePositionDot(locId);
    } /* end foreach locations */
}; /* end var initLocations */
dojo.addOnLoad(initLocations);


dojo.require("dojox.fx");
var guideMoveMapIntervalId;
function guideMoveMap (mapName, direction)
{
    switch (direction)
    {
        case 'down':
            moveTop = -2;
            moveLeft = 0;
            break;
        case 'top':
            moveTop = 2;
            moveLeft = 0;
            break;
        case 'right':
            moveTop = 0;
            moveLeft = -2;
            break;
        case 'left':
            moveTop = 0;
            moveLeft = 2;
            break;
    }
    guideMoveMapIntervalId = setInterval("guideMoveMapLayers('"+mapName+"', "+moveTop+", "+moveLeft+")", 10);
}
function guideMoveMapLayers (mapName, moveTop, moveLeft)
{
    mapcontNode = dojo.byId("mapcontainer");
    mapNode = dojo.byId(mapName);
    
			var cs = dojo.getComputedStyle(mapNode);
			var pos = cs.position;
			mapTop = (pos == 'absolute' ? mapNode.offsetTop : parseInt(cs.top) || 0);
			mapLeft = (pos == 'absolute' ? mapNode.offsetLeft : parseInt(cs.left) || 0);
			mapWidth = parseInt(cs.width);
			mapHeight = parseInt(cs.height);
            
    //console.debug("moveMapLayers: ", mapName, moveTop, moveLeft);
				var ret = dojo.coords(mapNode, true);
				mapTop = ret.y;
				mapLeft = ret.x;
				dojo.style(mapNode, "position", "absolute");
				dojo.style(mapNode, "top", mapTop+"px");
				dojo.style(mapNode, "left", mapLeft+"px");
    //console.debug("moveMapLayers: offset ", mapNode.offsetTop, mapNode.offsetLeft);
    //console.debug("moveMapLayers: style ", mapNode.style.top, mapNode.style.left);
    //console.debug("moveMapLayers: dojo ", mapTop, mapLeft);
    
    // get new position
    newTop = mapTop + moveTop;
    newLeft = mapLeft + moveLeft;
    //console.debug("moveMapLayers: ", mapName, newTop, newLeft);
    // restrict to container
    if (newTop > mapcontNode.offsetTop) {
        newTop = mapcontNode.offsetTop;
    }
    if (newTop < mapcontNode.offsetTop+mapcontNode.offsetHeight-mapHeight) {
        newTop = mapcontNode.offsetTop+mapcontNode.offsetHeight-mapHeight;
    }
    if (newLeft > mapcontNode.offsetLeft) {
        newLeft = mapcontNode.offsetLeft;
    }
    if (newLeft < mapcontNode.offsetLeft+mapcontNode.offsetWidth-mapWidth) {
        newLeft = mapcontNode.offsetLeft+mapcontNode.offsetWidth-mapWidth;
    }
    // move map
    dojo.style(mapNode, "top", newTop +"px");
    dojo.style(mapNode, "left", newLeft +"px");
    
    // move clipping
    Ctop = 0 - newTop + mapcontNode.offsetTop;
    Cleft= 0 - newLeft + mapcontNode.offsetLeft;
    Cright = Cleft + mapcontNode.offsetWidth;
    Cbottom = Ctop + mapcontNode.offsetHeight;
    dojo.style(mapNode, "clip", "rect("+Ctop+"px, "+Cright+"px, "+Cbottom+"px, "+Cleft+"px)");
}
function guideStopMap ()
{
    clearInterval(guideMoveMapIntervalId);
}
function guideMoveNavOver (node)
{
    dojo.style(node, "opacity", 1);
    dojo.style(node, "-moz-opacity", 1);
    dojo.style(node, "filter:alpha(opacity=100)");
}
function guideMoveNavOut (node)
{
    dojo.style(node, "opacity", .5);
    dojo.style(node, "-moz-opacity", .5);
    dojo.style(node, "filter:alpha(opacity=50)");
}


function mapShow(id) {
    /*
    oldScale = maps["map25x"]["scale"];
			var cs = dojo.getComputedStyle(dojo.byId("map25x"));
			var pos = cs.position;
			oldTop = (pos == 'absolute' ? dojo.byId("map25x").offsetTop : parseInt(cs.top) || 0);
			oldLeft = (pos == 'absolute' ? dojo.byId("map25x").offsetLeft : parseInt(cs.left) || 0);
			oldWidth = parseInt(cs.width);
			oldHeight = parseInt(cs.height);
    console.debug("mapShow: ", dojo.byId("map25x").style.top, ",", dojo.byId("map25x").offsetTop, ",", oldTop);
    */
    /*
    oldTop = parseInt(dojo.byId("map25x").style.top);
    oldLeft = parseInt(dojo.byId("map25x").style.left);
    */
    
    //console.debug(dojo.byId("map25x").style.top);
    //console.debug("init: ",oldTop, ",", oldLeft);
    
    /* make sure every map is hidden */
    if (id != "map1x" && dojo.style("map1x", "display") != "none") {
        //console.debug("fade out map1x");
        var fadeArgs = {
            node: "map1x",
            duration: 300,
            onEnd: function () { dojo.style("map1x", "display", "none"); }
        };
        dojo.fadeOut(fadeArgs).play();
        oldScale = maps["map1x"]["scale"];
        oldTop = dojo.byId("map1x").offsetTop;
        oldLeft = dojo.byId("map1x").offsetLeft;
    }
    if (id != "map15x" && dojo.style("map15x", "display") != "none") {
        //console.debug("fade out map15x");
        var fadeArgs = {
            node: "map15x",
            duration: 300,
            onEnd: function () { dojo.style("map15x", "display", "none"); }
        };
        dojo.fadeOut(fadeArgs).play();
        oldScale = maps["map15x"]["scale"];
        oldTop = dojo.byId("map15x").offsetTop;
        oldLeft = dojo.byId("map15x").offsetLeft;
    }
    if (id != "map25x" && dojo.style("map25x", "display") != "none") {
        //console.debug("fade out map25x");
        var fadeArgs = {
            node: "map25x",
            duration: 300,
            onEnd: function () { dojo.style("map25x", "display", "none"); }
        };
        dojo.fadeOut(fadeArgs).play();
        oldScale = maps["map25x"]["scale"];
        oldTop = dojo.byId("map25x").offsetTop;
        oldLeft = dojo.byId("map25x").offsetLeft;
    }
    /* move map */
    /*
    console.debug("oldMap: ", oldTop, ",", oldLeft);
    console.debug("oldMap scale: ", oldScale);
    newTop = oldTop/oldScale*maps[id]["scale"];
    newLeft = oldLeft/oldScale*maps[id]["scale"];
    console.debug("newMap: ", newTop, ",", newLeft);
    
    moveTop = parseInt(dojo.byId(id).style.top) - newTop;
    moveLeft = parseInt(dojo.byId(id).style.left) - newLeft;
    console.debug("newMap ("+id+") current pos: ", dojo.byId(id).style.top, ",", dojo.byId(id).style.left);
    console.debug("newMap move: ", moveTop, ",", moveLeft);
    //dojo.byId(id).style.top = Math.ceil(oldTop/oldScale*maps[id]["scale"])+"px";
    //dojo.byId(id).style.left = Math.ceil(oldLeft/oldScale*maps[id]["scale"])+"px";
    //dojo.byId(id).style.display = null;
    guideMoveMapLayers(id, -moveTop, -moveLeft);
    console.debug(dojo.byId(id).style.top);
    */
    
    /* show just the selected map */
    var fadeArgs = {
        node: id,
        duration: 300,
        beforeBegin: function () { dojo.removeClass(id, "hidden"); dojo.style(id, "display", "block"); }
    };
    dojo.fadeIn(fadeArgs).play();
    
    if (id == "map25x") {
        dojo.byId("nav_sub_map_zoomin").innerHTML = '<img src="/images/pages/guide/zoom-in-2-inactive.png" style="width:16px;" alt="zoom in not possible" />';
        dojo.byId("nav_sub_map_zoomout").innerHTML = '<a href="javascript:void(0);" onclick="mapShow(\'map15x\');"><img src="/images/pages/guide/zoom-out-2.png" style="width:16px;" alt="zoom out" /></a>';
        dojo.style("map15x_nav", "display", "none");
        dojo.style("map25x_nav", "display", "block");
    }
    if (id == "map15x") {
        dojo.byId("nav_sub_map_zoomin").innerHTML = '<a href="javascript:void(0);" onclick="mapShow(\'map25x\');"><img src="/images/pages/guide/zoom-in-2.png" style="width:16px;" alt="zoom in" /></a>';
        dojo.byId("nav_sub_map_zoomout").innerHTML = '<a href="javascript:void(0);" onclick="mapShow(\'map1x\');"><img src="/images/pages/guide/zoom-out-2.png" style="width:16px;" alt="zoom out" /></a>';
        dojo.style("map15x_nav", "display", "block");
        dojo.style("map25x_nav", "display", "none");
    }
    if (id == "map1x") {
        dojo.byId("nav_sub_map_zoomin").innerHTML = '<a href="javascript:void(0);" onclick="mapShow(\'map15x\');"><img src="/images/pages/guide/zoom-in-2.png" style="width:16px;" alt="zoom in" /></a>';
        dojo.byId("nav_sub_map_zoomout").innerHTML = '<img src="/images/pages/guide/zoom-out-2-inactive.png" style="width:16px;" alt="zoom out not possible" />';
        dojo.style("map15x_nav", "display", "none");
        dojo.style("map25x_nav", "display", "none");
    }
}


/**
 * show/hide detailed information (right side box)
 */
var map_locations_activeId; // = "0";
var locationimageLoaded = { };
function showLocation (id)
{
    if (map_locations_activeId != undefined && map_locations_activeId === id) {
        return false;
    }
    if (map_locations_activeId != undefined) {
        dojo.fadeOut({
            node: dojo.byId("map_location_"+map_locations_activeId),
            duration: 300,
            onEnd: function () { dojo.style("map_location_"+map_locations_activeId, "display", "none"); }
        }).play();
        if (locations[map_locations_activeId] != undefined) {
            locations[map_locations_activeId]["active"] = false;
            guideChangeDotState(map_locations_activeId, "visited");
        }
    }
    
    dojo.fadeIn({
        node: dojo.byId("map_location_"+id),
        duration: 300,
        beforeBegin: function () { dojo.removeClass("map_location_"+id, "hidden"); dojo.style("map_location_"+id, "display", "block"); },
        onEnd: function () {
            locations[id]["visited"] = true;
            locations[id]["active"] = true;
            guideChangeDotState(id, 'active');
            
            map_locations_activeId = id;
            if (id.length == 1) {
                imgId = "0"+id;
            } else {
                imgId = id;
            }
            dojo.removeClass("map_location_"+id, "hidden");
            dojo.byId("map_location_"+id+"_image").src = locationImagesPath+imgId+".jpg";
            //dojo.style("map_location_"+id+"_image", "display", "block");
            locationimageLoaded[id] = setInterval("guideCheckLocationimageLoaded('"+id+"')", 50);
            
            if (locationimageCycle != undefined) {
                clearInterval(locationimageCycle);
                //alert("foo"+(typeof locationimageCycle));
                locationimageCycle = undefined;
                // DEBUG
                //alert("foo"+(typeof locationimageCycle));
            }
            if (id == "0") {
                locationimageCycle = setInterval("guideLocationimageCycle('"+id+"')", locationImageCycleInterval*1000);
            }
        }
    }).play();
    
    return false;
}
function isImageLoaded (imgNode) {
    // During the onload event, IE correctly identifies any images
    // that weren't downloaded as not complete. Others should too.
    // Gecko-based browsers act like NS4 in that they report this
    // incorrectly: they always return true.
    if (!imgNode.complete) {
        return false;
    }

    // However, they do have two very useful properties: naturalWidth
    // and naturalHeight. These give the true size of the image. If
    // it failed to load, either of these should be zero.
    if (typeof imgNode.naturalWidth != "undefined" && imgNode.naturalWidth == 0) {
        return false;
    }

    // No other way of checking: assume it's ok.
    return true;
}
function guideCheckLocationimageLoaded (id) {
    if (isImageLoaded(dojo.byId("map_location_"+id+"_image")) == true) {
        //alert("is loaded");
    //if (dojo.byId("map_location_"+id+"_loading").complete == true) {
        /* setTimeout(function() { */
            var fadeArgs = {
                node: "map_location_"+id+"_image",
                duration: 600,
                beforeBegin: function () { dojo.removeClass("map_location_"+id+"_image", "hidden"); dojo.style("map_location_"+id+"_image", "display", "block"); }
            };
            dojo.fadeIn(fadeArgs).play();
            var fadeArgs = {
                node: "map_location_"+id+"_loading",
                duration: 300,
                onEnd: function () { dojo.style("map_location_"+id+"_loading", "display", "none"); }
            };
            dojo.fadeOut(fadeArgs).play();
            clearInterval(locationimageLoaded[id]);
        /* }, 500); */
    }
}

var locationimageCycle;
function guideLocationimageCycle (id) {
    if (id.length < 2) {
        imgName = "0"+id;
    } else {
        imgName = id;
    }
    imagesArr = new Array("00.jpg", "00-2.jpg");
    S = dojo.byId("map_location_"+id+"_image").src; // locationImagesPath+imgId+".jpg";
    //alert(S);
    re = new RegExp(locationImagesPath+"([^\/.]+.jpg)$","g");
    Ergebnis = re.exec(S);
    oldImgName = Ergebnis[1];
    //console.debug("old image name:", oldImgName);
    
    /* search for old image and get new name of the next image */
    for (var i = 0; i < imagesArr.length; i++) {
        //console.debug("search in array:", imagesArr[i]);
        if (imagesArr[i] == oldImgName) {
            if (i+1 == imagesArr.length) {
                newImgName = imagesArr[0];
            } else {
                newImgName = imagesArr[i+1];
            }
        }
    }
    //console.debug("new image name:", newImgName);
    
    dojo.fadeIn({
        node: dojo.byId("map_location_"+id+"_loading"),
        duration: 150,
        onEnd: function () { dojo.style("map_location_"+id+"_loading", "display", "block"); }
    }).play();
    dojo.fadeOut({
        node: dojo.byId("map_location_"+id+"_image"),
        duration: 150,
        onEnd: function () { dojo.style("map_location_"+id+"_image", "display", "none"); }
    }).play();
    
    setTimeout("guideChangeLocationimage('"+id+"', '"+locationImagesPath+newImgName+"')", 200);
}

function guideChangeLocationimage (id, src) {
    dojo.byId("map_location_"+id+"_image").src = src;
    locationimageLoaded[id] = setInterval("guideCheckLocationimageLoaded('"+id+"')", 50);
}

function guideChangeDotState (locId, state)
{
    if (locations[locId]["active"] == true) {
        dojo.byId("map1x_loc_"+locId).src = dotSrcActive;
        dojo.byId("map15x_loc_"+locId).src = dotSrcActive;
        dojo.byId("map25x_loc_"+locId).src = dotSrcActive;
    } else if (locations[locId]["visited"] == true) {
        dojo.byId("map1x_loc_"+locId).src = dotSrcVisited;
        dojo.byId("map15x_loc_"+locId).src = dotSrcVisited;
        dojo.byId("map25x_loc_"+locId).src = dotSrcVisited;
    } else {
        dojo.byId("map1x_loc_"+locId).src = dotSrcNormal;
        dojo.byId("map15x_loc_"+locId).src = dotSrcNormal;
        dojo.byId("map25x_loc_"+locId).src = dotSrcNormal;
    }
    
    guidePositionDot(locId);
}
function guidePositionDot (locId)
{
    if (locations[locId]["active"] == true) {
        w = Math.round(24/2.5); //16
        h = Math.round(24/2.5); //16
        xOffset = -14/2.5; //6
        yOffset = -14/2.5; //6
        dotSrc = dotSrcActive;
    } else if (locations[locId]["visited"] == true) {
        w = Math.round(10/2.5);
        h = Math.round(10/2.5);
        xOffset = 0;
        yOffset = 0;
        dotSrc = dotSrcVisited;
    } else {
        w = Math.round(11/2.5);
        h = Math.round(10/2.5);
        xOffset = 0;
        yOffset = 0;
        dotSrc = dotSrcNormal;
    }
    for (var mapName in maps) {
        locNode = dojo.byId(mapName+"_loc_"+locId);
        f = maps[mapName]["scale"];
        fd = maps[mapName]["dotscale"];
        offsetX = maps[mapName]["dotOffsetX"] +xOffset*fd;
        offsetY = maps[mapName]["dotOffsetY"] +yOffset*fd;
        locNode.src = dotSrc;
        dojo.style(locNode, "left", Math.round((locations[locId]["x"]+Math.round(w/2))*f) + offsetX + "px");
        dojo.style(locNode, "top", Math.round((locations[locId]["y"]+Math.round(h/2))*f) + offsetY + "px");
        dojo.style(locNode, "width", Math.round(w*fd) + "px");
        dojo.style(locNode, "height", Math.round(h*fd) + "px");
    } /* end foreach zoom factors */
}


var guideActiveCatMain = "smartloft";
function guideShowDotsByCategory (catMain, catSub)
{
    catMain_JS = catMain.replace(/[ &]/g, "");
    if (guideActiveCatMain != undefined) {
        dojo.byId("nav_sub_map_"+guideActiveCatMain+"_main").className = "";
        dojo.byId("nav_sub_map_"+guideActiveCatMain+"_main_a").className = "";
    }
    guideActiveCatMain = catMain_JS;
    dojo.byId("nav_sub_map_"+catMain_JS+"_main").className = "active";
    dojo.byId("nav_sub_map_"+catMain_JS+"_main_a").className = "active";
        
        for (var id in locations) {
            if (
                catMain == "smartloft"
                ||
                (catSub == "" && locations[id]["category"] == catMain)
                ||
                (locations[id]["category"] == catMain && locations[id]["category-sub"] == catSub)
            ) {
                dojo.style("maplocations_1x_dot_"+id, "display", "block");
                dojo.style("maplocations_15x_dot_"+id, "display", "block");
                dojo.style("maplocations_25x_dot_"+id, "display", "block");
                if (locId == undefined) {
                    var locId = id;
                }
            } else {
                dojo.style("maplocations_1x_dot_"+id, "display", "none");
                dojo.style("maplocations_15x_dot_"+id, "display", "none");
                dojo.style("maplocations_25x_dot_"+id, "display", "none");
            }
        }
    
    showLocation(locId);
}