var paddingBorder = 50;
var heightObject = 60;
var padding = 2;
var floor;
// standard point:  0 is left-x, center-y;  1: is left-x, bottom-y;     2: is left-x, top-y;    3: center-x, top-y;     4: right-x, top-y;
var arrStandardPoint = [];
var leftX_centerY = 0, leftX_bottomY = 1, leftX_topY = 2, centerX_topY = 3, rightX_topY = 4;
// save type object can set to horizontal wall or vertical wall, 0: horizontal wall, 1: vertical wall
var arrTypeObject = [];
var horizontalObject = 0, verticalObject = 1;
var arrImage = [];
var startIndex = 0;
var numObjectOneTime = 4;
// MR_1298 fix
var maxNumObject = 10;
var arrayBoundObjectX = [16.95, 121.30, 225.05, 328.8, 432.55, 536.30, 640.10, 743.85, 847.60, 951.60, 1056.00, 1158.95];
var boundObjectY = 843.90;

var arrObjectInWall = [];
var arrStepper = [];
var arrNewInstanceObject = [];
var arrObjectInBottom = [];
var arc;
var arrowLeft;
var arrowRight;
var mouseDownPositionX;
var mouseDownPositionY;
var opacityShape;

var transitionState = -1; // just for get data; when you want to set , please use setTransitionState

var mouseDeviation = 100;
function GetMouseDeviation() {
    return mouseDeviation / (zoom * scale);
}


function createImages(stage) {
    stage.enableMouseOver(10);
    stage.mouseMoveOutside = true;
    createImage_1(stage, 30, 900, 30, 30);
    createImage_2(stage, 130, 900, 30, 30);
    createImage_3(stage, 230, 900, 60, 25);
//    createImage_3(stage, 200, 930, 60, 60);
//    createImage_4(stage, 300, 870, 60, 60);
    createImage_5(stage, 330, 900, 30, 10);
    createImage_6(stage, 430, 900, 60, 10);
//    createImage_7(stage, 620, 900, 90, 10);
//    createImage_8(stage, 730, 900, 90, 10);
//    createImage_9(stage, 840, 900, 90, 10);
//    createImage_10(stage, 950, 900, 90, 10);
//    createImage_11(stage, 1060, 900, 90, 10);
//    createImage_12(stage, 1170, 900, 90, 5);
    createImage_13(stage, 530, 800, 30, 30);
    createImage_14(stage, 630, 800, 30, 30);
    createImage_15(stage, 730, 800, 25, 60);
//    createImage_15(stage, 200, 800, 60, 60);
//    createImage_16(stage, 350, 800, 60, 60);
    createImage_17(stage, 830, 800, 10, 30);
    createImage_18(stage, 930, 800, 10, 60);
//    createImage_19(stage, 620, 800, 10, 90);
//    createImage_20(stage, 730, 800, 10, 90);
//    createImage_21(stage, 840, 800, 10, 90);
//    createImage_22(stage, 950, 800, 10, 90);
//    createImage_23(stage, 1060, 800, 10, 90);
//    createImage_24(stage, 1170, 800, 5, 90);
//    drawArrowLeft(stage, 0, 860, 15, 70);
//    drawArrowRight(stage, 1265, 860, 15, 70);
    var objectName = ["  ドア", "  ドア", "ステップ", "窓（小）", "窓（中）", "  ドア", "  ドア", "ステップ", "窓（小）", "窓（中）"];

//    arrImage = [image_1, image_2, image_3, image_4, image_5, image_6, image_7, image_8, image_9, image_10, image_11, image_12, image_13,
//        image_14, image_15, image_16, image_17, image_18, image_19, image_20, image_21, image_22, image_23, image_24];
    arrImage = [image_1, image_2, image_3, image_5, image_6, image_13, image_14, image_15, image_17, image_18];
    // add to array that show to user
    for (var i = 0; i < arrImage.length; i++) {
        var object = arrImage[i].clone(true);
        object.width = arrImage[i].width;
        object.height = arrImage[i].height;
        var x = getXValue(arrStandardPoint[i], object, i);
        var y = getYValue(arrStandardPoint[i], object);

        addObjectName(stage, arrayBoundObjectX[i], ( boundObjectY), objectName[i]);
        object.x = x;
        object.y = y;
        object.oldX = x;
        object.oldY = y;
        object.oldWidth = arrImage[i].width;
        object.oldHeight = arrImage[i].height;
        object.oldObject = arraySVGObject[i];
        object.index = i;
        object.standardPoint = arrStandardPoint[i];
        object.typeObject = arrTypeObject[i];
        object.oldZoomX = x;
        object.oldZoomY = y;
        object.oldZoomWidth = arrImage[i].width;
        object.oldZoomHeight = arrImage[i].height;
        // mouse down
        object.on("mousedown", function (evt) {
            imageMouseDown(evt, this.oldObject, this.index, this.rotation);
        });
        arrObjectInBottom.push(object);
    }
    createListObject();
    stage.update();
}

function addObjectName(stage, x, y, objectName) {


    var text = new createjs.Text(objectName, "14px Arial", "#000");
    text.x = x + 25; // + (100- text.clientWidth)/2;
    text.y = y + 105;
    text.textBaseline = "alphabetic";
    stage.addChild(text)
}


function createListObject() {
    for (var i = 0; i < arrObjectInBottom.length; i++) {
        stage.addChild(arrObjectInBottom[i]);
    }
}


// Find a point (x, y) contains in list position that can set pillar or not?
var findPillarInitPosition = function (x, y) {
    for (var i = 0; i < listInitPillar.length; i++) {
        if (Math.abs(listInitPillar[i].x - x) <= 20 && Math.abs(listInitPillar[i].y - y) <= 20) {
            return listInitPillar[i];
        }
    }
    return null;
}
var pillarNextToObjectList = [];
function findPillarNextToObject( pillar )
{
    for (var i = 0; i < pillarNextToObjectList.length; i++) {
    	if( pillarNextToObjectList[i] == pillar)
    	{
    		return i;
    	}
    }
    return pillarNextToObjectList.length;

}
function removeCurrentPillarInObject(shape) {

    var shapeY = shape.y;
    var shapeX = shape.x;
    
    var arrDelete = [];
    console.log("removeCurrentPillarInObject 1");
    for (var i = 0; i < pillarIndexStage.length; i++) {

        // check duplicate with auto set pillar
        //var pillarPosition = findPillarPosition(pillarIndexStage[i].x, pillarIndexStage[i].y);
        //if (pillarPosition != null) {
        //    continue;
        //}
        var pillarNextToObjIndex = findPillarNextToObject(pillarIndexStage[i]);
        if( pillarNextToObjIndex >= pillarNextToObjectList.length) continue;
        

    console.log("removeCurrentPillarInObject 2");
    
		var diff = converMMtoPX(widthPillar);

        if (( (pillarIndexStage[i].x  <= shapeX  && pillarIndexStage[i].x + converMMtoPX(widthPillar) + diff >= shapeX ) &&
            (pillarIndexStage[i].y  <= shapeY && pillarIndexStage[i].y + converMMtoPX(widthPillar) + diff >= shapeY) )
            ||
            ( ( pillarIndexStage[i].x <= shapeX + shape.width && pillarIndexStage[i].x + converMMtoPX(widthPillar) >= shapeX + shape.width) &&
            ( pillarIndexStage[i].y <= shapeY  && pillarIndexStage[i].y + converMMtoPX(widthPillar) >= shapeY) )
            ||
            ( ( pillarIndexStage[i].y <= shapeY + shape.height && pillarIndexStage[i].y + converMMtoPX(widthPillar) >= shapeY + shape.height) &&
            ( pillarIndexStage[i].x <= shapeX  && pillarIndexStage[i].x + converMMtoPX(widthPillar) >= shapeX) )) {
            
    console.log("removeCurrentPillarInObject 3");
            stage.removeChild(pillarIndexStage[i]);
            arrDelete.push(i);

            // remove pillar from memory
            var pillarTmp = getByTypeAndXY(TYPE_PILLAR, converPxtoMmWithScalenZoom(pillarIndexStage[i].x), converPxtoMmWithScalenZoom(pillarIndexStage[i].y));
            if (pillarTmp != null) {
                deleteArray3dCad(pillarTmp[0][0]);
            }
            pillarNextToObjectList.splice(pillarNextToObjIndex, 1);
        }
    }

    for (var i = arrDelete.length - 1; i > 0; i--) {
        pillarIndexStage.splice(arrDelete[i], 1);
    }
}

