///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//   Original-Diamonds // Функции на JavaScript                              //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

// Массив, проверяемых в форме полей

required = new Array(
    "query[name]",
    "query[email]",

    "send[name]",
    "send[email]",
    "send[email_to]",
    "send[email_from]",
    "send[name_from]",

    "user[first_name]",
    "user[last_name]",
    "user[email]",
    "user[address]",
    "user[city]",
    "user[state]",
    "user[zip]",
    "user[country]",
    "user[password]",
    "user[password_confirm]",

    "name",
    "email"
);

// Массив сообщений при проверке соответствующих полей

required_show = new Array(
    "your name",
    "your e-mail address",

    "your name",
    "your e-mail address",
    "friend's e-mail address",
    "your e-mail address",
    "your name",

    "your first name",
    "your last name",
    "your e-mail address",
    "your street address",
    "your city",
    "your state",
    "your zip code",
    "your country",
    "password",
    "confirm password",

    "your name",
    "your e-mail address"
);

// Массив, проверяемых в форме электронных адресов

required_email = new Array(
    "query[email]",
    "send[email]",
    "send[email_to]",
    "send[email_from]",
    "user[email]",
    "email"
);

// Регулярное выражение для проверки корректности электронного адреса

var regexp_email = /^[a-z0-9_-]+(\.[a-z0-9_-]+)*@([a-z0-9-]+\.)+[a-z]{2,4}$/i;

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//                  Функция проверки формы, перед отправкой                  //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

function SendForm () {

    var i, j, email;

    // Проверяем, что заполнены все обязательные поля
    for(j=0; j<required.length; j++) {
        for (i=0; i<document.forms[1].length; i++) {
            if (document.forms[1].elements[i].name == required[j] && (document.forms[1].elements[i].value == "" || document.forms[1].elements[i].value == "Your name" || document.forms[1].elements[i].value == "E-mail")) {
                alert("Please enter " + required_show[j]);
                document.forms[1].elements[i].focus();
                return false;
            }
        }
    }

    // Проверяем корректность электронных адресов
    for(j=0; j<required_email.length; j++) {
        for (i=0; i<document.forms[1].length; i++) {
            if (document.forms[1].elements[i].name == required_email[j]) {
                if (!regexp_email.test(document.forms[1].elements[i].value)) {
                    alert("Incorrect e-mail address");
                    document.forms[1].elements[i].focus();
                    return false;
                }
            }
        }
    }

    return true;
}

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//       Функция проверки формы, перед отправкой (для всплывающих окон)      //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

function SendFormPopUp () {

    var i, j, email;

    // Проверяем, что заполнены все обязательные поля
    for(j=0; j<required.length; j++) {
        for (i=0; i<document.forms[0].length; i++) {
            if (document.forms[0].elements[i].name == required[j] && (document.forms[0].elements[i].value == "" || document.forms[0].elements[i].value == "Your name" || document.forms[0].elements[i].value == "E-mail")) {
                alert("Please enter " + required_show[j]);
                document.forms[0].elements[i].focus();
                return false;
            }
        }
    }

    // Проверяем корректность электронных адресов
    for(j=0; j<required_email.length; j++) {
        for (i=0; i<document.forms[0].length; i++) {
            if (document.forms[0].elements[i].name == required_email[j]) {
                if (!regexp_email.test(document.forms[0].elements[i].value)) {
                    alert("Incorrect e-mail address");
                    document.forms[0].elements[i].focus();
                    return false;
                }
            }
        }
    }

    return true;
}

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//                  Функция открытия окна заданного размера                  //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

function OpenWindowSize(address, WindowWidth, WindowHeight) { 

    if (browser_ok == 'true') {

        WindowPosition='';
        
        if (browser_version >=4) {
            WindowLeft=Math.round((screen.width-WindowWidth)/2);
            WindowTop=Math.round((screen.height-WindowHeight)/2);
        }
        if (browser_name == "Netscape")  {  
            WindowPosition='screenX='+WindowLeft+',screenY='+WindowTop; 
        }
        if (browser_name == "Microsoft Internet Explorer") { 
            WindowPosition='left='+WindowLeft+',top='+WindowTop; 
        }
    
        newWindow=window.open(address, null, WindowPosition+',width='+WindowWidth+',height='+WindowHeight+',toolbar=0,scrollbars=1,resizable=1');
        newWindow.focus();
    }
}

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//                           Функция открытия окна                           //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

function OpenWindow(address) { 

    OpenWindowSize(address, 500, 350);
}

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//                Функция пересчета суммы заказа (Jewelry Care)              //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

