﻿var canvasPainter;
var siteDB;
var arrayKey = [];
var arrayTxtKey = [];
var delNode = null;

var solt = Math.floor(Math.random() * 1000000001);
var sid = Math.floor(Math.random() * 1000000001);


var lastSynx = 0;
var lastSynxMsg = 0;
var isPadClient = false;
var this_key = '';
var excanvas = false;

var canvasScale = 1
var canvasWith = 900;
var textoutHeightDelts = 0;

var canvasHeight = 700;


function ClrMousedown() {
    $('.jPickerContainer').mousedown(function () {
        return false;
    })

}


$(document).ready(
    function () {
        document.getElementById("LinkKey").value = location.href;
        setTimeout("ClrMousedown()", 500);

        this_key = getQueryKey();

        if (this_key != null && this_key != "" && this_key.length < 6 || this_key.length > 8) {
            alert(wrong_address_msg);
            if (lng != "en") {
                location.href = 'http://pomidor.com/' + lng;
            }
            else {
                location.href = 'http://pomidor.com/';
            }
            return false;
        }

        var isCtrl = false;

        if (!hasKey()) {
            ColorPicks();
        }

        $(document).keyup(function (e) {

            if (e.which == 17) isCtrl = false;
        }).keydown(function (e) {
            if (e.which == 17) isCtrl = true;


            if (e.which == 90 && isCtrl == true) {

                //run code for CTRL+Z

                siteDB.removeLastNode();

                return false;

            }
        });


        try {
            document.createEvent("TouchEvent");
            isPadClient = true;
        }
        catch (e) {
            isPadClient = false;
        }


        if (!hasKey()) {
            document.getElementById("imgClouds").style.display = "block";
            document.getElementById("ideaBtn").style.display = "block";
            document.getElementById("ideaText").style.display = "block";
            document.getElementById("canvasContainer").style.display = "none";

            document.getElementById("toolPanelMain").style.top = "107px";

            document.getElementById("tableLng").style.top = "15px";
            document.getElementById("logoPomidor").style.display = "block";
            document.getElementById("toolPanelBorderColor").style.top = "117px";
            document.getElementById("imgWait").style.top = "445px";

            document.getElementById("chkBodyColor").checked = true;
            document.getElementById("spanFillColorPkr").style.visibility = "visible";

            return;
        }

        if (!excanvas) {
            InitCanvas()
        }

        for (i = 1; i <= 1; i++) {
            document.getElementById("LinkLng" + i).href = document.getElementById("LinkLng" + i).href + '?' + this_key;
        }

        document.getElementById("linkLogo").style.display = "none";

        //document.getElementById("LinkLng").href = document.getElementById("LinkLng").href + this_key;

        document.getElementById("linkSmallLogo").style.display = "block";
        document.getElementById("imgClouds").style.display = "none";
        document.getElementById("ideaBtn").style.display = "none";
        document.getElementById("ideaText").style.display = "none";
        document.getElementById("canvasContainer").style.display = "block";
        $.ajax({
            type: 'POST',
            dataType: 'text',
            url: lng_subfolder + 'draw.asmx/addSolt',
            data: {
                solt: solt,
                isPadClient: isPadClient,
                lng: lng
            }
        });



    });


function InitCanvasIE() {
    if (excanvas && hasKey()) {
        InitCanvas()
    }
}


function InitCanvas() {



    disableSelection(document.getElementById("canvas"));
    disableSelection(document.getElementById("canvasInterface"));


    pagerUpdate();


    canvas2 = document.getElementById("canvas");
    context = canvas2.getContext("2d");

    canvasInterface2 = document.getElementById("canvasInterface");
    contextI = canvasInterface2.getContext("2d");

    canvasPainter = new CanvasPainter({ x: 90, y: 110 });
    siteDB = new siteDB();    

    if (isPadClient) {
        document.getElementById("liText").style.display = "none";
        document.getElementById("liPolygon").style.display = "none";
    }

    //if (document.all) {
    if ( typeof window.addEventListener != "undefined" )
    {

        if (isPadClient) {
            
            document.getElementById("canvasInterface").addEventListener('touchstart', function (e) { e.preventDefault(); canvasPainter.mouseDownActionPerformed(e) }, false);
            document.getElementById("canvasInterface").addEventListener('touchmove', function (e) { e.preventDefault(); canvasPainter.mouseMoveActionPerformed(e) }, false);
            document.getElementById("canvasInterface").addEventListener('touchend', function (e) { canvasPainter.mouseUpActionPerformed(e) }, false);
            //document.addEventListener("mousemove", function (e) { mouseMoveBody(e) }, false);
        } else {
            //document.getElementById("canvasInterface").addEventListener("mousedown", function (e) { canvasPainter.mouseDownActionPerformed(e) }, false);
            //document.getElementById("canvasInterface").addEventListener("mouseup", function (e) { canvasPainter.mouseUpActionPerformed(e) }, false);
            //document.getElementById("canvasInterface").addEventListener("mousemove", function (e) { canvasPainter.mouseMoveActionPerformed(e) }, false);

            document.body.addEventListener("mousedown", function (e) { canvasPainter.mouseDownActionPerformed(e) }, false);
            document.body.addEventListener("mouseup", function (e) { mouseUpBody(e) }, false);
            document.body.addEventListener("mousemove", function (e) { mouseMoveBody(e) }, false);
        }
    } else {

        //document.getElementById("canvasInterface").attachEvent("onmousedown", function (e) { canvasPainter.mouseDownActionPerformed(e) });
        //document.getElementById("canvasInterface").attachEvent("onmouseup", function (e) { canvasPainter.mouseUpActionPerformed(e) });
        //document.getElementById("canvasInterface").attachEvent("onmousemove", function (e) { canvasPainter.mouseMoveActionPerformed(e) });

        document.body.attachEvent("onmousedown", function (e) { canvasPainter.mouseDownActionPerformed(e) });
        document.body.attachEvent("onmouseup", function (e) { mouseUpBody(e) });        
        document.body.attachEvent("onmousemove", function (e) { mouseMoveBody(e) }, false);

    }

    setTimeout("GetCookSetings()",59);

    context.lineJoin = "round";
    contextI.lineJoin = "round";
    context.lineCap = "round";
    contextI.lineCap = "round";

    setInterval("timerEvent()", 1001)

}