function createPillarNextToObjectTopBottom(shape) {
    // set pillar when set object
    var shapeXMm = converPxtoMmWithScalenZoom(shape.x);
    var shapeYMm = converPxtoMmWithScalenZoom(shape.y);
    var shapeWidthMm = converPxtoMmWithScalenZoom(shape.width);
    var shapeHeightMm = converPxtoMmWithScalenZoom(shape.height);
    var widthPillarPx = converMMtoPXWithScalenZoom(widthPillar);

    if (getByTypeAndXY(TYPE_PILLAR, shapeXMm - widthPillar / 2, shapeYMm - widthPillar) == null) {
        var pillarFirst = createPillarWithPixel(shape.x - widthPillarPx/2, shape.y - widthPillarPx, (widthPillarPx));
        stage.addChild(pillarFirst);
        setArray3dCad(null, TYPE_PILLAR, shapeXMm - widthPillar / 2, shapeYMm - widthPillar, widthPillar, widthPillar, 0, 0, 0, 0, 0, 0);
        pillarIndexStage.push(pillarFirst);
        pillarNextToObjectList.push(pillarFirst);
    }

    if (getByTypeAndXY(TYPE_PILLAR, shapeXMm  - widthPillar / 2, shapeYMm + shapeHeightMm ) == null) {
        
        var pillarSecond = createPillarWithPixel(shape.x - widthPillarPx/2, shape.y + shape.height, (widthPillarPx));
        stage.addChild(pillarSecond);
        setArray3dCad(null, TYPE_PILLAR, shapeXMm  - widthPillar / 2, shapeYMm + shapeHeightMm, widthPillar, widthPillar, 0, 0, 0, 0, 0, 0);
        pillarIndexStage.push(pillarSecond);
        pillarNextToObjectList.push(pillarSecond);
    }
}

function createPillarNextToObjectLeftRight(shape) {
    // set pillar when set object
    var shapeXMm = converPxtoMmWithScalenZoom(shape.x);
    var shapeYMm = converPxtoMmWithScalenZoom(shape.y);
    var shapeWidthMm = converPxtoMmWithScalenZoom(shape.width);
    var shapeHeightMm = converPxtoMmWithScalenZoom(shape.height);
    var widthPillarPx = converMMtoPXWithScalenZoom(widthPillar);

    if (getByTypeAndXY(TYPE_PILLAR, shapeXMm - widthPillar, shapeYMm - widthPillar / 2) == null) {
        var pillarFirst = createPillarWithPixel(shape.x - widthPillarPx, shape.y - (widthPillarPx / 2), (widthPillarPx));
        stage.addChild(pillarFirst);
        setArray3dCad(null, TYPE_PILLAR, shapeXMm - widthPillar, shapeYMm - (widthPillar / 2), widthPillar, widthPillar, 0, 0, 0, 0, 0, 0);
        pillarIndexStage.push(pillarFirst);
        pillarNextToObjectList.push(pillarFirst);
    }

    if (getByTypeAndXY(TYPE_PILLAR, shapeXMm + shapeWidthMm, shapeYMm - widthPillar / 2) == null) {
        var pillarSecond = createPillarWithPixel(shape.x + shape.width, shape.y - widthPillarPx / 2, (widthPillarPx));
        stage.addChild(pillarSecond);
        setArray3dCad(null, TYPE_PILLAR, shapeXMm + shapeWidthMm, shapeYMm - widthPillar / 2, widthPillar, widthPillar, 0, 0, 0, 0, 0, 0);
        pillarIndexStage.push(pillarSecond);
        pillarNextToObjectList.push(pillarSecond);
    }
}

function CheckAndSetStepperLeft (CurrentObject, mouseX, mouseY, shape) {
    if(CurrentObject[1] <= mouseY
        && mouseY <=  CurrentObject[1] + CurrentObject[3]
        && Math.abs(mouseX - CurrentObject[0] + converPxtoMmWithScalenZoom(shape.width/2)) < GetMouseDeviation()) 
    {
        shape.x = converMMtoPXWithScalenZoom(CurrentObject[0]) - shape.width/2;
        return true;
    }
}

function CheckAndSetStepperTop (CurrentObject, mouseX, mouseY, shape) {
    if( (CurrentObject[0] <= mouseX) 
        && (mouseX <= CurrentObject[0] + CurrentObject[2])
        && (Math.abs(mouseY - CurrentObject[1] + converPxtoMmWithScalenZoom(shape.height/2)) < GetMouseDeviation()))
    {
        shape.y = converMMtoPXWithScalenZoom(CurrentObject[1]) - shape.height/2;
        return true;
    }
}

function CheckAndSetStepperRight (CurrentObject, mouseX, mouseY, shape) {
    if(CurrentObject[1] <= mouseY
        && mouseY <= CurrentObject[1] + CurrentObject[3]
        && Math.abs(mouseX - CurrentObject[0] - CurrentObject[2] - converPxtoMmWithScalenZoom(shape.width/2)) < GetMouseDeviation()) 
    {
        shape.x = converMMtoPXWithScalenZoom(CurrentObject[0]) + converMMtoPXWithScalenZoom(CurrentObject[2]) + shape.width/2;
        return true;
    }
}

function CheckAndSetStepperBottom (CurrentObject, mouseX, mouseY, shape) {
    if( (CurrentObject[0] <= mouseX) 
        && (mouseX <= CurrentObject[0] + CurrentObject[2])
        && (Math.abs(mouseY - CurrentObject[1] - CurrentObject[3] - converPxtoMmWithScalenZoom(shape.height/2)) < GetMouseDeviation()))
    {
        shape.y = converMMtoPXWithScalenZoom(CurrentObject[1]) + converMMtoPXWithScalenZoom(CurrentObject[3]) + shape.height/2;
        return true;
    }
}


function CheckAndSetStepper (mouseX, mouseY, shape) {
    // Get floor info
    var floorList = getArray3dCadByType(TYPE_FLOOR);
    var currentFloor = floorList[0][2];

    // Get balcony info
    var balconyList = getArray3dCadByType(TYPE_BALCONY);
    var currentBalcony = balconyList[0][2];

    var goodSet = false;
    
    if(balconyPos != 1 && shape.typeObject == verticalObject)
    {
        // Check left of floor
        if(CheckAndSetStepperLeft(currentFloor, mouseX, mouseY, shape))
        {
            goodSet = true;
        }
        
        // Check right of balcony
        if(CheckAndSetStepperRight(currentBalcony, mouseX, mouseY, shape))
        {
            goodSet = true;
        }
    }
    if(balconyPos != 3 && shape.typeObject == verticalObject)
    {
        //Check right of floor
        if(CheckAndSetStepperRight(currentFloor, mouseX, mouseY, shape))
        {
            goodSet = true;
        }
        
        // Check left of balcony
        if(CheckAndSetStepperLeft(currentBalcony, mouseX, mouseY, shape))
        {
            goodSet = true;
        }
    }

    if(balconyPos != 2 && shape.typeObject == horizontalObject)
    {
        // Check top of floor
        if(CheckAndSetStepperTop(currentFloor, mouseX, mouseY, shape))
        {
            goodSet = true;
        }

        // Check bottom of balcony
        if(CheckAndSetStepperBottom(currentBalcony, mouseX, mouseY, shape))
        {
            goodSet = true;
        }
    }
    if(balconyPos != 4 && shape.typeObject == horizontalObject)
    {
        //Check bottom of floor
        if(CheckAndSetStepperBottom(currentFloor, mouseX, mouseY, shape))
        {
            goodSet = true;
        }

        // Check top of balcony
        if(CheckAndSetStepperTop(currentBalcony, mouseX, mouseY, shape))
        {
            goodSet = true;
        }
    }
    return goodSet;
}