function update_care_order() { 

    with (document.order) {

        subtotal_jewelry.value = quantity_jewelry.value * price_jewelry.value;
        subtotal_gold.value = quantity_gold.value * price_gold.value;
        subtotal_brush.value = quantity_brush.value * price_brush.value;
        subtotal_spectacles.value = quantity_spectacles.value * price_spectacles.value;
        subtotal_kit.value = quantity_kit.value * price_kit.value;

        quantity_postage.value = parseInt(quantity_jewelry.value) + parseInt(quantity_gold.value) + parseInt(quantity_brush.value) + parseInt(quantity_spectacles.value) + parseInt(quantity_kit.value);
        subtotal_postage.value = quantity_postage.value * price_postage.value;
    
        sum = parseInt(subtotal_jewelry.value)+parseInt(subtotal_gold.value)+parseInt(subtotal_brush.value)+parseInt(subtotal_spectacles.value)+parseInt(subtotal_kit.value)+parseInt(subtotal_postage.value);

        total.value = sum;
    }
}

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//          Функция пересчета суммы заказа (Hearts & Arrows Viewer)          //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

function update_jewelry_product_order() { 

    with (document.order) {

        subtotal_product.value = quantity_product.value * price_product.value;

        quantity_postage.value = parseInt(quantity_product.value);
        subtotal_postage.value = quantity_postage.value * price_postage.value;
    
        sum = parseInt(subtotal_product.value)+parseInt(subtotal_postage.value);

        total.value = sum;
    }
}

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//                  Функция корректировки веса брильянта                     //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

function change_weight(weight_1, weight_2) { 

    with (document.order) {
    
       weight_digit_1.value = weight_1;
       weight_digit_2.value = weight_2;
    }
}

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//                          Функция смены изображения                        //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

function change_image(name, src) { 

    document.images[name].src = src;
}

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//                       Функция показа/скрытия лупы                         //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

function switch_glass() { 

    if (switch_flag_glass) {
        glass.style.visibility = "hidden";
        magnify_picture.style.visibility = "hidden";
        switch_flag_glass = 0;
    } else {
        glass.style.visibility = "visible";
        magnify_picture.style.visibility = "visible";
        switch_flag_glass = 1;
    }
}

///////////////////////////////////////////////////////////////////////////////
//                                                                           //
//                         Функция перемещения лупы                          //
//                                                                           //
///////////////////////////////////////////////////////////////////////////////

function move_glass() { 

    // Коэффициент увеличения
    magnify_coeff = 2;

    if (switch_flag_glass) {

        // Смещение курсора мышки относительно лупы
        cursor_offset_x = 15;
        cursor_offset_y = 15;

        // Читаем координаты и размеры лупы
        glass_x = document.body.scrollLeft + event.x + cursor_offset_x;
        glass_y = document.body.scrollTop + event.y + cursor_offset_y;
        glass_width = glass.offsetWidth;
        glass_height = glass.offsetHeight;

        // Читаем координаты и размеры изображения (числа, добавляемые 
        // к координатам изображения - поправка на верстку странички)
        picture_x = picture.offsetLeft + 40;
        picture_y = picture.offsetTop + 240;
        picture_width = picture.offsetWidth;
        picture_height = picture.offsetHeight;

        // Перемещаем лупу
        glass.style.left = glass_x;
        glass.style.top  = glass_y;

        // Рассчитываем координаты верхнего левого угла большой картинки
        clip_x = (glass_x - picture_x) * magnify_coeff - cursor_offset_x*2 - Math.ceil(glass_width/2);
        clip_y = (glass_y - picture_y) * magnify_coeff - cursor_offset_y*2 - Math.ceil(glass_height/2);

        // Перемещаем большую картинку
        magnify_picture.style.left = glass_x - clip_x;
        magnify_picture.style.top  = glass_y - clip_y;
        
        // Рассчитываем параметры кадрирования
        clip_top     = clip_y;
        clip_right   = clip_x + glass_width;
        clip_bottom  = clip_y + glass_height;
        clip_left    = clip_x;

        magnify_picture.style.clip = "rect("+clip_top+", "+clip_right+", "+clip_bottom+", "+clip_left+")";

window.status = "picture_y="+picture_y+"  |  ";

    }
}

///////////////////////////////////////////////////////////////////////////////

// Определяем версию броузера

browser_name = navigator.appName; 
browser_version = parseFloat(navigator.appVersion); 

if (browser_name == "Netscape" && browser_version >= 3.0) { 
    browser_ok = 'true'; 
} else if (browser_name == "Microsoft Internet Explorer" && browser_version >= 3.0) { 
    browser_ok = 'true'; 
} else { 
    browser_ok = 'false'; 
}

// Инициализируем глобальные переменные

switch_flag_glass = 0;