
$(document).ready(function(){
  // ------- Диалог -------
  $("#popup_order_div").dialog({
    title: "Корзина",
    autoOpen: false,
    width: 500,
    height: 480,
    resizable: false,
    draggable: true,
    position: "center",
    buttons: {  
    }  
  });
  // ------- Диалог -------

});

var types = Array ("spare", "service", "machine", "testdrive");
var typesRus = Array ("Запчасть", "Сервис", "Техника", "Тест-драйв");

function clearSpareCookies() {
    $.cookie("buy_spares_list", null);
}

function clearOrderCookies() {
    $.cookie("order_list", null);
    //$.cookie("fio", null);
    //$.cookie("email", null);
    //$.cookie("tel", null);
}

function updateContacts(contName, val) {
    if(contName == "fio" || contName == "email" || contName == "tel") {
        $.cookie(contName, val);
    }
    //alert("newContacts: " + $.cookie("fio") + $.cookie("email") + $.cookie("tel"));
}

function getInfoValue(orderList) {
    var infoValue = "";
    var aList;
    var aSpare;
    var tmpType;
    if(typeof orderList == "string") {

        aList = orderList.split("`");
        if(aList.length) {
            for(var i=0; i < aList.length; i++) {
                if(infoValue.length) {
                    infoValue += "\n";
                }
                aSpare = aList[i].split("|");
                tmpType = typesRus[types.indexOf(aSpare[3])];
                if(tmpType == "") {
                    tmpType = aSpare[3];
                }
                infoValue += aSpare[0] + " - " + aSpare[1] + " - " + tmpType;
            }
        }
    }
    return infoValue;
}

function onOrderSubmit() {

    // fill info field by spares list + order list from catalogue and pricelist
    var orderList = $.cookie("order_list");
    var infoValue = getInfoValue(orderList);

    //orderList = $.cookie("buy_spares_list")
    //infoValue += getInfoValue(orderList);

    //alert("info: " + infoValue);

    $("#info").val(infoValue);
    $("#orderlist").val(orderList);

    // checks form
    if (infoValue == '') {
        alert("Не выбраны запчасти для покупки");
        return false;
    }
    if ($("#firstname").val() == '') {
        $("#firstname").focus();
        alert("Введите ваше имя");
        return false;
    }
    if ($("#email").val() == '') {
        $("#email").focus();
        alert("Введите правильный адрес электронной почты");
        return false;
    } else if(isEmail($("#email").val()) == false) {
        $("#email").focus();
        alert("Некорректный адрес электонной почты!");
        return false;
    }

    if ($("#phone").val() == '') {
        $("#phone").focus();
        alert("Введите телефон");
        return false;
    }
    if (!isPhone($("#phone").val())) {
        $("#phone").focus();
        alert("Введите, пожалуйста, настоящий телефон. Телефонный номер должен содержать только цифры, допускаются пробелы, скобки, '+', '-'");
        return false;
    }

    clearOrderCookies();
    clearSpareCookies();

    // save return url to form
    $("#return_page_url").val(window.location);

    return true;
}

function isPhone(string) {
    if(string.search(/^[0-9+() -]+$/) != -1) {
        return true;
    }else{
        return false;
    }
}

function addToOrder(id, name, cnt, type) {

    var orderList;
    var typeStr = typesRus[types.indexOf(type)];
    //alert("typeStr"+typeStr);
    //var str;
    var select = "<SELECT name='order_type' id='order_type' onChange='javascript:changeOrderType(this.value)'><OPTION value='machine'>Купить технику</OPTION><OPTION value='service'>Заказать сервис</OPTION></SELECT>";

    $("#ordered_name").text(name);
    $("#ordered_cnt").text("1");

    if (type == 'testdrive') {
        $("#ordered_type").text(typeStr);
    } else {
        $("#ordered_type").html(select);
        $("order_type").val(type)
    }

    // Отключаем возомжность заказа нескольких товаров одновременно, ибо форма не позволяет. Просто создаем заказ из одного элемента.
    /*
    orderList = $.cookie("order_list");
    if(typeof orderList != "string") {
        orderList = "";
    }
    if(orderList != "") {
        orderList += "`";
    }*/
    orderList = id + "|" + name + "|1|" + type;
    $.cookie("order_list", orderList);
    //$("#ordered_type").text(typeStr);

    //alert($.cookie("fio"));
    //str = $.cookie("fio");
    if(typeof $.cookie("fio") == "string") {
        //alert(str);
        $("#firstname").val($.cookie("fio"));
    }
    if(typeof $.cookie("email") == "string") {
        $("#email").val($.cookie("email")+"");
    }
    if(typeof $.cookie("tel") == "string") {
        $("#phone").val($.cookie("tel")+"");
    }

    $("#popup_order_div").show();
    $("select").hide();
    if (type != 'testdrive') {
        $("#order_type").show();
    }
    $("#popup_order_div").dialog("open");
}

function changeOrderType(newType) {
    var orderList = $.cookie("order_list");
    var aOrder;
    if(typeof orderList != "string") {
        return;
    }
    aOrder = orderList.split("|");
    aOrder[3] = newType;//$("order_type").val();
    orderList = aOrder.join("|");
    $.cookie("order_list", orderList);
    //alert(newType + ", " + orderList);
}

function onOrderClick(itemId, itemName) {
    return addToOrder(itemId, itemName, 1, "machine");
}

function onClearOrderClick() {
    clearOrderCookies();
}

function onTestDriveClick(itemId, itemName) {
    return addToOrder(itemId, itemName, 1, "testdrive");
}

function onOrderCloseClick() {
  $("select").show();
  $("#popup_order_div").dialog("close");
  onClearOrderClick();
}

function onMakeOrderClick() {
    return onOrderSubmit();
}