function imageMouseDown(evt, objectValue, index, rotation) {
    if ( transitionState < STATE_TRANSITION_SET_OBJECT ) return ; 
    if (!isChoose) {
        var shape = evt.target;
        if ((rotation / 180) % 2 == 0) {
            drawArc(shape);
        } else {
            drawArcRevert(shape);
        }
        stage.on("mousedown", function (event) {
    		if ( transitionState < STATE_TRANSITION_SET_OBJECT ) return ; 

            removeCurrentPillarInObject(shape);

            // set the previous position
            shape.previousX = shape.x;
            shape.previousY = shape.y;
            
            mouseDownPositionX = event.localX;
            mouseDownPositionY = event.localY;

            stage.removeChild(arc);

            var temp = shape.settedFlag;
            // create new instance
            if (rotation == 0) {
                if (shape.settedFlag != true) {
                    createNewObjectInstance(shape, index);
                    // set flag for image
                    shape.settedFlag = true;
                    // draw with real size
                    drawWithRealSize(shape, index);
                }
            }
        });
        stage.on("stagemousemove", function (event) {
            if ( transitionState < STATE_TRANSITION_SET_OBJECT ) return ; 
            // Move follow the mouse
    		if ( transitionState < STATE_TRANSITION_SET_OBJECT ) return ; 
            shape.x = shape.previousX + (event.localX - mouseDownPositionX);
            shape.y = shape.previousY + (event.localY - mouseDownPositionY);
        });
        stage.on("stagemouseup", function (event) {
                if ( transitionState < STATE_TRANSITION_SET_OBJECT ) return ; 
                // Remove Event
            	stage.removeAllEventListeners();
                var isSetted = false;
                var mouseX = converPxtoMmWithScalenZoom(event.localX); //  * 455 / (100 * zoom*scale);
                var mouseY = converPxtoMmWithScalenZoom(event.localY); // * 455 / (100 * zoom*scale);
                var shapeWidthMm = converPxtoMmWithScalenZoom(shape.width);
                var shapeHeightMm = converPxtoMmWithScalenZoom(shape.height);
                var isOverlaps = false;
                
                if( objectValue[2] == TYPE_STEPPER ) 
                {
                    var indexOfStepperArr = arrStepper.indexOf(shape);
                    var indexOfMemory = -1;
                    if(CheckAndSetStepper(mouseX, mouseY, shape))
                    {
                        //stage.addChild(shape);
                        shape.oldZoomX = shape.x;
                        shape.oldZoomY = shape.y;
                        shape.oldZoomWidth = shape.width;
                        shape.oldZoomHeight = shape.height;

                        if (Math.abs(shape.oldX - shape.previousX) <= shape.width && Math.abs(shape.oldY - shape.previousY) <= shape.height) 
                        {
                            stage.addChild(shape);
                            indexOfMemory = setArray3dCad(objectValue[1], objectValue[2], converPxtoMmWithScalenZoom(shape.x), converPxtoMmWithScalenZoom(shape.y), shapeWidthMm, shapeHeightMm, 0, 0, 0, 0, 0, 0);

                            isZoom = 1;
                            isRoof2D = 0;
                        } 
                        else 
                        {
                            var currentShapeInMemory = getByTypeAndXY(objectValue[2], converPxtoMmWithScalenZoom(shape.previousX), converPxtoMmWithScalenZoom(shape.previousY));
                            if (currentShapeInMemory) {
                                updateArray3dCad(currentShapeInMemory[ARR3DCAD_NO][0], objectValue[1], objectValue[2], converPxtoMmWithScalenZoom(shape.x), converPxtoMmWithScalenZoom(shape.y),
                                    shapeWidthMm, shapeHeightMm, 0, 0, 0, 0, 0, 0);
                                indexOfMemory = currentShapeInMemory[ARR3DCAD_NO][0];
                            }
                        }

                        if (indexOfStepperArr < 0) {
                            arrStepper.push(shape);
                        } else {
                            arrStepper.splice(indexOfStepperArr, 1);
                            arrStepper.push(shape);
                        }
                        isSetted = true;
                        rotateImage(shape, arc);
                    }

                    if (!isSetted && rotation == 0) {
                        if (indexOfStepperArr >= 0) {
                            arrStepper.splice(indexOfStepperArr, 1);
                        }

                        if (indexOfMemory >= 0) {
                            deleteArray3dCad(indexOfMemory);
                        }
                        if (shape.index >= startIndex && shape.index <= startIndex + maxNumObject) {
                            shape.x = shape.oldX;
                            shape.y = shape.oldY;
                        }
                        stage.removeChild(arc);
                        shape.rotation = 0;
                    } else if (!isSetted && rotation != 0) {
                        if (indexOfStepperArr >= 0) {
                            arrStepper.splice(indexOfStepperArr, 1);
                        }
                        if (indexOfMemory >= 0) {
                            deleteArray3dCad(indexOfMemory);
                        }
                        stage.removeChild(shape);
                        stage.removeChild(arc);
                    }

                    if (!isSetted && shape.settedFlag == true) {
                        stage.removeChild(shape);
                    }
                    // enable wall event
                    addWallPillarEvent();
                    return;
                }

                var wallList = getArray3dCadByType(3);
                var indexOfArr = arrObjectInWall.indexOf(shape);
                var indexOfMemory = -1;
                for (var i = 0; i < wallList.length; i++) {
                    var dxy = wallList[i][dxyIndex];
                    var wallX = dxy[0];
                    var wallY = dxy[1];
                    var wallWidth = dxy[2];
                    var wallHeight = dxy[3];


                    if (wallWidth > wallHeight) {
                        if (wallX < mouseX && mouseX < wallX + wallWidth && shape.typeObject == horizontalObject &&
                            (shapeWidthMm < wallWidth ) &&
                            ((Math.abs(mouseY - wallY) <= GetMouseDeviation()) || Math.abs(mouseY - (wallY + wallHeight)) <= GetMouseDeviation()) &&
                            isSetObjectToWall(mouseX, mouseY)) {

                            
                            //shape.x = event.localX;
                            shape.y = converMMtoPXWithScalenZoom(wallY); // * 100 *zoom*scale / 455;
                            if (objectValue[2] == TYPE_DOOR || objectValue[2] == TYPE_WINDOW ) {
                            
	                            // Get list pillar in this wall
	                            var list_pillar = getArray3dCadByType(TYPE_PILLAR);
	                            var pillerInWall = [];
	                            list_pillar.forEach(function (v, k) {
	                                if (wallY > v[dxyIndex][1] && wallY <= (v[dxyIndex][1] + v[dxyIndex][3])) {
	                                    pillerInWall.push(v);
	                                }
	                            });
	                            var pillarRight, pillarLeft, min, max;
	                            pillerInWall.forEach(function (val, key) {
	                                if (converMMtoPXWithScalenZoom(val[dxyIndex][0]) > shape.x) {
	                                    var temp = converMMtoPXWithScalenZoom(val[dxyIndex][0]) - shape.x;
	                                    if (!min || min > temp) {
	                                        min = temp;
	                                        pillarRight = val;
	                                    }
	                                }
	                                if (converMMtoPXWithScalenZoom(val[dxyIndex][0]) < shape.x) {
	                                    var temp = converMMtoPXWithScalenZoom(val[dxyIndex][0]) - shape.x;
	                                    if (!max || max < temp) {
	                                        max = temp;
	                                        pillarLeft = val;
	                                    }
	                                }
	                            });
	                            
                                if (pillarRight && pillarLeft && (converPxtoMmWithScalenZoom(shape.x) + (shapeWidthMm)) >= pillarRight[dxyIndex][0]) {
                				    shape.x = converMMtoPXWithScalenZoom(pillarLeft[dxyIndex][0] + (pillarRight[dxyIndex][0] + widthPillar  - pillarLeft[dxyIndex][0]) / 2 - shapeWidthMm / 2);
                                }
                                
                                if ((converPxtoMmWithScalenZoom(shape.x) + (shapeWidthMm)) > (wallX + wallWidth)) {
                                    shape.x = converMMtoPXWithScalenZoom(wallX + wallWidth - widthPillar / 2 - shapeWidthMm);
                                }
                                if (converPxtoMmWithScalenZoom(shape.x) <= (wallX + widthPillar / 2)) {
                                    shape.x = converMMtoPXWithScalenZoom(wallX + widthPillar / 2 );
                                }
                                if (pillarRight && pillarLeft &&  converPxtoMmWithScalenZoom(shape.x) <= (pillarLeft[dxyIndex][0] + 2*widthPillar)) {
                                    shape.x = converMMtoPXWithScalenZoom(pillarLeft[dxyIndex][0] + widthPillar );
                                }

                            }
                            
                            // check is pillar inside the object
	                        if( pillarRight && pillarLeft &&  pillarRight[dxyIndex][0] + widthPillar  - pillarLeft[dxyIndex][0] < shapeWidthMm ) break;
                            // Check object is not overlap to others
                            if( checkOverlapObject( shape ) == true) break;

                            shape.oldZoomX = shape.x;
                            shape.oldZoomY = shape.y;
                            shape.oldZoomWidth = shape.width;
                            shape.oldZoomHeight = shape.height;

                            // set two pillar next to object
                            if( transitionState > STATE_TRANSITION_SET_OBJECT)
                            {
                            	createPillarNextToObjectLeftRight(shape);
                            }

                            if (Math.abs(shape.oldX - shape.previousX) <= shape.width && Math.abs(shape.oldY - shape.previousY) <= shape.height) {

                                stage.addChild(shape);
                                // add to memory
                                if (objectValue[2] == TYPE_DOOR) {
                                    indexOfMemory = setArray3dCad(objectValue[1], objectValue[2], shape.x / (scale * zoom), shape.y / (scale * zoom), objectValue[3], objectValue[4], 0, 0, 0, 0, 0, 0);
                                } else {
                                    indexOfMemory = setArray3dCad(objectValue[1], objectValue[2], shape.x / (scale * zoom), shape.y / (scale * zoom), objectValue[3], objectValue[4], 0, 0, 0, 0, 0, 0);
                                }

                                isZoom = 1;
                                isRoof2D = 0;

                            } else {
                                var currentShapeInMemory = getByTypeAndXY(objectValue[2], shape.previousX / (scale * zoom), shape.previousY / (scale * zoom));
                                if (currentShapeInMemory) {
                                    updateArray3dCad(currentShapeInMemory[ARR3DCAD_NO][0], objectValue[1], objectValue[2], shape.x / (scale * zoom), shape.y / (scale * zoom),
                                        objectValue[3], objectValue[4], 0, 0, 0, 0, 0, 0);
                                    indexOfMemory = currentShapeInMemory[ARR3DCAD_NO][0];
                                }
                            }

                            if (indexOfArr < 0) {
                                arrObjectInWall.push(shape);
                                // change state
                                //setTransitionState(STATE_TRANSITION_SET_OBJECT_CANFINISH);
                                
                            } else {
                                arrObjectInWall.splice(indexOfArr, 1);
                                arrObjectInWall.push(shape);
                            }
                            
                            isSetted = true;
                            // if(index <=3 ){
                            rotateImage(shape, arc);
                            // }

                            break;
                        }
                    } else {
                        // wall is left or right
                        if (wallY < mouseY && mouseY < wallY + wallHeight && shape.typeObject == verticalObject &&
                            (objectValue[4] < converMMtoPX(wallHeight) ) &&
                            ((Math.abs(mouseX - wallX) <= GetMouseDeviation()) || Math.abs(mouseX - (wallX + wallWidth)) <= GetMouseDeviation()
                            || Math.abs(mouseX + wallWidth - wallX) <= GetMouseDeviation()) && isSetObjectToWall(mouseX, mouseY)) {

                            shape.x = converMMtoPXWithScalenZoom(wallX);
                            
                            if (objectValue[2] == TYPE_DOOR || objectValue[2] == TYPE_WINDOW ) {
	                            var list_pillar = getArray3dCadByType(4);
	                            
	                            // Get list pillar in this wall
	                            var pillerInWall = [];
	                            list_pillar.forEach(function (v, k) {
	                                if (wallX > v[dxyIndex][0] && wallX <= (v[dxyIndex][0] + v[dxyIndex][2])) {
	                                    pillerInWall.push(v);
	                                }
	                            });
	                            
	                            // search pillar which above object and under object
	                            var pillarBottom, pillarTop, min, max;
	                            pillerInWall.forEach(function (val, key) {
	                                if (converMMtoPXWithScalenZoom(val[dxyIndex][1]) > shape.y) {
	                                    var temp = converMMtoPXWithScalenZoom(val[dxyIndex][1]) - shape.y;
	                                    if (!min || min > temp) {
	                                        min = temp;
	                                        pillarBottom = val;
	                                    }
	                                }
	                                if (converMMtoPXWithScalenZoom(val[dxyIndex][1]) < shape.y) {
	                                    var temp = converMMtoPXWithScalenZoom(val[dxyIndex][1]) - shape.y;
	                                    if (!max || max < temp) {
	                                        max = temp;
	                                        pillarTop = val;
	                                    }
	                                }
	                            });
	                            
                                if (pillarTop && pillarBottom && (converPxtoMmWithScalenZoom(shape.y) + shapeHeightMm) >= pillarBottom[dxyIndex][1]) {
                                	shape.y = converMMtoPXWithScalenZoom(pillarTop[dxyIndex][1] + (pillarBottom[dxyIndex][1] + widthPillar - pillarTop[dxyIndex][1]) / 2 - shapeHeightMm / 2);
                                }
                                
                                if ((converPxtoMmWithScalenZoom(shape.y) + (shapeHeightMm)) > (wallY + wallHeight)) {
                                    shape.y = converMMtoPXWithScalenZoom(wallY + wallHeight - widthPillar / 2 - shapeHeightMm);
                                }
                                
                                if (converPxtoMmWithScalenZoom(shape.y ) <= (wallY + widthPillar/2) ) {
                                    shape.y = converMMtoPXWithScalenZoom(wallY + widthPillar / 2 );
                                }
                                

                            }
                            // check is pillar inside the object
	                        if( pillarTop && pillarBottom && pillarBottom[dxyIndex][1] + widthPillar - pillarTop[dxyIndex][1] < shapeHeightMm ) break;
                            // Check object is not overlap to others
                            if( checkOverlapObject( shape ) == true) break;
                            
                            shape.oldZoomX = shape.x;
                            shape.oldZoomY = shape.y;
                            shape.oldZoomWidth = shape.width;
                            shape.oldZoomHeight = shape.height;

                            // set two pillar next to object
                            if( transitionState > STATE_TRANSITION_SET_OBJECT)
                            {
                            	createPillarNextToObjectTopBottom(shape);
                            }

                            if (Math.abs(shape.oldX - shape.previousX) <= shape.width && Math.abs(shape.oldY - shape.previousY) <= shape.height) {
                                stage.addChild(shape);

                                // add to memory
                                if (objectValue[2] == TYPE_DOOR) {
                                    indexOfMemory = setArray3dCad(objectValue[1], objectValue[2], shape.x / (scale * zoom), shape.y / (scale * zoom), objectValue[3], objectValue[4], 0, 0, 0, 0, 0, 0);
                                } else {
                                    indexOfMemory = setArray3dCad(objectValue[1], objectValue[2], shape.x / (scale * zoom), shape.y / (scale * zoom), objectValue[3], objectValue[4], 0, 0, 0, 0, 0, 0);
                                }

                                isZoom = 1;
                                isRoof2D = 0;
                                

                            } else {
                                var currentShapeInMemory = getByTypeAndXY(objectValue[2], converPxtoMmWithScalenZoom(shape.previousX), converPxtoMmWithScalenZoom(shape.previousY));
                                if (currentShapeInMemory) {
                                    updateArray3dCad(currentShapeInMemory[ARR3DCAD_NO][0], objectValue[1], objectValue[2], converPxtoMmWithScalenZoom(shape.x), converPxtoMmWithScalenZoom(shape.y),
                                        objectValue[3], objectValue[4], 0, 0, 0, 0, 0, 0);
                                    indexOfMemory = currentShapeInMemory[ARR3DCAD_NO][0];
                                }
                            }

                            if (indexOfArr < 0) {
                                arrObjectInWall.push(shape);
                                
                                // change state
                                //setTransitionState(STATE_TRANSITION_SET_OBJECT_CANFINISH);
                            } else {
                                arrObjectInWall.splice(indexOfArr, 1);
                                arrObjectInWall.push(shape);
                            }

                            isSetted = true;
                            // if(index <=3 ){
                            rotateImage(shape, arc);
                            // }
                            break;
                        }
                    }
                }
                if (!isSetted && rotation == 0) {
                    if (indexOfArr >= 0) {
                        arrObjectInWall.splice(indexOfArr, 1);
                    }

                    if (indexOfMemory >= 0) {
                        deleteArray3dCad(indexOfMemory);
                    }
                    if (shape.index >= startIndex && shape.index <= startIndex + maxNumObject) {
                        shape.x = shape.oldX;
                        shape.y = shape.oldY;
                    }
                    stage.removeChild(arc);
                    shape.rotation = 0;
                } else if (!isSetted && rotation != 0) {
                    if (indexOfArr >= 0) {
                        arrObjectInWall.splice(indexOfArr, 1);
                    }
                    if (indexOfMemory >= 0) {
                        deleteArray3dCad(indexOfMemory);
                    }
                    stage.removeChild(shape);
                    stage.removeChild(arc);
                }

                if (!isSetted && shape.settedFlag == true) {
                    // Move if the shape is not put at the wall
                    var currentShapeInMemory = getByTypeAndXY(objectValue[2], shape.previousX / (scale * zoom), shape.previousY / (scale * zoom));
                    if (currentShapeInMemory) {
                        indexOfMemory = currentShapeInMemory[ARR3DCAD_NO][0];
                    }
                	deleteArray3dCad(indexOfMemory);
                    stage.removeChild(shape);
                	
                }
                // enable wall event
                addWallPillarEvent();
            }
        )
        ;
    }
}

