/*
 * Тут будут обработчики событий, добавленные в процессе внутренней разработки
 * проекта в АвтоОпт (Ячменев Алексей)
 **/

// максимальное число телефонов Клиента
var MaxPhoneCount = 10;

var ActualPhoneCount = 1;

$(function() {
    /*
     * Обработка клика на добавление дополнительного телефона при регистрации
     */
    $("#addPhone").click(function() {
        addPhone("");
        return false;
    });
    
    /*
     * Загоняем все номера телефонов в одну строку перед отправкой
     */
    $("#regForm").submit(function() {
        
        //if (ActualPhoneCount > 1) {
            
            var phones = "";
            
            for (var i = 1; i <= ActualPhoneCount; i++) {
                phoneNum = $.trim($("input[name='phone" + i + "']").val());
                
                if (phoneNum != "") phones += (i > 1 ? ";" : "") + phoneNum;
            }

            $("input[name='phone']").val(phones);
            //if (phones != "")
            //    $("input[name='phone']").val($("input[name='phone']").val() + phones);
        //}
        
        // не раскомментировать, текст был для отладки
        //alert($("input[name='phone']").val());
        //return false;
    });
    
    /**
     * Анимируем мигание товаров-заменителей
     */
    if (document.location.hash == "#also") {
        flashAlso();
    }  
    
    /*
     * Скрываем/показываем ответ на предложение в левом столбце
     */
    $(".rating th.answered").click(function() {
        var answerDiv = $(this).parent().next().children().children("div");
        if ($(answerDiv).css("display") == "none") {
            $(answerDiv).show();
        } else
            $(answerDiv).hide();

        return false;
    });
      
    /*
     * Биндим подсказки поиска к самому поиску непосредственно
     */
    /*
    $(document).bind("ready", function() {
        $("#search").sres({
            "url": "/search/words"
        });
    });
    */
});

/**
 * Скрываем поля адреса если выбран самовывоз
 */
function showHideAddress() {
    if ($("input[name='pickup']:checked").val() == 1) {
        
        $("select[name='addressId']").parent().hide();
        $("input[name='city']").parent().hide();
        $("input[name='address']").parent().hide();
        $("input[name='index']").parent().hide();
        $("input[name='date']").parent().hide();
        $("select[name='time']").parent().hide();
    } else {
        if ($("select[name='addressId'] option").size() == 1)
            $("select[name='addressId']").parent().hide();
        else
            $("select[name='addressId']").parent().show();
        showHideAddressInList();
        
        if ($("input[name='pickup']:checked").val() == 2) {
            $("input[name='date']").parent().hide();
            $("select[name='time']").parent().hide();
        } else {
            $("input[name='date']").parent().show();
            $("select[name='time']").parent().show();            
        }
    }        
}

function showHideAddressInList() {
    if ($("select[name='addressId']").val() > 0) {
        $("input[name='city']").parent().hide();
        $("input[name='index']").parent().hide();
        $("input[name='address']").parent().hide();
    } else {
        $("input[name='city']").parent().show();
        $("input[name='index']").parent().show();
        $("input[name='address']").parent().show();

        $("input[name='city']").focus();
    }        
}

function addPhone(phone) {
    if (ActualPhoneCount < MaxPhoneCount) {
        ActualPhoneCount++;

        // прорисовываем новый блок с номером телефона
        $("#addPhoneBlock").before(
            "<div class=\"row\" id=\"phone" + ActualPhoneCount + "\">" +
                "<label>Телефон (" + ActualPhoneCount + "):</label>" +
                "<input type=\"text\" value=\"" + phone + "\" name=\"phone" + ActualPhoneCount + "\" />" +
                "<a href=\"#0\" class=\"close\" onclick=\"deletePhone($(this).parent());return false;\">x</a>" +
            "</div>"
        );
    }    
}

/**
 * Удаляет форму редактирования дополнительного телефона
 */
function deletePhone(element) {
    //вычленяем ID телефона
    var id = parseInt($(element).attr("id").substr(("phone").length));
    var pos;
    
    // удаляем блок
    $(element).empty();
    
    for (var i = id; i < ActualPhoneCount; i++) {
        pos = i + 1;
        $("#phone" + (i + 1) + " label").html("Телефон (" + i + "):");
        $("#phone" + (i + 1) + " input").attr("name", "phone" + i);
        
        $("#phone" + (i + 1)).attr("id", "phone" + i);
    }
    
    ActualPhoneCount--;
}

/**
 * Разбиваем список телефонов на отдельные поля
 */
function loadPhones(phonesString) {
    var phones = phonesString.split(";", MaxPhoneCount);
    
    
    $("input[name='phone']").attr("name", "phone1");
    $("input[name='phone0']").attr("name", "phone");
    
    $("input[name='phone1']").val(phones[0]);
     
    if (phones.length > 1) {
        for (var i = 1; i < phones.length; i++) {
            var phoneNum = $.trim(phones[i]);
            if (phoneNum != "") addPhone(phoneNum);
        }
    }
}

/**
 * Возвращает заданную дату в текстовом формате
 */
function stringDate(date) {
    var day = date.getDate();
    var month = date.getMonth() + 1;
    var year = date.getYear() + 1900;
    
    return ((day < 10) ? "0" : "") + day + "." + 
        ((month < 10) ? "0" : "") + month + "." + year;
}

function flashAlso() {
    $(".see-also .row").animate({opacity:0.1}, 300, function() {$(".see-also .row").animate({opacity:1}, 300);});
}
