var initObject = [];
var array3dCad = [];
var array3dCad0 = [];
var array3dCad1 = [];
var array3dCad2 = [];
var array3dCad3 = [];
var arrayPositionCanSetPillar = [];

var createArray3dCad = function (no, fileName, type, start_X, start_Y, width_X, width_Y, height_startpoint, height_endpoint, widthObject_x, widthObject_y, widthObject_r, pointObject_r) {
    array3dCad0 = [no];
    array3dCad1 = [type];
    array3dCad2 = [start_X, start_Y, width_X, width_Y, height_startpoint, height_endpoint];
    array3dCad3 = [fileName, widthObject_x, widthObject_y, widthObject_r, pointObject_r];

    array3dCad.push([array3dCad0, array3dCad1, array3dCad2, array3dCad3]);
    array3dCad = array3dCad.sort(comparator);
}

function comparator(a, b) {
    if (a[0][0] < b[0][0]) {
        return -1;
    } else if (a[0][0] > b[0][0]) {
        return 1;
    } else {
        return 0;
    }
}

var getArray3dCad = function (no) {
    for (var i = 0; i < array3dCad.length; i++) {
        if (array3dCad[i][0][0] == no) {
            return array3dCad[i];
        }
    }
}

var getArray3dCadByType = function (type) {
    var result = [];
    for (var i = 0; i < array3dCad.length; i++) {
        if (array3dCad[i][1][0] == type) {
            result.push(array3dCad[i]);
        }
    }
    return result;
}

var getByTypeAndXY = function (type, x, y) {
    for (var i = 0; i < array3dCad.length; i++) {
        if (array3dCad[i][1][0] == type) {
            if (Math.abs(array3dCad[i][dxyIndex][0] - x) <= 20 && Math.abs(array3dCad[i][dxyIndex][1] - y) <= 20) {
                return array3dCad[i];
            }
        }
    }
    return null;
}

var deleteArray3dCad = function (no) {
    for (var i = 0; i < array3dCad.length; i++) {
        if (array3dCad[i][0][0] == no) {
            array3dCad.splice(i, 1);
            break;
        }
    }
}

var updateArray3dCad = function (no, fileName, type, start_X, start_Y, width_X, width_Y, height_startpoint, height_endpoint, widthObject_x, widthObject_y, widthObject_r, pointObject_r) {
    deleteArray3dCad(no);
    createArray3dCad(no, fileName, type, start_X, start_Y, width_X, width_Y, height_startpoint, height_endpoint, widthObject_x, widthObject_y, widthObject_r, pointObject_r);
}

var setArray3dCad = function (fileName, type, start_X, start_Y, width_X, width_Y, height_startpoint, height_endpoint, widthObject_x, widthObject_y, widthObject_r, pointObject_r) {

    var index = 1;
    var length = array3dCad.length;
    if (length > 0) {
        var array3dCadLastElement = array3dCad[length - 1];
        index = array3dCadLastElement[0][0] + 1;
    }
    createArray3dCad(index, fileName, type, start_X, start_Y, width_X, width_Y, height_startpoint, height_endpoint, widthObject_x, widthObject_y, widthObject_r, pointObject_r);
    return index;
}

//#################### Function for handle list position can set pillar ################
// Add a position can set pillar
var addPillarPosition = function (pillarX, pillarY) {
    arrayPositionCanSetPillar.push([pillarX, pillarY]);
}

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

var createArray3dCad = function (no, fileName, type, start_X, start_Y, width_X, width_Y, height_startpoint, height_endpoint, widthObject_x, widthObject_y, widthObject_r, pointObject_r) {
    array3dCad0 = [no];
    array3dCad1 = [type];
    array3dCad2 = [start_X, start_Y, width_X, width_Y, height_startpoint, height_endpoint];
    array3dCad3 = [fileName, widthObject_x, widthObject_y, widthObject_r, pointObject_r];

    array3dCad.push([array3dCad0, array3dCad1, array3dCad2, array3dCad3]);
    array3dCad = array3dCad.sort(comparator);
}

var saveDataToCsv = function(){

    // Prepare data to save
	var data = [["roofRotate", rotate],
				["index", "type", "start_X", "start_Y", "width_X", "width_Y", "height_startpoint", "height_endpoint" , "name"]];
	
	for ( var i = 0; i< array3dCad.length; i++){
		var item = array3dCad[i];
		var row = [item[0], item[1], item[2][0], item[2][1], item[2][2], item[2][3], item[2][4], item[2][5], item[3][0] ];
		data.push(row);
	}

    var fullData ="";
    var dataString = "";
    data.forEach(function(infoArray, index){

       dataString = infoArray.join(",");
       fullData += dataString + '|';
    }); 
    
    //var jsonString = JSON.stringify(data);
    document.getElementById("list-data").value = fullData;
    document.getElementById("formsave").submit();

    // Show popup for input infomation to send mail
    // Get the modal
    var modal = document.getElementById('saveModal');

    modal.style.display = "block";
    
    // Set Csv data to submit
    document.getElementById("csv-data").value = fullData;
    
    // Get the <span> element that closes the modal
    var span = document.getElementsByClassName("saveclose")[0];

    // When the user clicks on <span> (x), close the modal
    span.onclick = function() {
        modal.style.display = "none";
    }

    // When the user clicks anywhere outside of the modal, close it
    window.onclick = function(event) {
        if (event.target == modal) {
            modal.style.display = "none";
        }
    }

    // Handle send mail click button
    // get button request send
    var btnSendMailRequest = document.getElementById("btnSendMailRequest");
    // When click then submmit form and close popup
    btnSendMailRequest.onclick = function(event) {
        //close modal
        //modal.style.display = "none";
        // Validate data
        if(!validateFormSendMailRequestData()) {return};
        //Disable send mail button
        btnSendMailRequest.disabled = true;
        // Raise sending mail status
        lblstatus = document.getElementById('reqtatus');
        lblstatus.innerHTML = 'Email is sending ...';
        //Do submit
        var frmSendMailRequest = document.getElementById("frmSendMailRequest");
         $.ajax({
            url: 'sendEmailRequestEstimate.php',
            type: 'POST',
            data: $(frmSendMailRequest).serialize(), // it will serialize the form data
                dataType: 'html'
            })
            .done(function(data){
                // $('#saveModalBody').fadeOut('slow', function(){
                //      $('#saveModalBody').fadeIn('slow').html(data);
                // });
                alert('メールを送信しました。')
                modal.style.display = "none";
                btnSendMailRequest.disabled = false;
                lblstatus.innerHTML = '';
            })
            .fail(function(){
                alert('Error: Could not send a request');    
            });
    }
}


function validateFormSendMailRequestData()
{
    // full name
    var fullname = document.getElementById('txtName').value;
    if(fullname == ""){ alert('氏名を入力してください。'); return false;}
    // Email
    var email = document.getElementById('txtEmail').value;
    if(email == ""){ alert('メールアドレスを入力してください。'); return false;}
    if(!validateEmail(email)){ alert('正しいメールアドレスを入力してく'); return false;}

    // optLocate
    var optLocate = document.getElementById('optLocate'); // or in jQuery use: select = this;
    if (optLocate.value == "") { alert('配送先を入力してください。'); return false;}
    // phone
    
    // address
    var address = document.getElementById('txtAddress').value;
    if(address == ""){ alert('住所を入力してください。'); return false;} 
    
    // date
    var requestDate = document.getElementById('txtRequestDate').value;
    if(requestDate == ""){ alert('希望納期を入力してください。'); return false;} 

    // note
    // 
    return true;
}