function checkOverlapObjectWithPos( x, y , width , height)
{

    // Check object is not overlap to others
    for( var j = 0; j<arrObjectInWall.length; j ++ )
    {
    	// check overlaps
    	if ((x < (arrObjectInWall[j].x + arrObjectInWall[j].width)) && 
    		( ( x + width) > arrObjectInWall[j].x) && 
    		(y < (arrObjectInWall[j].y + arrObjectInWall[j].height)) && 
    		((y + height) > arrObjectInWall[j].y) ) 
    	{
    		return true;
    	}
    }  
    return false;

}

function checkOverlapObject(shape)
{

    // Check object is not overlap to others
    for( var j = 0; j<arrObjectInWall.length; j ++ )
    {
    	if( shape != arrObjectInWall[j])
    	{
	    	// check overlaps
	    	if ((shape.x < (arrObjectInWall[j].x + arrObjectInWall[j].width)) && 
	    		( ( shape.x + shape.width) > arrObjectInWall[j].x) && 
	    		(shape.y < (arrObjectInWall[j].y + arrObjectInWall[j].height)) && 
	    		((shape.y + shape.height) > arrObjectInWall[j].y) ) 
	    	{
	    		return true;
	    	}
    	}
    }  
    return false;

}

function isSetObjectToWall(clickedX, clickedY) {
    var pillarList = getArray3dCadByType(4);
    for (var i = 0; i < pillarList.length; i++) {
        var dxy = pillarList[i][ARR3DCAD_DXY];
        if (dxy[DXY_X] <= clickedX && clickedX <= dxy[DXY_X] + dxy[DXY_WIDTH_X]
            && dxy[DXY_Y] <= clickedY && clickedY <= dxy[DXY_Y]) {
            return false;
        }
    }
    return true;
}