function onClickZoom() {

    if (canvasScale == 1) {
        canvasScale = 2;
        document.getElementById("Btn_zoom").src = lng_subfolder + "img_t/zoom_3.PNG";
    }
    else {
        canvasScale = 1;
        document.getElementById("Btn_zoom").src = lng_subfolder + "img_t/zoom_1.PNG";
    }

    reSize(true);
    unfocus();
    return false;

}

function hasKey() {

    if (this_key == null || this_key.length == '') {
        return false;
    }

    return true;

}


function veryClose(Ax,Ay, Bx, By) {

    if (Math.abs(Ax - Bx) <=7 && Math.abs(Ay - By) <= 7)
        return true;
    else
        return false;

}


function completePolygon() {

    var currentNode = siteDB.drawing[canvasPainter.currentNodeIndex];

    if (!currentNode) return; // empty

    if (currentNode.a != 0) return;

    if (!currentNode.p) return;

    //too small
    if (currentNode.p.length <= 2) {
        siteDB.drawing.splice(canvasPainter.currentNodeIndex, 1);
    }
    else {
        var firstPoint = currentNode.p[0];
        var lastPoint = currentNode.p[currentNode.p.length - 1];

        // add first point to the end and repaint
        currentNode.p[currentNode.p.length] = { x: firstPoint.x, y: firstPoint.y };
        SendPolygon(siteDB.drawing[canvasPainter.currentNodeIndex]);
        document.getElementById("idRemoveLastNodes").style.display = "block";
    }

    canvasPainter.currentNodeIndex = -1;
    canvasPainter.clearInterface();
    siteDB.paintDrawing();
    canvasPainter.fatNode = false;
    canvasPainter.mouseMoveTrigger = false;

}


function GetCookSetings() {

    solt = Get_Cookie('pomisolt');
    if (!solt) {
        solt = Math.floor(Math.random() * 1000000001);
        Set_Cookie('pomisolt', solt, 300, '/', '', '');
    }

    clickAction = Get_Cookie('clickAction');
    if (!clickAction) {
        clickAction = 'pencil';
    }
    poClick(clickAction);    



    erzWidth = Get_Cookie('erzWidth');
    if (erzWidth) {
        setLineWidth(erzWidth, false);
    }
    else {
        setLineWidth(5, false);
    }

    LineWidth = Get_Cookie('LineWidth');
    if (LineWidth) {
        setLineWidth(LineWidth, false);
    }
    else
    {
        setLineWidth(3, false);
    }

    zoom100 = Get_Cookie('zoom100');
    if (zoom100 && zoom100 === "true") {
        canvasScale = 2;
        reSize(false);
        document.getElementById("Btn_zoom").src = lng_subfolder + "img_t/zoom_3.PNG";
    }

    savedLineColor = Get_Cookie('savedLineColor');
    if (!savedLineColor) {
        // deft: #FF7F00
        savedLineColor = (16 * 15 + 15) + ',' + (16 * 7 + 15) + ',' + (16 * 0 + 0);
    }
    var arrLineColorRGB = savedLineColor.split(",");
    canvasPainter.setLineColor(arrLineColorRGB[0], arrLineColorRGB[1], arrLineColorRGB[2]);
    $('#lineColorPkr').val('#' + decimalToHex(arrLineColorRGB[0]) + decimalToHex(arrLineColorRGB[1]) + decimalToHex(arrLineColorRGB[2]));

    savedFillColor = Get_Cookie('savedFillColor');
    if (!savedFillColor) {
        // deft: #1E90FF
        savedFillColor = (16 * 1 + 14) + ',' + (9 * 16 + 0) + ',' + (16 * 15 + 15);
    }
    var arrFillColorRGB = savedFillColor.split(",");
    canvasPainter.setFillColor(arrFillColorRGB[0], arrFillColorRGB[1], arrFillColorRGB[2]);
    $('#fillColorPkr').val('#' + decimalToHex(arrFillColorRGB[0]) + decimalToHex(arrFillColorRGB[1]) + decimalToHex(arrFillColorRGB[2]));


    this_key_saved = Get_Cookie('this_key_saved');
    if (this_key == this_key_saved) {

        this_page_saved = Get_Cookie('pomipage');
        if (this_page_saved) {
            this_page = parseInt(this_page_saved);
        }
    }
    else {
        this_key.length = 1;
        Set_Cookie('pomipage', this_page, 300, '/', '', '');
    }
    Set_Cookie('this_key_saved', this_key, 300, '/', '', '');

    ColorPicks();

}

function decimalToHex(d) {
    var hex = Number(parseInt(d)).toString(16);
    hex = "00".substr(0, 2 - hex.length) + hex;
    return hex; 
}





