is_design_page = true;
var urlbase;
var fabric_part = 'all';
var last_button = '';
var PNGfix = /MSIE (5\.5|6\.)/.test(navigator.appVersion);

var product = {};
var last_imgs = {};
var last_photos = {};
var stripedFabricOption = null;
//Волшебство какое-то
function asciionly (e) {
    var keynum;
    var keychar;
    var numcheck;

    if (window.event) { // IE
        keynum = e.keyCode;
    } else if (e.which) { // Netscape/Firefox/Opera
        keynum = e.which;
    }
    if (keynum == 8) { //Backspace;
        return true;
    }
    keychar = String.fromCharCode(keynum);
    //numcheck = /[\x00-\x7e]/;
    numcheck = /[-!"#$%&'()*+,./:;<=>?@[\\\]^_`{|}~\w\sА-Яа-яЁё]/;
    return numcheck.test(keychar);
}

//Тип параметра
function attr_type (attr) {
    try {
    return currentProductAttr[attr].attr.attrType;
    } catch (Ex) {
        dbg(Ex);
    }
}

//Возвращает значение параметра по-умолчанию
function attr_default (attr) {
    try{
    var def_val = currentProductAttr[attr].attr.defaultValue;

    if (def_val == '' || (currentProductAttr[attr].values && currentProductAttr[attr].values[def_val]))
        return (def_val);
    for (def_val in currentProductAttr[attr].values)
        return (def_val);
    if(!currentProductAttr[attr].values)
        return(def_val);
    alert ('Oops, nothing found in ' + attr);
    } catch (ex) {
        dbg(ex);
    }
}

//Генерация заголовка страницы
function calc_title () {
    var a = productName + '. ';
    a += product.useTieFabric ? currentProductAttr.tieFabric.attr.displayName + ' ' + currentProductAttr.tieFabric.values[product.tieFabric].shortName + '. ' :
        currentProductAttr.fabric.attr.displayName + ' ' + currentProductAttr.fabric.values[product.fabric].shortName + '. ';
    a += currentProductAttr.tieEnding.attr.displayName +': ' + currentProductAttr.tieEnding.values[product.tieEnding].displayName + '. ';
    a += currentProductAttr.tieWidth.attr.displayName + ': ' + product.tieWidth + 'см . ';
    a += product.tieLength ? currentProductAttr.tieLength.attr.displayName + ': ' + product.tieLength + 'см . ' : '';
    a += currentProductAttr.tieThickness.attr.displayName + ': ' + currentProductAttr.tieThickness.values[product.tieThickness].displayName + '. ';
    a += currentProductAttr.embroidery.attr.displayName + ': ' + currentProductAttr.embroidery.values[product.embroidery].displayName + '. ';
    
    document.title = a;
}

//Заполнение объекта product значениями по-умолчанию
function set_attr_defaults () {
    var a = currentProductAttr;
    var g = typeof (gallery_shirt) != 'undefined';
    for (var i in a) {
        deselect_icon (i);
        if (g && gallery_shirt[i] && a[i].values)
            if (a[i].values[gallery_shirt[i]])
                product[i] = gallery_shirt[i];
            else {
                myalert ('Извините. Позиция "' + a[i].attr.displayName + ' ' + gallery_shirt[i] + '" уже недоступна для заказа.');
                product[i] = attr_default (i);
            }
        else
            product[i] = attr_default (i);
    }
    if(g && gallery_shirt.tieWidth)
        product['tieWidth'] = gallery_shirt.tieWidth;
    if(g && gallery_shirt.tieLength)
        product['tieLength'] = gallery_shirt.tieLength;
    /*if(g && gallery_shirt.tieThickness)
        select_thickness(gallery_shirt.tieThickness);
    */
    delete product.stdSize;
    delete product.waistLengthFront;
    delete product.shoulderHeightFront;
    delete product.waistLengthBack;
    delete product.shoulderHeightBack;
}

function show_part (part) {
    var e = elt('img_' + part);
    show_item ('img_' + part);
    if (PNGfix && e.filters.length)
        e.filters.item(0).enabled = true;
}

function hide_part (part) {
    var e = elt('img_' + part);
    if (PNGfix && e.filters.length)
        e.filters.item(0).enabled = false;
    hide_item ('img_' + part);
}

function change_part (part, name) {
    var url = urlbase + name + '.png';
    var e = elt('img_' + part);

    if (last_imgs[part] == url)
        return;

    if (PNGfix) {
        if (e.filters.length)
            e.filters.item(0).src = url;
        else
            e.style.filter =
            "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"
            + url + "')";
    } else {
        e.src = url;
    }
    
    last_imgs[part] = url;
}

function change_part_buttons (part, name) {
    change_part ('buttons_' + part, '../../buttons/' + product.buttons + '/buttons_' + name);
}

function change_part_buttonsThread (part, name) {
    change_part ('buttonsThread_' + part, '../../threads/' + product.buttonsThread + '/buttonsThread_' + name);
}

function change_button_text (attr, val) {
    if (elt('button_' + attr).className != 'disabled')
        if(product.useTieFabric && attr == 'fabric')
            write_inner ('button_fabric', currentProductAttr['tieFabric'].values[val].shortName);            
        else
            write_inner ('button_' + attr, currentProductAttr[attr].values[val].shortName);
    else
        write_inner ('button_' + attr, '---');
}

function enable_button (item, val) {
    if (elt('button_' + item).className == 'disabled')
        elt('button_' + item).className = '';
    change_button_text (item, val);
}

function disable_button (item) {
    el = elt('button_' + item);
    if(el){
        el.className = 'disabled';
        write_inner ('button_' + item, '---');
    }
}

function attr_cost (attr) {
    return (currentProductAttr[attr] && currentProductAttr[attr].attr ? currentProductAttr[attr].attr.price : 0 );
}

function write_attr_cost (attr, id) {
    write_inner (attr + '_' + id, '(+' + attr_cost (attr) + 'p)');
}

function attr_value_cost (attr, val) {
    return (currentProductAttr[attr] && currentProductAttr[attr].values ? currentProductAttr[attr].values[val].price : 0);
}

function write_cost (attr, val) {
    write_inner (val + '_cost', '(+' + attr_value_cost (attr, val) + 'p)');
}

function get_cost (attr) {
    var a = attr_cost (attr);
    if (a == 0)
        return (parseInt (attr_value_cost (attr, product[attr])));
    else if (product[attr] == attr_default (attr))
        return (0);
    else
        return (parseInt (a));
}

function calc_price () {
    var price = 0;
    price += product.useTieFabric ?
        get_cost('tieFabric') : get_cost ('fabric');
    if(!product.embroidery.match(/none$/i)) {
        price += get_cost('embroideryVariant');
        price += get_cost(product.embroideryVariant);
    }
    price += get_cost ('invertStripes');
    price -= calcProductDiscount('tie', price);
    write_inner ('design_price', String (parseInt (price)));
}

/*
 *  Все функции change вызываются из select_icon при помощи eval
 *
 */

//Мое творчество, меняет форму конца галстука
function change_tieEnding() {
    if(product.useTieFabric) {
        urlbase = tie_design_base + product.tieFabric + '/';        
    } else {
        urlbase = design_base + product.fabric + '/';
    }
    change_button_text ('tieEnding', product.tieEnding);

    change_part ('background_fabric', '../../customTie/' + ( product.useTieFabric == true ? product.tieFabric : product.fabric ) + '/tie_' + product.invertStripes + '_' + product.tieEnding +'_' + product.tieWidth);
   
    calc_title ();
    calc_price ();
}

//Меняет ширину галстука
function change_tieWidth() {
    if(product.tieWidth) {
        write_inner ('button_tieWidth', product.tieWidth + '&nbsp;см');

        //change_part ('mask', '../../images/mask/' + product.tieWidth + '-trans');

        change_part ('background_fabric', '../../customTie/' + ( product.useTieFabric == true ? product.tieFabric : product.fabric ) + '/tie_' + product.invertStripes + '_' + product.tieEnding +'_' + product.tieWidth);
    } else {
        write_inner ('button_tieWidth', '---');
    }

    //change_popup('select_tieWidth');
    calc_title ();
    calc_price ();
}

//Меняет толщину галстука
function change_tieThickness() {
    urlbase = design_base + product.fabric + '/';
    change_button_text ('tieThickness', product.tieThickness);

    calc_title ();
    calc_price ();
}

function change_tieLength() {
    if(product.tieLength) {
        write_inner ('button_tieLength', product.tieLength);
    } else {
        write_inner ('button_tieLength', '---');
    }

    calc_title ();
    calc_price ();
}
/*
function change_embroideryEastern() {
    change_part ('embroidery_sandwich_thread', '../../threads/' + product.embroideryColor + '/' + product.embroideryEastern);
}

function change_embroideryZodiac1() {
    change_part ('embroidery_sandwich_thread', '../../threads/' + product.embroideryColor + '/' + product.embroideryZodiac1);
}

function change_embroideryZodiac2() {
    change_part ('embroidery_sandwich_thread', '../../threads/' + product.embroideryColor + '/' + product.embroideryZodiac2);
}

function change_embroideryLogo() {
    change_part ('embroidery_sandwich_thread', '../../threads/' + product.embroideryColor + '/' + product.embroideryLogo);
}
*/
function change_invertStripes() {
    change_button_text ('invertStripes', product.invertStripes);
    change_part ('background_fabric', '../../customTie/' + ( product.useTieFabric == true ? product.tieFabric : product.fabric ) + '/tie_' + product.invertStripes + '_' + product.tieEnding +'_' + product.tieWidth);
    if (currentProductAttr[product.useTieFabric ? 'tieFabric' : 'fabric'].values[product.useTieFabric ? product.tieFabric : product.fabric].hasStripes == 'true') {
        stripedFabricOption = product.invertStripes;
    }
    calc_title ();
    calc_price ();
}

function change_body () {
    var name = product.model ? product.model + '_' : '';
    change_button_text ('volume', product.volume);
    change_button_text ('bottomCut', product.bottomCut);
    change_part ('body', name +  product.volume + '_' + product.bottomCut);
}

function change_bottomCut () {
    change_body ();
}

function change_fabric () {
    product.useTieFabric = false;
    deselect_icon('tieFabric');

    urlbase = design_base + product.fabric + '/';
    if(currentProductAttr.fabric.values[product.fabric].hasStripes == 'true') {
        load_striped_option();
        enable_button ('invertStripes', product.invertStripes);
        stripedFabricOption = product.invertStripes;
    } else {
        disable_button ('invertStripes');
        deselect_icon ('invertStripes', product.invertStripes);
        product.invertStripes = currentProductAttr.invertStripes.attr.defaultValue;
        select_icon ('invertStripes', product.invertStripes);
    }

    change_button_text ('fabric', product.fabric);

    change_part ('fabric', 'fabric_icon');

    change_part ('sandwich_fabric', 'sandwich');
    change_part ('embroidery_sandwich_fabric', 'sandwich');

    change_part ('fabric', 'fabric_icon');

    change_part ('background_fabric', '../../customTie/' + product.fabric + '/tie_' + product.invertStripes + '_' + product.tieEnding +'_' + product.tieWidth);

    setFabricZoomed (product.fabric, 'fabric');
    
    calc_title ();    
    calc_price ();
}

function change_tieFabric () {
    product.useTieFabric = true;
    deselect_icon('fabric');

    fabricbase = design_base + '../customTie/' + product.tieFabric + '/';

    urlbase = tie_design_base + product.tieFabric + '/';
    if(currentProductAttr.tieFabric.values[product.tieFabric].hasStripes == 'true') {
        load_striped_option();
        enable_button ('invertStripes', product.invertStripes);
        stripedFabricOption = product.invertStripes;
    } else {
        disable_button ('invertStripes');
        deselect_icon ('invertStripes', product.invertStripes);
        product.invertStripes = currentProductAttr.invertStripes.attr.defaultValue;
        select_icon ('invertStripes', product.invertStripes);
    }

    change_button_text ('fabric', product.tieFabric);

    change_part ('embroidery_sandwich_fabric', '../' + product.tieFabric + '/sandwich');
    change_part ('sandwich_fabric', '../' + product.tieFabric + '/sandwich');

    change_part ('fabric', '../../customTie/' + product.tieFabric +'/fabric_icon');
    //change_part ('background_fabric', '../../customTie/' + product.tieFabric + '/' + product.tieFabric);
    //change_part ('mask', '../../../tie/images/mask/' + product.tieWidth + '-trans');
    change_part ('background_fabric', '../../customTie/' + product.tieFabric + '/tie_' + product.invertStripes + '_' + product.tieEnding +'_' + product.tieWidth);
    
    setFabricZoomed (product.tieFabric, 'tieFabric');

    calc_title ();    
    calc_price ();

}


function load_striped_option() {
    if(stripedFabricOption != null) {
        deselect_icon ('invertStripes', product.invertStripes);
        product.invertStripes = stripedFabricOption
        select_icon ('invertStripes', product.invertStripes);
    }
}
/*
function change_embroideryVariant() {
    change_button_text ('embroideryVariant', product.embroideryVariant);
    filename = product.embroideryFont;

    switch (product.embroideryVariant) {
        case 'embroideryMonogram':
            break;
        case 'embroideryZodiac1':
            filename = product.embroideryZodiac1;
            break;
        case 'embroideryZodiac2':
            filename = product.embroideryZodiac2;
            break;
        case 'embroideryEastern':
            filename = product.embroideryEastern;
            break;
        case 'embroideryLogo':
            filename = product.embroideryLogo;
            break;
        default:
            break;
    }

    calc_price();
    setEmbroideryPriceDiv();
    change_part ('embroidery_sandwich_thread', '../../threads/' + product.embroideryColor + '/' + filename);
}
*/
function setEmbroideryPriceDiv() {
    price = (product.embroideryVariant == 'embroideryMonogram' ?
              parseInt(currentProductAttr['embroideryVariant'].values['embroideryMonogram'].price) : parseInt(currentProductAttr[product.embroideryVariant].values[product[product.embroideryVariant]].price));
    elt('embroidery_cost').innerHTML = price == 0 ? '' : ('(+' + price + 'р)');
}


function change_photo (part, name) {
    if (last_photos[part] == name)
        return;
    elt('photo_' + part).src = '../photo/' + name + '.jpg';
    last_photos[part] = name;
}

function change_backPleats () {
    change_button_text ('backPleats', product.backPleats);
    change_photo ('backPleats', product.backPleats);
}


function change_embroidery () {
    if (product.embroidery.match(/none$/i)) {
        disable_button ('embroideryFont');
        disable_button ('embroideryColor');
        disable_button ('embroideryVariant');
        elt('embroideryText').value = '';
        elt('embroideryText').disabled = true;

        last_imgs['embroideryPhoto'] = null;
        elt('img_embroideryPhoto').src = design_base + '../../images/white.jpg';
        hide_part ('buttons_sandwich');
        hide_part ('embroidery_sandwich_thread');

        elt('embroidery_cost').innerHTML = '';
    } else {
        enable_button ('embroideryFont', product.embroideryFont);
        enable_button ('embroideryColor', product.embroideryColor);
        enable_button ('embroideryVariant', product.embroideryVariant);
        elt('embroideryText').disabled = false;

        //elt('photo_embroidery').src = '../images/embroideryImg/' + product.embroidery + '.png';
        //change_photo ('embroideryFont', 'embroideryImg/' + product.embroidery);

        show_part ('buttons_sandwich');
        show_part ('embroidery_sandwich_thread');
        try {
            eval('change_'+ product.embroideryVariant +'()');
        } catch (ex) {
            
        }
        if('embroideryMonogram' == product.embroideryVariant) {
            change_part ('embroidery_sandwich_thread', '../../threads/' + product.embroideryColor + '/' + product.embroideryFont);
        }
        change_part ('buttons_sandwich', '../../threads/' + product.embroideryColor + '/' + product.embroideryColor);
        last_imgs['embroideryPhoto'] = '/' + contentGender + '/images/embroidery/embroideryTieAtCenter.png';
        elt('img_embroideryPhoto').src = last_imgs['embroideryPhoto'];

        setEmbroideryPriceDiv();
    }

    change_button_text ('embroidery', product.embroidery);
    //change_photo ('embroidery', product.embroidery);
    calc_price ();
    calc_title ();
}

function change_embroideryFont () {
    change_embroidery ();
}

function change_embroideryColor () {
    change_embroidery ();
}

var design_step_active = 0;

function design_step (step) {
    //change_popup2 ('');
    if (design_step_active) {
        elt('design_step_' + design_step_active).className = ''; // 'design_step';
        //elt('design_step_' + design_step_active + '_active').id = 'design_step_' + design_step_active; // 'design_step';
        hide_item ('design_page_' + design_step_active);
    }
    if (step) {
        if (measurements_step (0))
            return;
        show_item ('design_tabs');
        elt('design_step_' + step).className = 'design_step_active';
        //elt('design_step_' + step).id = 'design_step_' + step + '_active';
        // АКТИВАЦИЯ ПУНКТА МЕНЮ ПРИ ПЕРЕХОДЕ К ВКЛАДКЕ step
        switch (step) {
            case 1:
                $('.design_menu a#fabric').trigger('click');
                break;
            case 2:
                $('.design_menu a#tieThickness').trigger('click');
                break;
            case 3:
                $('.design_menu a#embroidery').trigger('click');
                break;
            case 4:
                $('.design_right#shirtPreview').hide();
                break;
        }
        show_item ('design_page_' + step);
    } else
        hide_item ('design_tabs');
    design_step_active = step;
    
    show_item ('design_price_div');
    if(product.tieFabric && step > 1) {
        fabric_zoom_close();
    }
    /*
    if(product.tieFabric && step == 3) {
        hide_item ('shirt_design');
        hide_item ('img_fabric');
        hide_item ('design_fabric_zoom_img');
    } else {
        show_item ('shirt_design');
        show_item ('img_fabric');
        show_item ('design_fabric_zoom_img');
    }
    */
}

var measurements_step_active = 0;

function measurements_step (step, require) {
    if (step == last_meas_step) {
        var s = '';
        var i, j;
        s += '<p>Просмотр Ваших размеров:</p>';
        for (i = 1; i < last_meas_step; i++) {
            var n = 0;
            var l = 0;
            for (j in meas[i])
                l++;
            for (j in meas[i]) {
                s += '<div class="row" onclick="measurements_step(' + i + ')">';
                s += '<div class="left">';
                s += i + (l > 1 ? '.' + ++n : '') + '. ' + currentProductAttr[j].attr.displayName;
                s += '</div>';
                s += '<div class="right">';
                s += elt(j).value + ' см';
                s += '</div>';
                s += '&nbsp;';
                s += '</div>';
            }
        }
        write_inner ('measurements_summary', s);
    }
    if (measurements_step_active) {
        for (i in meas[measurements_step_active]) {
            var e = elt(i);
            var v = parseInt (0 + e.value, 10);
            var a = currentProductAttr[i].attr;
            var min = parseInt (0 + a.min, 10);
            var max = parseInt (0 + a.max, 10);
            if (v < min && (i != 'sleeveLength' || product.sleeve == 'sleeveLong' || product.sleeve == 'sleeveLongNarrow')
                && (i != 'shortSleeveLength' || product.sleeve == 'sleeveShort' || product.sleeve == 'sleeveShortCuff')) {
                e.focus();
                e.select();
                if (require) {
                    myalert ('Значение "' + a.displayName + '" не должно быть меньше ' + min + ' см.');
                    return (true);
                }
                if (!myconfirm ('Значение "' + a.displayName + '" не должно быть меньше ' + min + ' см. Вы уверены, что хотите продолжить?'))
                    return (false);
            } else if (v > max && (i != 'sleeveLength' || product.sleeve != 'sleeveLong' && product.sleeve != 'sleeveLongNarrow')
                && (i != 'shortSleeveLength' || product.sleeve != 'sleeveShort' && product.sleeve != 'sleeveShortCuff')) {
                e.focus();
                e.select();
                if (require) {
                    myalert ('Значение "' + a.displayName + '" не должно быть больше ' + max + ' см.');
                    return (true);
                }
                if (!myconfirm ('Значение "' + a.displayName + '" не должно быть больше ' + max + ' см. Вы уверены, что хотите продолжить?'))
                    return (false);
            } else if (v < min || v > max)
                e.value = '';
        }
        elt('measurements_step_' + measurements_step_active).className = 'design_step';
        hide_item ('measurements_page_' + measurements_step_active);
    }
    if (step) {
        design_step (0);
        show_item ('measurements_tabs');
        elt('measurements_step_' + step).className = 'design_step_active';
        show_item ('measurements_page_' + step);
        for (i in meas[step]) {
            elt(i).focus();
            elt(i).select();
            break;
        }
    } else
        hide_item ('measurements_tabs');
    measurements_step_active = step;
    return (false);
}

function newProfile_callback (res) {
    myalert ('Готово');
    profileList_page ();
}

function newProfile (f) {
    for (var i in profile) {
        var e = elt('np_'+i);
        var v = e.value;
        if (i == 'displayName') {
            if (!v) {
                myalert ('Не заполнено имя профиля');
                e.focus();
                return;
            } else
                profile[i] = v;
        } else if (v || i != 'sleeveLength' && i != 'shortSleeveLength') {
            var a = currentProductAttr[i].attr;
            v = parseInt (0 + v, 10);
            var min = parseInt (0 + a.min, 10);
            var max = parseInt (0 + a.max, 10);
            if (v < min) {
                myalert ('Значение "' + a.displayName + '" не должно быть меньше ' + min + ' см.');
                e.focus();
                e.select();
                return;
            }
            if (v > max) {
                myalert ('Значение "' + a.displayName + '" не должно быть больше ' + max + ' см.');
                e.focus();
                e.select();
                return;
            }
            profile[i] = v;
        } else
            delete profile[i];
    }
    customerService (f, 'createShirtProfile', newProfile_callback, profile);
}

function newProfile_page () {
    var dn = 'Профиль ' + (last_profile_number + 1);
    var s = '';
    s += '<table summary="">';
    s += '<tr>';
    s += '<td class="left">';
    s += 'Имя профиля';
    s += '</td>';
    s += '<td>';
    s += '<input type="text" size="16" maxlength="32" id="np_displayName" value="' + dn + '" />';
    s += '</td>';
    s += '</tr>';
    profile = {};
    profile.displayName = dn;
    profile.height = 0;
    for (var i = 1; i < last_meas_step; i++)
        for (var j in meas[i]) {
            var size = currentProductAttr[j].attr.max > 99 ? 3 : 2;
            s += '<tr>';
            s += '<td class="left">';
            s += currentProductAttr[j].attr.displayName;
            s += '</td>';
            s += '<td>';
            s += '<input type="text" size="3" maxlength="' + size + '" id="np_' + j + '" value="" /> см.';
            s += '</td>';
            s += '</tr>';
            profile[j] = '';
        }
    s += '</table>';
    write_inner ('newProfile', s);
    change_popup3 ('newProfile_page');
}

function addShirt_callback (res) {
    eval (res);
    change_cart (count, sum);
    myalert ('Готово');
    design_step (1);
}

function addShirt (f) {
    var i, j;
    var p = {};
    /*for (i = 1; i <= last_meas_step; i++)
        if (measurements_step (i, true))
            return;
    */
    p.price = elt('design_price').innerHTML;
    for (i in product)
        p[i] = product[i];
    p.embroideryText = elt('embroideryText').value;
    if (!p.embroidery.match(/none$/i) && p.embroideryVariant == 'embroideryMonogram' && !p.embroideryText) {
        myalert ('Выбрано использование монограммы, но не введен текст');
        return;
    }
    //if (!p.embroideryText.match(/^[\x20-\x7e]*$/)) {
    if (p.embroideryText.length > 0 && p.embroideryText.match(/[^-!"#$%&'()*+,./:;<=>?@[\\\]^_`{|}~\w\sА-Яа-яЁё]+/)) {
        myalert ('Текст монограммы содержит недопустимые символы');
        return;
    }
    if (!p.tieLength) {
        myalert ('Не выбрана длина');
        return;
    }

    /*
    if(p.useTieFabric)
        p.fabric = null;
    else
        p.tieFabric = null;
    delete p.useTieFabric;
    */
    delete p.tieLengthTo;
    delete p.tieLengthFrom;
    delete p.tieHeight;
    delete p.tieLengthNeck;
    delete p.tieLengthHeight;

    p.measurementsName = '';
    customerService (f, addShirtSvc, addShirt_callback, p);
}

function addShirt_with_profile_callback (res) {
    readShirtProfile_callback (res);
    var p = {};
    p.price = elt('design_price').innerHTML;
    for (var i in product)
        p[i] = product[i];
    p.embroideryText = elt('embroideryText').value;
    if (p.embroidery != 'embroideryNone' && !p.embroideryText) {
        myalert ('Выбрано использование монограммы, но не введен текст');
        return;
    }
    //if (!p.embroideryText.match(/^[\x20-\x7e]*$/)) {
    if (p.embroideryText.length > 0 && p.embroideryText.match(/[^-!"#$%&'()*+,./:;<=>?@[\\\]^_`{|}~\w\sА-Яа-яЁё]+/)) {
        myalert ('Текст монограммы содержит недопустимые символы');
        return;
    }
    for (var i in profile) {
        if (i == 'objectId' || i == 'customerId' || i == 'displayName') {
        // nop
        } else {
            var e = elt('up_'+i);
            var v = e.value;
            var a = currentProductAttr[i].attr;
            v = parseInt (0 + v, 10);
            var min = parseInt (0 + a.min, 10);
            var max = parseInt (0 + a.max, 10);
            if (v < min && (i != 'sleeveLength' || product.sleeve == 'sleeveLong' || product.sleeve == 'sleeveLongNarrow')
                && (i != 'shortSleeveLength' || product.sleeve == 'sleeveShort' || product.sleeve == 'sleeveShortCuff')) {
                change_popup3 ('updateProfile_page');
                e.focus();
                e.select();
                myalert ('Значение "' + a.displayName + '" не должно быть меньше ' + min + ' см.');
                return;
            } else if (v > max && (i != 'sleeveLength' || product.sleeve != 'sleeveLong' && product.sleeve != 'sleeveLongNarrow')
                && (i != 'shortSleeveLength' || product.sleeve != 'sleeveShort' && product.sleeve != 'sleeveShortCuff')) {
                change_popup3 ('updateProfile_page');
                e.focus();
                e.select();
                myalert ('Значение "' + a.displayName + '" не должно быть больше ' + max + ' см.');
                return;
            }
            if (v >= min && v <= max)
                p[i] = v;
            else
                delete p[i];
        }
    }
    if (!profile.lengthToShoulder)
        delete p.lengthToShoulder;

    delete p.tieLengthTo;
    delete p.tieLengthFrom;
    delete p.tieHeight;
    delete p.tieLengthNeck;
    delete p.tieLengthHeight;

    html = '';
    for(var i in p) {
        html += i+": "+product[i] + '<br/>';
    }
    elt('bannerr').innerHTML = html;
    
    p.measurementsName = profile.displayName;
    customerService (0, addShirtSvc, addShirt_callback, p);
}

function addShirt_with_profile (f, oid) {
    var p = {
        'objectId' : oid
    };
    customerService (0, 'readShirtProfile', addShirt_with_profile_callback, p);
}

function enable_option (id) {
    var e = elt (id);
    e.disabled = false;
    e.style.color = '#000';
}

function disable_option (id) {
    var e = elt (id);
    e.disabled = true;
    e.style.color = '#CCC';
}

function show_stdSize () {
    hide_item ('show_stdSize_link');
    show_item ('select_std2');
    show_inline_item ('addShirt_stdSize');
}

function addShirt_stdSize (f) {
    var i, j;
    var p = {};
    p.price = elt('design_price').innerHTML;
    for (i in product)
        if (attr_type (i) != 'measure')
            p[i] = product[i];
    p.embroideryText = elt('embroideryText').value;
    if (p.embroidery != 'embroideryNone' && !p.embroideryText) {
        myalert ('Выбрано использование монограммы, но не введен текст');
        return;
    }
    //if (!p.embroideryText.match(/^[\x20-\x7e]*$/)) {
    if (p.embroideryText.length > 0 && p.embroideryText.match(/[^-!"#$%&'()*+,./:;<=>?@[\\\]^_`{|}~\w\sА-Яа-яЁё]+/)) {
        myalert ('Текст монограммы содержит недопустимые символы');
        return;
    }

    p.height = elt('stdHeight').value;
    var stdSize = elt('stdSize').value;
    if (design_sex == 'f') {
        var stdSeat = elt('stdSeat').value;
        if (!stdSize) {
            myalert ('Не выбран обхват груди');
            return;
        } else if (!stdSeat) {
            myalert ('Не выбран обхват бедер');
            return;
        } /* else if (elt('stdSize_'+stdSize).disabled || elt('stdSeat_'+stdSeat).disabled) {
            myalert ('Недопустимая комбинация размеров');
            return;
        } */
        p.stdSize = Math.round(stdSize/2);
        p.chestAround = stdSize;
        p.seatAround = stdSeat;
    } else
        p.stdSize = stdSize;
    
    delete p.height;
    delete p.stdSize;

    customerService (f, addShirtSvc, addShirt_callback, p);
}

function createShirtProfile_callback (res) {
    customerService (0, 'shirtProfileList', profileList_callback);
    myalert ('Готово');
}

function createShirtProfile (f) {
    var i, j;
    for (i = 1; i <= last_meas_step; i++)
        if (measurements_step (i, true))
            return;
    var p = {};
    p.displayName = elt('measurementsName').value;
    p.height = 0;
    for (i = 1; i < last_meas_step; i++)
        for (j in meas[i]) {
            var v = parseInt (0 + elt(j).value, 10);
            if (v)
                p[j] = v;
        }
    customerService (f, 'createShirtProfile', createShirtProfile_callback, p);
}

function fabric_zoom (fabric, productAttribute) {
    if(fabric && product) {
        setFabricZoomed(fabric, productAttribute);
    }
    show_item ('fabric_zoom');
    hide_item ('design_price_div');
}

function fabric_zoom_close () {
    show_item ('design_price_div');
    hide_item ('fabric_zoom');
}

/**
 * Устанавливает детальную информацию о ткани
 */
function setFabricZoomed (fabric, productAttribute) {
        var fabric_attrs = currentProductAttr[productAttribute].values[fabric];
        if (fabric_attrs.symbols) {
            fabric_attrs.symbols = fabric_attrs.symbols.replace(/\.\.\/\.\.\/fabric_help/gi, '/fabric_help');
            write_inner ('fabric_symbols', fabric_attrs.symbols);
        } else {
            write_inner ('fabric_symbols', '');
        }
        write_inner ('fabric_name', fabric_attrs.displayName);
        write_inner ('fabric_id', fabric_attrs.article + ' (' + fabric_attrs.country + ')');
        write_inner ('fabric_composition', fabric_attrs.composition);
        write_inner ('fabric_density', fabric_attrs.density == '0' ? 'Н/д' : fabric_attrs.density);
        write_inner ('fabric_price', fabric_attrs.price);
        write_inner ('fabric_color', fabric_attrs.color || '');
        photo = design_base;
        if (currentProductAttr[productAttribute].values[fabric].priceTie == -1) {
            photo = '/female/skirtPresets/fabric/'+ fabric +'_photo.jpg';
        } else if(currentProductAttr[productAttribute].values[fabric].price == 0 || (productType == 'tie' && productAttribute == 'tieFabric')) {
            photo += '../customTie/' + fabric + '/photo_.jpg';
        } else {
            photo += fabric + '/photo.jpg';
        }
        elt('fabric_photo').src = resolveAbsoluteUrl(photo);
}

function help (what) {
    alert ('help ' + what);
}

function deselect_icon (attr) {
    var icon;
    switch (attr) {
        /*case 'contrastFabric':
            icon = 'icon_contrast_';
            break;*/
        case 'embroideryColor':
            icon = 'icon_embroideryColor_';
            break;
        default:
            icon = 'icon_';
            break;
    }
    if (!product[attr] || !elt(icon + product[attr]))
        return '';
    elt(icon + product[attr]).className = '';
    return icon;
}

//Нужно вызывать для того, чтоб происходило изменение выбраного пункта

//function select_icon (attr, val) {
//    var icon = deselect_icon (attr);
    /*
    if('logoMTM' == val && product.embroideryColor && product.embroideryColor != '00088') {
        alert ('Вышивка логотипа возможна только фирменным цветом 00088');
        return;
    }
    
    if ('embroideryColor' == attr && '00088' != val && 'embroideryLogo' == product.embroideryVariant) {
        alert ('Вышивка логотипа возможна только фирменным цветом 00088');
        return;
    }
    */
   /*
    product[attr] = val;
    if(val != '') {
        try {
            elt(icon + val).className = 'selected_icon';            
        } catch (err) {
            //dbg(err);
        }
    }
    
    try{
        eval ('change_' + attr + '()');
    } catch (err) {
        //dbg(err);
    }
}
        */

function reset_contrastFabric () {
    select_icon ('contrastFabric', product.fabric);
}

function select_button (what, context) {
    $('div.design_menu a').removeClass('designMenuActive');
    $(context).addClass('designMenuActive');
    $('div.design_middle > div.design_menu_popup_bg').hide();

    if (elt('button_' + what).className == 'disabled')
        return;
    if (last_button)
        elt('button_' + last_button).className = '';
    elt('button_' + what).className = 'last';
    last_button = what;
    show_item ('select_' + what + '_container');
}

/**
 * Нажатие кнопки в опциях вышивки галстука
 */
/*
function select_embroidery_button (type, what) {
    select_icon (type, what);
    if ('embroideryMonogram' == what) {
        //hide_item ('')
        hide_item ('design_menu_usual');
        hide_item ('select_embroideryVariant_container');
        show_item ('design_menu_monogram');
    } else {
        show_item ('select_' + what + '_container');
    }
}


function hide_embroidery_options() {
    show_item ('design_menu_usual');
    show_item ('select_embroideryVariant_container');
    hide_item ('design_menu_monogram');
}
*/

function select_ckbox_collarWhite () {
    product.collarWhite = product.collarWhite == 'true' ? 'false' : 'true';
    change_collar ();
}

function select_ckbox_cuffWhite () {
    product.cuffWhite = product.cuffWhite == 'true' ? 'false' : 'true';
    change_cuff ();
}

function select_ckbox_pocketFlap () {
    product.pocketFlap = product.pocketFlap == 'true' ? 'false' : 'true';
    change_flap ();
}

function select_ckbox_epaulettes () {
    product.epaulettes = product.epaulettes == 'true' ? 'false' : 'true';
    change_epaulettes ();
}

function select_ckbox_collarDensity () {
    product.collarDensity = product.collarDensity == 'true' ? 'false' : 'true';
    change_collarDensity ();
}

function select_ckbox_collarBone () {
    product.collarBone = product.collarBone == 'true' ? 'false' : 'true';
    change_collarBone ();
    if (product.collarBone == 'true')
        disable_ckbox ('collarButtons');
    else
        enable_ckbox ('collarButtons', product.collarButtons);
}

function select_ckbox_collarButtons () {
    product.collarButtons = product.collarButtons == 'true' ? 'false' : 'true';
    change_collarButtons ();
    if (product.collarButtons == 'true')
        disable_ckbox ('collarBone');
    else
        enable_ckbox ('collarBone', product.collarBone);
}

function write_popup (attr, cols, help, toInvoke) {
    var s = '';
    var i = 0;
    var j;
    s += '<table cellpadding="5">';
    invoke = 'select_icon';
    if(toInvoke) {
        invoke = toInvoke;
    }

    if (!currentProductAttr[attr].values && currentProductAttr[attr].attr && currentProductAttr[attr].attr.attrType == 'measure') {
        from = parseInt (currentProductAttr[attr].attr.min);
        to = parseInt (currentProductAttr[attr].attr.max);
        for (m = from; m<=to; m++) {
            s += i ? '' : '<tr>';
            s += '<td>';
            s += '<div class="design_menu_small_popup_icon">';
            s += '<img src="/' + contentGender + '/images/'+ attr + '/' + m + '.png" id="icon_' + m + '" onclick="'+ invoke +'(\'' + attr + '\',\'' + m + '\')" />';
            if (help)
                s += '<img src="../../images/help.png" onclick="alert(\'help ' + m + '\')" />';
            s += '</div>';
            s += m;
            s += '</td>';
            i++;
            if (i >= cols)
                i = 0;
            s += i ? '' : '</tr>';
        }

    } else {
        for (var v in currentProductAttr[attr].values) {
            s += i ? '' : '<tr>';
            s += '<td>';
            s += '<div class="design_menu_popup_icon">';
            s += '<img src="/' + contentGender + '/images/' + v + '.png" id="icon_' + v + '" onclick="'+ invoke +'(\'' + attr + '\',\'' + v + '\')" />';
            if (help)
                s += '<img src="../../images/help.png" onclick="alert(\'help ' + v + '\')" />';
            s += '</div>';
            s += currentProductAttr[attr].values[v].displayName;
            if (attr_cost (attr) == 0 && attr_value_cost (attr, v) > 0)
                s += '<span class="addcost" id="' + v + '_cost"> (+' + currentProductAttr[attr].values[v].price + 'p)</span>';
            s += '</td>';
            i++;
            if (i >= cols)
                i = 0;
            s += i ? '' : '</tr>';
        }
    }
    if (i) {
        for (j = i; j < cols; j++)
            s += '<td>&nbsp;</td>';
        s += '</tr>';
    }
    s += '</table>';
    write_inner ('select_' + attr, s);

}
/*
function write_unisex_popup (attr, cols, small, toInvoke, subdir) {
    var s = '';
    var i = 0;
    var j;
    s += '<table cellpadding="5">';
    invoke = 'select_icon';
    if(toInvoke) {
        invoke = toInvoke;
    }
    dir = '../../images/';
    if(subdir) {
        dir += subdir + '/';
    }

    divClass = 'design_menu_popup_icon';
    if(small) {
        divClass = 'design_menu_small_popup_icon';
    }

    if (!currentProductAttr[attr].values && currentProductAttr[attr].attr && currentProductAttr[attr].attr.attrType == 'measure') {
        from = parseInt (currentProductAttr[attr].attr.min);
        to = parseInt (currentProductAttr[attr].attr.max);
        for (m = from; m<=to; m++) {
            s += i ? '' : '<tr>';
            s += '<td>';
            s += '<div class="'+ divClass +'">';
            s += '<img src="' + dir + attr + '/' + m + '.png" id="icon_' + m + '" onclick="'+ invoke +'(\'' + attr + '\',\'' + m + '\')" />';
            s += '</div>';
            s += m;
            s += '</td>';
            i++;
            if (i >= cols)
                i = 0;
            s += i ? '' : '</tr>';
        }

    } else {
        for (var v in currentProductAttr[attr].values) {
            s += i ? '' : '<tr>';
            s += '<td>';
            s += '<div class="'+ divClass +'">';
            s += '<img src="' + dir + v + '.png" id="icon_' + v + '" onclick="'+ invoke +'(\'' + attr + '\',\'' + v + '\')" />';
            s += '</div>';
            s += currentProductAttr[attr].values[v].displayName;
            if (attr_cost (attr) == 0 && attr_value_cost (attr, v) > 0)
                s += '<span class="addcost" id="' + v + '_cost"> (+' + currentProductAttr[attr].values[v].price + 'p)</span>';
            s += '</td>';
            i++;
            if (i >= cols)
                i = 0;
            s += i ? '' : '</tr>';
        }
    }
    if (i) {
        for (j = i; j < cols; j++)
            s += '<td>&nbsp;</td>';
        s += '</tr>';
    }
    s += '</table>';
    write_inner ('select_' + attr, s);

}
*/
function write_tieWidth_popup (attr, cols, toInvoke) {
    var s = '';
    var i = 0;
    var j;
    s += '<table cellpadding="5">';
    invoke = 'select_icon';
    if(toInvoke) {
        invoke = toInvoke;
    }

    from = parseInt (currentProductAttr[attr].attr.min);
    to = parseInt (currentProductAttr[attr].attr.max);
    for (m = from; m<=to; m++) {
        s += i ? '' : '<tr>';
        s += '<td>';
        s += '<div class="design_menu_small_popup_icon">';
        s += '<img src="/' + contentGender +  '/images/'+ attr + '/' + m + '.png" id="icon_' + m + '" onclick="'+ invoke +'(\'' + attr + '\',\'' + m + '\')" />';
        s += '</div>';
        s += m + '&nbsp;см';
        s += '</td>';
        i++;
        if (i >= cols)
            i = 0;
        s += i ? '' : '</tr>';
    }
    write_inner ('select_' + attr, s);

}

function write_fabric_popup (attr, cols, help) {
    var icon = attr == 'contrastFabric' ? 'icon_contrast_' : 'icon_';
    var s = '';
    var i = 0;
    var j;
    var base = attr == 'tieFabric' ?
        tie_design_base : design_base;
    s += '<table cellpadding="5">';
    for (var v in currentProductAttr[attr].values) {
        s += i ? '' : '<tr>';
        s += '<td>';
        s += '<div class="design_menu_popup_icon">';
        s += '<img src="' + base + v + '/fabric.png" id="' + icon + v + '" onclick="select_icon(\'' + attr + '\',\'' + v + '\')" />';
        if (help)
            s += '<img src="../../images/help.png" onclick="alert(\'help ' + v + '\')" />';
        s += '</div>';
        //if (attr == 'fabric')
            s += '<div class="fabric_price">' + currentProductAttr[attr].values[v].price + ' руб.</div>';
        s += '<div class="fabric_cotton">' + currentProductAttr[attr].values[v].shortComposition + '</div>';
        s += '<div class="fabric_name">' + currentProductAttr[attr].values[v].displayName + '</div>';
        s += '</td>';
        i++;
        if (i >= cols)
            i = 0;
        s += i ? '' : '</tr>';
    }
    if (i) {
        for (j = i; j < cols; j++)
            s += '<td>&nbsp;</td>';
        s += '</tr>';
    }
    s += '</table>';
    write_inner ('select_' + attr, s);
}

function write_tieLength_popup (attr, cols, help) {

}
function write_buttons_popup (attr, cols, help) {
    var s = '';
    var i = 0;
    var j;
    s += '<table cellpadding="5">';
    for (var v in currentProductAttr[attr].values) {
        s += i ? '' : '<tr>';
        s += '<td>';
        s += '<div class="design_menu_popup_icon">';
        s += '<img src="../buttons/' + v + '/pict.png" id="icon_' + v + '" onclick="select_icon(\'' + attr + '\',\'' + v + '\')" />';
        if (help)
            s += '<img src="../../images/help.png" onclick="alert(\'help ' + v + '\')" />';
        s += '</div>';
        s += currentProductAttr[attr].values[v].displayName;
        s += '</td>';
        i++;
        if (i >= cols)
            i = 0;
        s += i ? '' : '</tr>';
    }
    if (i) {
        for (j = i; j < cols; j++)
            s += '<td>&nbsp;</td>';
        s += '</tr>';
    }
    s += '</table>';
    write_inner ('select_' + attr, s);
}

function write_buttonsThread_popup (attr, cols, help) {
    var icon = attr == 'embroideryColor' ? 'icon_embroideryColor_' : 'icon_';
    var s = '';
    var i = 0;
    var j;
    s += '<table cellpadding="5">';
    for (var v in currentProductAttr[attr].values) {
        s += i ? '' : '<tr>';
        s += '<td>';
        s += '<div class="design_menu_popup_icon">';
        s += '<img src="/' + contentGender + '/threads/' + v + '/pict.png" id="' + icon + v + '" onclick="select_icon(\'' + attr + '\',\'' + v + '\')" />';
        if (help)
            s += '<img src="../../images/help.png" onclick="alert(\'help ' + v + '\')" />';
        s += '</div>';
        s += currentProductAttr[attr].values[v].displayName;
        s += '</td>';
        i++;
        if (i >= cols)
            i = 0;
        s += i ? '' : '</tr>';
    }
    if (i) {
        for (j = i; j < cols; j++)
            s += '<td>&nbsp;</td>';
        s += '</tr>';
    }
    s += '</table>';
    write_inner ('select_' + attr, s);
}

function shirt_design_page () {
    design_step (1);
}

function tie_design_page() {
    design_step(1);
}

function booklet_design_page () {
    design_step(1);
}

function testShirt_page () {
    shirt_design_page ();
}

function test_design_init (section) {
    design_init (section);
    disable_controls ();
}

function hide_test_menu (item) {
    disable_controls ();
    hide_item (item);
}

//Выбор длины галстука в зависимости от обхвата шеи и роста
function select_height(what) {
    //Пытаемся собрать все вычисления
    if('tieLengthNeck' == what) {
        value = elt('tieLengthNeck').value;
        if(IsInt(value))
            product.tieLengthNeck = value;
    }
    if('tieLengthHeight' == what) {
        value = elt('tieLengthHeight').value;
        if(IsInt(value))
            product.tieLengthHeight = value;
    }

    if(product.tieLengthNeck && product.tieLengthHeight && (what == 'tieLengthNeck' || what == 'tieLengthHeight')) {
        gost = parseInt(product.tieLengthHeight)*28/100;
        value = parseInt(product.tieLengthNeck) + Math.round(gost*7/4) + 20;
        /*
        remainder = value % 5;
        
        value -= remainder
        if(remainder >= 2.5)
            value += 5;
        */
       
        //product.tieHeight = value;
        //select_icon('tieLength', value);
        product.tieLength = value;

        //elt('tieLengthRecommend').value = value;
        elt('tieLengthRecommend').innerHTML = value + ' cм';

    }

    if('tieLengthUserdef' == what) {
        value = elt('tieLengthUserdef').value;
        if(IsInt(value)) {
            //product.tieHeight = value;
            //select_icon('tieLength', value);
            product.tieLength = value;
        }
            //product.tieLength = value;
    }

}

//Вычисляет, какие значения показать пользователю
function select_heightRange(what) {
    if('tieLengthFrom' == what) {
        value = elt('tieLengthFrom').value;
        if(IsInt(value)) {
            remainder = value % 5;
            product.tieLengthFrom = value - remainder;
        }
    }
    if('tieLengthTo' == what) {
        value = elt('tieLengthTo').value;
        if(IsInt(value)) {
            remainder = value % 5;
            value -= remainder
            if(remainder >= 2)
                value += 5;

            product.tieLengthTo = value;
        }
    }

    if(product.tieLengthFrom && product.tieLengthTo) {
        generateRangeDropdown(parseInt(product.tieLengthFrom), parseInt(product.tieLengthTo), 5, 'tieLengthSelect');
        select_icon('tieLength', elt('tieLengthSelect').value);
        product.tieHeight = product.tieLength;
    }
}

function select_width(value) {
    if(IsInt(value)) {
        //select_icon('tieWidth', value);
        product['tieWidth'] = value;
    }
}

//Функция генерирует опции выпадающему списку по выбранному диапазону с выбранным шагом
function generateRangeDropdown(From, To, Step, elementName) {
    html = '';
    elem = elt(elementName);
    from = parseInt(From);
    to = parseInt(To);
    step = parseInt(Step);
    begin = end = 0;
    if(!IsInt(from)|| !IsInt(to)) //не отвлекаемся на левый ввод
        return;
    //отфильтруем любителей вводить числа не в том порядке
    if(from < to) {
        begin = from;
        end = to;
    } else {
        begin = to;
        end = from;
    }
    //генерируем список
    for(var i = begin; i<= end; i += step) {
        html += '<option id="' + elementName + '" value="' + i + '">' + i + '</option>';
    }

    //Заполнить опциями селект
    elem.innerHTML = html;
}

//Включает соответствующий элемент
function tieLengthTablesToggle(what) {
    if('table_tieLengthAdvisor' == what) {
        //change_popup('table_tieLengthAdvisor');
        elt('table_tieLengthAdvisor').className = 'table_tieLengthAdvisor';
        elt('table_tieLengthRange').className = 'design_menu_popup_bg';
        
    } else {
        //change_popup('table_tieLengthRange');
        elt('table_tieLengthRange').className = 'table_tieLengthRange';
        elt('table_tieLengthAdvisor').className = 'design_menu_popup_bg';
        
    }
}

function IsInt(data){
    return parseInt(data)==data;
}

//Выбор толщины галстука в зависимости от чекбокса
function select_thickness(what) {

    if(typeof what == 'object' && what.value != null) {
        product.tieThickness = what.value;
    }
    if(typeof what == 'string') {
         input = document.getElementById(what);
         if(input != null)
             input.checked = 'checked';
         product.tieThickness = what;
    }

}