function createNewObjectInstance(object, index) {

    var newImage = object.clone(true);
    newImage.x = object.oldX;
    newImage.y = object.oldY;
    newImage.width = object.oldWidth;
    newImage.height = object.oldHeight;
    // set origin position
    newImage.oldX = object.oldX;
    newImage.oldY = object.oldY;
    newImage.oldWidth = object.oldWidth;
    newImage.oldHeight = object.oldHeight;
    newImage.cursor = "pointer";
    newImage.oldObject = arraySVGObject[index];
    newImage.index = index;
    newImage.standardPoint = object.standardPoint;
    newImage.typeObject = object.typeObject;
    newImage.oldZoomX = object.oldX;
    newImage.oldZoomY = object.oldY;
    newImage.oldZoomWidth = object.width;
    newImage.oldZoomHeight = object.height;
    // mouse down
    newImage.on("mousedown", function (evt) {
        imageMouseDown(evt, this.oldObject, this.index, this.rotation);
    });
    newImage.settedFlag = false;
    stage.addChild(newImage);
    arrNewInstanceObject.push(newImage);
}

function rotateImage(image, arc) {
    if (!isChoose) {
        image.on('pressmove', function (evt) {
            stage.removeChild(arc);
            evt.currentTarget.cursor = "pointer";
            //evt.currentTarget.x = evt.stageX;
            //evt.currentTarget.y = evt.stageY;


            stage.update();
        });

        image.on('pressup', function (evt) {
            stage.removeChild(arc);
            arc.x = getXValueForArc(evt.currentTarget);
            arc.y = getYValueForArc(evt.currentTarget);

            stage.addChild(arc);
            stage.update();
        });

        image.on('mouseover', function (evt) {
            evt.currentTarget.cursor = "pointer";
            stage.removeChild(arc);
            arc.x = getXValueForArc(evt.currentTarget);
            arc.y = getYValueForArc(evt.currentTarget);
            stage.addChild(arc);
            arc.visible = true;
            stage.update();
        });

        image.on('mouseout', function (evt) {
            stage.removeChild(arc);
            stage.update();
        });
        arc.removeAllEventListeners('click');

        arc.addEventListener('click', function (evt) {
            image.visible = false;
            arc.visible = false;
            stage.removeChild(arc);
            arc.x = getXValueForArc(image);
            arc.y = getYValueForArc(image);
            image.x = getXValueForImage(image);
            image.y = getYValueForImage(image);

            if (image.standardPoint == 0 || image.standardPoint == 3) {
                stage.addChild(arc);
                arc.visible = true;
            }

            image.rotation += 180;
            image.visible = true;

            stage.update();
        });
    }
}

function drawArc(image) {
    arc = new createjs.Shape();
    arc.graphics.beginStroke('#000000').beginFill('#ffffff')
        .arc(0, 0, 10, 0, 1.5 * Math.PI)
        .moveTo(0, 5).lineTo(10, 0)
        .moveTo(10, 0).lineTo(15, 5)
        .endStroke();
    arc.x = image.x + image.width / 2;
    arc.y = image.y + image.height / 2;
}

function drawArcRevert(image) {
    arc = new createjs.Shape();
    arc.graphics.beginStroke('#000000').beginFill('#ffffff')
        .arc(0, 0, 10, 0, 1.5 * Math.PI)
        .moveTo(0, 5).lineTo(10, 0)
        .moveTo(10, 0).lineTo(15, 5)
        .endStroke();
    arc.x = image.x - image.width / 2;
    arc.y = image.y - image.height / 2;
}

function drawArrowLeft(stage, x, y, width, height) {
    stage.removeChild(arrowLeft);
    arrowLeft = new createjs.Shape();
    arrowLeft.graphics.setStrokeStyle(padding).beginStroke('#000000').beginFill('#333333')
        .drawRect(0, 0, width, height)
        .beginStroke('#000000').beginFill('#FFFFFF')
        .moveTo(2.5, 35).lineTo(10, 20).lineTo(10, 50).lineTo(2.5, 35)
        .endStroke();
    arrowLeft.x = x;
    arrowLeft.y = y;

    arrowLeft.cursor = "pointer";

    arrowLeft.on('mouseover', function (evt) {
        var target = evt.currentTarget;
        target.graphics.beginStroke('#FF9966').beginFill('#FF9966')
            .drawRect(0, 0, width, height)
            .beginStroke('#000000').beginFill('#FFFFFF')
            .moveTo(2.5, 35).lineTo(10, 20).lineTo(10, 50).lineTo(2.5, 35)
            .endStroke();
        stage.update();
    });

    arrowLeft.on('mouseout', function (evt) {
        var target = evt.currentTarget;
        target.graphics.setStrokeStyle(padding).beginStroke('#000000').beginFill('#333333')
            .drawRect(0, 0, width, height)
            .beginStroke('#000000').beginFill('#FFFFFF')
            .moveTo(2.5, 35).lineTo(10, 20).lineTo(10, 50).lineTo(2.5, 35)
            .endStroke();
        stage.update();
    });

    stage.addChild(arrowLeft);

    arrowLeft.on('click', function (event) {
        if (startIndex > 0) {
            // remove old object from stage
            for (var i = 0; i < arrObjectInBottom.length; i++) {
                stage.removeChild(arrObjectInBottom[i]);
            }
            for (var t = 0; t < arrNewInstanceObject.length; t++) {
                stage.removeChild(arrNewInstanceObject[t]);
            }
            for (var z = 0; z < arrObjectInWall.length; z++) {
                stage.addChild(arrObjectInWall[z]);
            }
            if (startIndex >= numObjectOneTime) {
                startIndex -= numObjectOneTime;
            } else {
                startIndex = 0;
            }
            // add new object
            arrObjectInBottom = [];
            var j = 0;
            for (var i = startIndex; i < startIndex + maxNumObject; i++) {
                var object = arrImage[i].clone(true);
                object.width = arrImage[i].width;
                object.height = arrImage[i].height;
                var x = getXValue(arrStandardPoint[i], object, j);
                var y = getYValue(arrStandardPoint[i], object);
                object.x = x;
                object.y = y;
                object.oldX = x;
                object.oldY = y;
                object.oldWidth = arrImage[i].width;
                object.oldHeight = arrImage[i].height;
                object.oldObject = arraySVGObject[i];
                object.index = i;
                object.standardPoint = arrStandardPoint[i];
                object.typeObject = arrTypeObject[i];
                object.oldZoomX = x;
                object.oldZoomY = y;
                object.oldZoomWidth = arrImage[i].width;
                object.oldZoomHeight = arrImage[i].height;
                // mouse down
                object.on("mousedown", function (evt) {
                    imageMouseDown(evt, this.oldObject, this.index, this.rotation);
                });
                j++;
                arrObjectInBottom.push(object);
            }
            createListObject();
            stage.update();
        }
    });
}

function drawArrowRight(stage, x, y, width, height) {
    stage.removeChild(arrowRight);
    arrowRight = new createjs.Shape();
    arrowRight.graphics.setStrokeStyle(padding).beginStroke('#000000').beginFill('#333333')
        .drawRect(0, 0, width, height)
        .beginStroke('#000000').beginFill('#FFFFFF')
        .moveTo(12.5, 35).lineTo(5, 20).lineTo(5, 50).lineTo(12.5, 35)
        .endStroke();
    arrowRight.x = x;
    arrowRight.y = y;

    arrowRight.cursor = "pointer";

    arrowRight.on('mouseover', function (evt) {
        var target = evt.currentTarget;
        target.graphics.beginStroke('#FF9966').beginFill('#FF9966')
            .drawRect(0, 0, width, height)
            .beginStroke('#000000').beginFill('#FFFFFF')
            .moveTo(12.5, 35).lineTo(5, 20).lineTo(5, 50).lineTo(12.5, 35)
            .endStroke();
        stage.update();
    });

    arrowRight.on('mouseout', function (evt) {
        var target = evt.currentTarget;
        target.graphics.setStrokeStyle(padding).beginStroke('#000000').beginFill('#333333')
            .drawRect(0, 0, width, height)
            .beginStroke('#000000').beginFill('#FFFFFF')
            .moveTo(12.5, 35).lineTo(5, 20).lineTo(5, 50).lineTo(12.5, 35)
            .endStroke();
        stage.update();
    });
    stage.addChild(arrowRight);

    arrowRight.on('click', function (evt) {
        // remove old object from stage
        for (var i = 0; i < arrObjectInBottom.length; i++) {
            stage.removeChild(arrObjectInBottom[i]);
        }
        for (var t = 0; t < arrNewInstanceObject.length; t++) {
            stage.removeChild(arrNewInstanceObject[t]);
        }
        for (var z = 0; z < arrObjectInWall.length; z++) {
            stage.addChild(arrObjectInWall[z]);
        }
        var remainObject = arrImage.length - startIndex - maxNumObject;
        if (remainObject >= numObjectOneTime) {
            startIndex += numObjectOneTime;
        } else {
            startIndex += remainObject;
        }
        // add new object
        arrObjectInBottom = [];
        var j = 0;
        for (var i = startIndex; i < startIndex + maxNumObject; i++) {
            var object = arrImage[i].clone(true);
            object.width = arrImage[i].width;
            object.height = arrImage[i].height;
            var x = getXValue(arrStandardPoint[i], object, j);
            var y = getYValue(arrStandardPoint[i], object);
            object.x = x;
            object.y = y;
            object.oldX = x;
            object.oldY = y;
            object.oldWidth = arrImage[i].width;
            object.oldHeight = arrImage[i].height;
            object.oldObject = arraySVGObject[i];
            object.index = i;
            object.standardPoint = arrStandardPoint[i];
            object.typeObject = arrTypeObject[i];
            object.oldZoomX = x;
            object.oldZoomY = y;
            object.oldZoomWidth = arrImage[i].width;
            object.oldZoomHeight = arrImage[i].height;
            // mouse down
            object.on("mousedown", function (evt) {
                imageMouseDown(evt, this.oldObject, this.index, this.rotation);
            });
            j++;
            arrObjectInBottom.push(object);
        }
        createListObject();
        stage.update();
    });
}

function getXValue(typeObject, imageObject, boundIndex) {
    switch (typeObject) {
        case 0:
        case 1:
        case 2:
            // left-x, center-y;
            return arrayBoundObjectX[boundIndex] + (100 - imageObject.width) / 2;
            break;
        case 3:
            // center-x, top-y;
            return arrayBoundObjectX[boundIndex] + (100 - imageObject.width) / 2 + imageObject.width / 2;
            break;
        case 4:
            // right-x, top-y;
            return arrayBoundObjectX[boundIndex] + (100 - imageObject.width) / 2 + imageObject.width;
            break;
    }
}

function getYValue(typeObject, imageObject) {
    switch (typeObject) {
        case 0:
            // left-x, center-y;
            return boundObjectY + (100 - imageObject.height) / 2 + imageObject.height / 2;
            break;
        case 1:
            // left-x, bottom-y;
            return boundObjectY + (100 - imageObject.height) / 2 + imageObject.height;
            break;
        case 2:
        case 3:
        case 4:
            // right-x, top-y;
            return boundObjectY + (100 - imageObject.height) / 2;
            break;
    }
}

function getXValueForArc(imageObject) {
    switch (imageObject.standardPoint) {
        case 0:
            if ((imageObject.rotation / 180) % 2 == 0) {
                return imageObject.x + imageObject.width / 2;
                break;
            } else {
                return imageObject.x - imageObject.width / 2;
                break;
            }
        case 1:
            if ((imageObject.rotation / 180) % 2 == 0) {
                return imageObject.x + imageObject.width / 2;
                break;
            } else {
                return imageObject.x - imageObject.width / 2;
                break;
            }
        case 2:
            if ((imageObject.rotation / 180) % 2 == 0) {
                return imageObject.x + imageObject.width / 2;
                break;
            } else {
                return imageObject.x - imageObject.width / 2;
                break;
            }
        case 3:
            // center-x, top-y;
            return imageObject.x;
            break;
        case 4:
            // right-x, top-y;
            if ((imageObject.rotation / 180) % 2 == 0) {
                return imageObject.x - imageObject.width / 2;
                break;
            } else {
                return imageObject.x + imageObject.width / 2;
                break;
            }
    }
}

function getYValueForArc(imageObject) {
    switch (imageObject.standardPoint) {
        case 0:
            return imageObject.y;
            break;
        case 1:
            if ((imageObject.rotation / 180) % 2 == 0) {
                return imageObject.y - imageObject.height / 2;
                break;
            } else {
                return imageObject.y + imageObject.height / 2;
                break;
            }
        case 2:
            if ((imageObject.rotation / 180) % 2 == 0) {
                return imageObject.y + imageObject.height / 2;
                break;
            } else {
                return imageObject.y - imageObject.height / 2;
                break;
            }
        case 3:
            if ((imageObject.rotation / 180) % 2 == 0) {
                return imageObject.y + imageObject.height / 2;
                break;
            } else {
                return imageObject.y - imageObject.height / 2;
                break;
            }
        case 4:
            if ((imageObject.rotation / 180) % 2 == 0) {
                return imageObject.y + imageObject.height / 2;
                break;
            } else {
                return imageObject.y - imageObject.height / 2;
                break;
            }
    }
}

function getXValueForImage(imageObject) {
    switch (imageObject.typeObject) {
        case horizontalObject:
            if ((imageObject.rotation / 180) % 2 == 0) {
                return imageObject.x + imageObject.width;
                break;
            } else {
                return imageObject.x - imageObject.width;
                break;
            }
        case verticalObject:
            return imageObject.x;
            break;
    }
}

function getYValueForImage(imageObject) {
    switch (imageObject.typeObject) {
        case horizontalObject:
            return imageObject.y;
            break;
        case verticalObject:
            if ((imageObject.rotation / 180) % 2 == 0) {
                return imageObject.y + imageObject.height;
                break;
            } else {
                return imageObject.y - imageObject.height;
                break;
            }
    }
}

function drawWithRealSize(object, index) {

    switch (index) {
        case 0:
            drawImage_1(object, arraySVGObject[0][3], arraySVGObject[0][4])
            break;
        case 1:
            drawImage_2(object, arraySVGObject[1][3], arraySVGObject[1][4])
            break;
        case 2:
            drawImage_3(object, arraySVGObject[2][3], arraySVGObject[2][4])
            break;
        case 3:
            drawImage_5(object, arraySVGObject[3][3], arraySVGObject[3][4])
            break;
        case 4:
            drawImage_6(object, arraySVGObject[4][3], arraySVGObject[4][4])
            break;
        case 5:
            drawImage_13(object, arraySVGObject[5][3], arraySVGObject[5][4])
            break;
        case 6:
            drawImage_14(object, arraySVGObject[6][3], arraySVGObject[6][4])
            break;
        case 7:
            drawImage_15(object, arraySVGObject[7][3], arraySVGObject[7][4])
            break;
        case 8:
            drawImage_17(object, arraySVGObject[8][3], arraySVGObject[8][4])
            break;
        case 9:
            drawImage_18(object, arraySVGObject[9][3], arraySVGObject[9][4])
            break;

    }

}


function drawImage_1(object, width_px, height_px) {

    var widthDraw = parseInt((width_px - converMMtoPX(widthPillar) ) * scale * zoom);
    var width = parseInt((width_px) * scale * zoom);
    var height = parseInt(height_px * scale * zoom);

    object.graphics.setStrokeStyle(padding).beginStroke('#000000').beginFill('#FFFFFF').setStrokeDash([5, 0])
        .drawRect(0, 0, widthDraw, widthDraw/20)
        .setStrokeDash([5, 5])
        .moveTo(0, 0).lineTo(0, -widthDraw)
        .arc(0, 0, widthDraw, 1.5 * Math.PI, 0 * Math.PI)
        .endStroke();
    object.width = widthDraw;
    object.height = height;
}

function drawImage_2(object, width_px, height_px) {

    var widthDraw = parseInt((width_px - converMMtoPX(widthPillar)) * scale * zoom);
    var width = parseInt(width_px * scale * zoom);
    var height = parseInt((height_px - 10) * scale * zoom);

    object.graphics.setStrokeStyle(padding).beginStroke('#000000').beginFill('#FFFFFF').setStrokeDash([5, 0])
        .drawRect(0, 0, widthDraw, widthDraw/20)
        .setStrokeDash([5, 5])
        .moveTo(0, 0)
        .arc(widthDraw, 0, widthDraw, 1 * Math.PI, 1.5 * Math.PI)
        .lineTo(widthDraw, 0);

    object.width = widthDraw;
    object.height = height;
}

function drawImage_3(object, width_px, height_px) {

    var widthDraw = parseInt((width_px - converMMtoPX(widthPillar) ) * scale * zoom);
    var width = parseInt(width_px * scale * zoom);
    var height = parseInt(height_px * scale * zoom);

    // object.graphics.setStrokeStyle(padding).beginStroke('#000000').beginFill('#FFFFFF')
    //     .moveTo(0, 0).lineTo(0, 35).lineTo(width, 35).lineTo(width, 0).lineTo(0, 0)
    //     .setStrokeDash([5, 5])
    //     .lineTo(width/2, 0).arc(width, 0, width/2, 1 * Math.PI, 1.5 * Math.PI)
    //     .lineTo(width, 0)
    //     .moveTo(0, 0).lineTo(0, -width/2).arc(0, 0, width/2, 1.5 * Math.PI, 0 * Math.PI)
    //     .endStroke();

    object.graphics.setStrokeStyle(padding).beginStroke('#000000').beginFill('#FFFFFF')
        .moveTo(0, 0).lineTo(0, -height / 2).lineTo(widthDraw, -height / 2).lineTo(widthDraw, 0).lineTo(0, 0)
        .lineTo(0, height / 2).lineTo(widthDraw, height / 2).lineTo(widthDraw, 0)
        .endStroke();

    object.width = widthDraw;
    object.height = height;
}


function drawImage_5(object, width_px, height_px) {

    var widthDraw = parseInt((width_px - converMMtoPX(widthPillar) ) * scale * zoom);
    var width = parseInt(width_px * scale * zoom);
    var height = parseInt(height_px * scale * zoom);


    object.graphics.setStrokeStyle(padding).beginStroke('#000000').beginFill('#FFFFFF')
        .moveTo(0, 0).lineTo(0, -5).lineTo(widthDraw, -5).lineTo(widthDraw, 0).lineTo(0, 0)
        .lineTo(0, 5).lineTo(widthDraw, 5).lineTo(widthDraw, 0)
        .endStroke();
    object.width = widthDraw;
    object.height = height;
    object.cursor = "pointer";
}

function drawImage_6(object, width_px, height_px) {

    var width = parseInt(width_px * scale * zoom);
    var height = parseInt(height_px * scale * zoom);

    object.graphics.setStrokeStyle(padding).beginStroke('#000000').beginFill('#FFFFFF')
        .moveTo(0, 0).lineTo(0, -5).lineTo(width, -5).lineTo(width, 5).lineTo(0, 5).lineTo(0, 0)
        .moveTo(0, -2).lineTo(width / 2, -2)
        .moveTo(width / 2, 2).lineTo(width, 2)
        .endStroke();
    object.width = width;
    object.height = height;
    object.cursor = "pointer";
}

/* Shape set to left/right wall */
function drawImage_13(object, width_px, height_px) {

    var heightDraw = parseInt((height_px - converMMtoPX(widthPillar) ) * scale * zoom);

    var width = parseInt(width_px * scale * zoom);
    var height = parseInt(height_px * scale * zoom);

    object.graphics.setStrokeStyle(padding).beginStroke('#000000').beginFill('#FFFFFF').setStrokeDash([5, 0])
        .drawRect(0, 0, -heightDraw/20, heightDraw)
        .setStrokeDash([5, 5])
        .moveTo(0, 0).lineTo(heightDraw, 0)
        .arc(0, 0, heightDraw, 0 * Math.PI, 0.5 * Math.PI)
        .endStroke();
    object.width = width;
    object.height = heightDraw;
    object.cursor = "pointer";
}

function drawImage_14(object, width_px, height_px) {

    var heightDraw = parseInt((height_px - converMMtoPX(widthPillar) ) * scale * zoom);
    var width = parseInt(width_px * scale * zoom);
    var height = parseInt(height_px * scale * zoom);

    object.graphics.setStrokeStyle(padding).beginStroke('#000000').beginFill('#FFFFFF').setStrokeDash([5, 0])
        .drawRect(0, 0, -heightDraw/20, heightDraw)
        .setStrokeDash([5, 5])
        .moveTo(0, 0)
        .arc(0, heightDraw, heightDraw, 1.5 * Math.PI, 0 * Math.PI)
        .lineTo(0, heightDraw)
        .endStroke();

    object.width = width;
    object.height = heightDraw;
    object.cursor = "pointer";
}

function drawImage_15(object, width_px, height_px) {

    var heightDraw = parseInt((height_px - converMMtoPX(widthPillar) ) * scale * zoom);
    var width = parseInt(width_px * scale * zoom);
    var height = parseInt(height_px * scale * zoom);

    // object.graphics.setStrokeStyle(padding).beginStroke('#000000').beginFill('#FFFFFF')
    //     .moveTo(0, 0).lineTo(0, height).lineTo(-35, height).lineTo(-35, 0).lineTo(0, 0)
    //     .setStrokeDash([5, 5])
    //     .moveTo(0, 0).lineTo(height/2, 0).arc(0, 0, height/2, 0 * Math.PI, 0.5 * Math.PI)
    //     .arc(0, height, height/2, 1.5 * Math.PI, 0 * Math.PI)
    //     .moveTo(height/2, height).lineTo(0, height)
    //     .endStroke();
    object.graphics.setStrokeStyle(padding).beginStroke('#000000').beginFill('#FFFFFF')
        .moveTo(0, 0).lineTo(width / 2, 0).lineTo(width / 2, heightDraw).lineTo(-width / 2, heightDraw).lineTo(-width / 2, 0).lineTo(0, 0).lineTo(0, heightDraw)
        .endStroke();
    object.width = width;
    object.height = heightDraw;
    object.cursor = "pointer";
}

function drawImage_17(object, width_px, height_px) {

    var heightDraw = parseInt((height_px - converMMtoPX(widthPillar) ) * scale * zoom);
    var width = parseInt(width_px * scale * zoom);
    var height = parseInt(height_px * scale * zoom);

    object.graphics.setStrokeStyle(padding).beginStroke('#000000').beginFill('#FFFFFF')
        .moveTo(0, 0).lineTo(5, 0).lineTo(5, heightDraw).lineTo(-5, heightDraw).lineTo(-5, 0).lineTo(0, 0).lineTo(0, heightDraw)
        .endStroke();
    object.width = width;
    object.height = heightDraw;
    object.cursor = "pointer";
}

function drawImage_18(object, width_px, height_px) {

    var width = parseInt(width_px * scale * zoom);
    var height = parseInt(height_px * scale * zoom);

    object.graphics.setStrokeStyle(padding).beginStroke('#000000').beginFill('#FFFFFF')
        .moveTo(0, 0).lineTo(5, 0).lineTo(5, height).lineTo(-5, height).lineTo(-5, 0).lineTo(0, 0)
        .moveTo(2, 0).lineTo(2, height / 2)
        .moveTo(-2, height / 2).lineTo(-2, height)
        .endStroke();
    object.width = width;
    object.height = height;
    object.cursor = "pointer";
    // add type of object
}

function converPxtoMmWithScalenZoom(px) {
    return mm = px * 455 / (  100 * zoom * scale);
}

function converMMtoPXWithScalenZoom(mm) {
    return px = mm * 100 * zoom * scale / 455;
}

function incTransitionState( ev )
{

	if ( transitionState >= STATE_TRANSITION_SET_3DVIEW )
	{
		return;
	}
	// 0: 3DView	1:  Geometry	2: Esitamte	3: Next	4: pillar	5: balcony	6: roof	 7: zoom scale
	transitionState = transitionState + 1;
	
    alert(guideTextList[transitionState]);
	
	switch(transitionState)
	{
	case STATE_TRANSITION_RESIZE_FLOOR: // zoom + scale
		
		disableOpacity(3);
		disableOpacity(7);
			
        diablog(stage, guideTextList[transitionState]);
		
		break;
	case STATE_TRANSITION_SET_OBJECT: // select the object 
	
    	stage.removeChild(scaleTopRight);
    	stage.removeChild(scaleBottomLeft);
    	stage.removeChild(scaleBottomRight);
    	
		// disable zoom
		enableOpacity(7);
					
        diablog(stage, guideTextList[transitionState]);
		break;
		
	//case STATE_TRANSITION_SET_OBJECT_CANFINISH: // next roof
	//
    //    nextBtn.addEventListener('click', incTransitionState);
	//	disableOpacity(3);
	//	
    //    diablog(stage, guideTextList[3]);
	//	break;
	case STATE_TRANSITION_SET_PILLAR: // adjust pillar
		handleWallAndPillar(stage, zoom);
		
        diablog(stage, guideTextList[transitionState]);
		// disable zoom
		//enableOpacity(7);

		break;
		
	case STATE_TRANSITION_SET_ROOF: //roof
		
		disableOpacity(6);// can set roof
		
        diablog(stage, guideTextList[transitionState]);
        
		break;
	case STATE_TRANSITION_SET_3DVIEW: // view 3D
	
        nextBtn.removeEventListener('click', incTransitionState);
		enableOpacity(3);
		
		disableOpacity(0);	// can view 3D
		disableOpacity(2); // can estimate
			
        diablog(stage, guideTextList[transitionState]);	
		break;	
	}
	stage.update();
}



function setTransitionState(state)
{
	// 0: 3DView	1:  Geometry	2: Esitamte	3: Next	4: pillar	5: balcony	6: roof	 7: zoom scale
	
	if(state <= transitionState)	return;
	
	transitionState = state;
	
	switch(transitionState)
	{
	case STATE_TRANSITION_RESIZE_FLOOR: // zoom + scale
		
		disableOpacity(3);
		disableOpacity(7);
			
        diablog(stage, guideTextList[transitionState]);
		
		break;
	case STATE_TRANSITION_SET_OBJECT: // select the object 
    
        //nextBtn.removeEventListener('click', incTransitionState);
		//enableOpacity(3);
		// disable zoom
		enableOpacity(7);
					
        diablog(stage, guideTextList[transitionState]);
		break;
		
	//case STATE_TRANSITION_SET_OBJECT_CANFINISH: // next roof
	//
    //    nextBtn.addEventListener('click', incTransitionState);
	//	disableOpacity(3);
	//	
    //    diablog(stage, guideTextList[3]);
	//	break;
	case STATE_TRANSITION_SET_PILLAR: // adjust pillar
		handleWallAndPillar(stage, zoom);
		
        diablog(stage, guideTextList[transitionState]);
		// disable zoom
		//enableOpacity(7);

		break;
		
	case STATE_TRANSITION_SET_ROOF: //roof
		disableOpacity(6);// can set roof
		
        diablog(stage, guideTextList[transitionState]);
        
		break;
	case STATE_TRANSITION_SET_3DVIEW: // view 3D
	
    	stage.removeChild(scaleTopRight);
    	stage.removeChild(scaleBottomLeft);
    	stage.removeChild(scaleBottomRight);
	
        nextBtn.removeEventListener('click', incTransitionState);
		enableOpacity(3);
		
		disableOpacity(0);	// can view 3D
		disableOpacity(2); // can estimate
		disableOpacity(6);// can set roof
			
        diablog(stage, guideTextList[transitionState]);	
		break;	
	}
	stage.update();
}


function creaetOpacityList()
{

    log_Bgd = new createjs.Shape();
    
    log_Bgd.graphics.setStrokeStyle(padding).beginStroke('#FFFFFF').beginFill('#00FF00')
        .drawRect(0, 0, 800, 50);
        
    log_Bgd.x = 800;
    log_Bgd.y = 0;
    stage.addChild(log_Bgd);
    
	createOpacityShape(  0);
	createOpacityShape(  1);
	createOpacityShape(  2);
	createOpacityShape(  3);
	createOpacityShape(  4);
	createOpacityShape(  5);
	createOpacityShape(  6);
	createOpacityShape(  7);
}


// object to control
	// 0: 3DView	1:  Geometry	2: Esitamte	3: Next	4: pillar	5: balcony	6: roof	 7: zoom scale
	// x; y; widht; heigth
	
var opacityList = [];
var changeState = 0;
	
var btnPosList = 	[	[ 0, 0, 200, 50	],
						[ 200, 0, 200, 50	],
						[ 400, 0, 200, 50	],
						[ 600, 0, 200, 50	],
						[ 0, 50, 100, 100	],
						[ 0, 150, 100, 95	],
						[ 0, 245, 100, 110	],
						[ 1019.45, 727.2, 259.6, 102.6	]
					];
		

function createOpacityShape( index)
{
	x = btnPosList[index][0];
	y = btnPosList[index][1];
	width = btnPosList[index][2];
	height = btnPosList[index][3];
	var opacity = new createjs.Shape();
    opacity.graphics.setStrokeStyle(padding).beginFill('#FFFFFF')
        .moveTo(0, 0).lineTo(width, 0).lineTo(width, height ).lineTo(0, height).lineTo(0, 0);
    opacity.x = x;
    opacity.y = y;
    opacity.alpha = 0.5;
    
    stage.addChild(opacity);
    opacityList.push(opacity);
}

function disableOpacity(Index)
{
	opacityList[Index].alpha = 0;
}

function enableOpacity(Index)
{
	opacityList[Index].alpha = 0.5;
}

function createInitObjectInstance(data ) {
	
	var type = parseInt(data[1]);
	var name = data[8];
	
	var xMm = parseFloat(data[2]);
	var yMm = parseFloat(data[3]);
	var widthMm = parseFloat(data[4]);
	var heightMm = parseFloat(data[5]);
	
	if( type == TYPE_DOOR || type == TYPE_WINDOW )
	{
		var index = searchBottomObject(name);
		if(Math.round(widthMm) < Math.round(heightMm))
		{
			index += 5;
		}
	
		var xPx = xMm*(scale * zoom);
		var yPx = yMm*(scale * zoom);
		
	    var object = arrObjectInBottom[index];
	    var newImage = object.clone(true);
    	newImage.x = xPx;
    	newImage.y = yPx;
    	newImage.width = object.oldWidth;
    	newImage.height = object.oldHeight;
    	// set origin position
    	newImage.oldX = object.oldX;
    	newImage.oldY = object.oldY;
    	newImage.oldWidth = object.oldWidth;
    	newImage.oldHeight = object.oldHeight;
    	newImage.cursor = "pointer";
    	newImage.oldObject = arraySVGObject[index];
    	newImage.index = index;
    	newImage.standardPoint = object.standardPoint;
    	newImage.typeObject = object.typeObject;
    	newImage.oldZoomX = object.oldX;
    	newImage.oldZoomY = object.oldY;
    	newImage.oldZoomWidth = object.width;
    	newImage.oldZoomHeight = object.height;
    	// mouse down
    	newImage.on("mousedown", function (evt) {
    	    imageMouseDown(evt, this.oldObject, this.index, this.rotation);
    	});
    	
	    drawWithRealSize(newImage, index);
    	newImage.settedFlag = true;
    	newImage.x = xPx;
    	newImage.y = yPx;
    
	    
    	stage.addChild(newImage);
	    stage.update();
        arrObjectInWall.push(newImage); 
	    if (getByTypeAndXY(type, xMm, yMm) == null) {
		    setArray3dCad( data[8], type, parseFloat(data[2]), parseFloat(data[3]), parseFloat(data[4]), parseFloat(data[5]), parseFloat(data[6]), parseFloat(data[7]), 0, 0, 0, 0);
	    }
    }
    else if( type == TYPE_STEPPER)
	{
		var index = searchBottomObject(name);
		if(Math.round(widthMm) < Math.round(heightMm))
		{
			index += 5;
		}
	
		var xPx = converMMtoPXWithScalenZoom(xMm);
		var yPx = converMMtoPXWithScalenZoom(yMm);
		
	    var object = arrObjectInBottom[index];
	    var newImage = object.clone(true);
    	newImage.x = xPx;
    	newImage.y = yPx;
    	newImage.width = object.oldWidth;
    	newImage.height = object.oldHeight;
    	// set origin position
    	newImage.oldX = object.oldX;
    	newImage.oldY = object.oldY;
    	newImage.oldWidth = object.oldWidth;
    	newImage.oldHeight = object.oldHeight;
    	newImage.cursor = "pointer";
    	newImage.oldObject = arraySVGObject[index];
    	newImage.index = index;
    	newImage.standardPoint = object.standardPoint;
    	newImage.typeObject = object.typeObject;
    	newImage.oldZoomX = object.oldX;
    	newImage.oldZoomY = object.oldY;
    	newImage.oldZoomWidth = object.width;
    	newImage.oldZoomHeight = object.height;
    	// mouse down
    	newImage.on("mousedown", function (evt) {
    	    imageMouseDown(evt, this.oldObject, this.index, this.rotation);
    	});
    	
	    drawWithRealSize(newImage, index);
    	newImage.settedFlag = true;
    	newImage.x = xPx;
    	newImage.y = yPx;
    
	    
    	stage.addChild(newImage);
        arrStepper.push(newImage); 
	    if (getByTypeAndXY(type, xMm, yMm) == null) {
		    setArray3dCad( data[8], type, parseFloat(data[2]), parseFloat(data[3]), parseFloat(data[4]), parseFloat(data[5]), parseFloat(data[6]), parseFloat(data[7]), 0, 0, 0, 0);
	    }
        
    }
    isZoom = 1;
    isRoof2D = 0;
    
	stage.update();
    
}

function createInitPillarInstance(data ) {
	
	var type = parseInt(data[1]);
	
    if( type == TYPE_PILLAR)
    {
		var name = data[8];
		
		var xMm = parseFloat(data[2]);
		var yMm = parseFloat(data[3]);
		var widthMm = parseFloat(data[4]);
		var heightMm = parseFloat(data[5]);
		
	    if (getByTypeAndXY(TYPE_PILLAR, xMm, yMm) == null) {
	        var pillar = createPillarWithPixel(converMMtoPXWithScalenZoom(xMm), converMMtoPXWithScalenZoom(yMm), converMMtoPXWithScalenZoom(widthPillar));
	        stage.addChild(pillar);
	        pillarIndexStage.push(pillar);
	    }
	    if (getByTypeAndXY(type, xMm, yMm) == null) {
		    setArray3dCad( data[8], type, parseFloat(data[2]), parseFloat(data[3]), parseFloat(data[4]), parseFloat(data[5]), parseFloat(data[6]), parseFloat(data[7]), 0, 0, 0, 0);
	    }
	}
    
	stage.update();
}

function createInitRoofInstance(data ) {
	
	var type = parseInt(data[1]);
	if (type >= 100 )	
	{
	
		var name = data[8];
		
		var xMm = parseFloat(data[2]);
		var yMm = parseFloat(data[3]);
		var widthMm = parseFloat(data[4]);
		var heightMm = parseFloat(data[5]);
		//roof();
		loadRoof( data[8], type, parseFloat(data[2]), parseFloat(data[3]), parseFloat(data[4]), parseFloat(data[5]) ) ;
	}
    
	stage.update();
}
function searchBottomObject(name)
{
    for(var i = 0; i<arrObjectInBottom.length; i++)
    {
    	if(arrObjectInBottom[i].oldObject[1] == name)
    	{
    		return i;
    	}
    }
}
