// JScript File
/**
 * количество выбранных марок/моделей(для раздела куплю)
 */
var numberItems = {make:0,region:0,smake:0};
/**
 * максимальное количество добавляемых элементов
 */
var maxItems = {make:50,region:50,smake:50};
/**
 * массив выбранных марок/моделей(для раздела куплю) 
 */
var mass_selected_items = {make:[],region:[],smake:[]};
var gLinkBaseMap =
{
    arc:
    [
            {
                from: ['#inMake'],
                to: ['Autocomplete?request=/@am/list/item=make/vehicle=/make=/%40html/p/&minprefix=0&onlyAvailableValues=true'],
                arcrole: "behavior"
            },
        {
            from: ['#bMake'],
            to: ['Autocomplete?request=/@am/list/item=make/bvehicle=/bmake=/%40html/p/&minprefix=0&onlyAvailableValues=true'],
            arcrole: "behavior"
        },
        {
            from: ['#sMake'],
            to: ['Autocomplete?request=/@am/list/item=make/vehicle=/smake=/%40html/p/&minprefix=0&onlyAvailableValues=true'],
            arcrole: "behavior"
        },           
	    {
	        from: ['#inModel'],
	        to: ['Autocomplete?request=/@am/list/item=model/vehicle=/make=/model=/%40html/p/&minprefix=0&onlyAvailableValues=true'],
	        arcrole: "behavior"
	    },
	    {
	        from: ['#bModel'],
	        to: ['Autocomplete?request=/@am/list/item=model/bvehicle=/bmake=/bmodel=/%40html/p/&minprefix=0&onlyAvailableValues=true'],
	        arcrole: "behavior"
	    },
        {
            from: ['#sModel'],
            to: ['Autocomplete?request=/@am/list/item=model/vehicle=/smake=/smodel=/%40html/p/&minprefix=0&onlyAvailableValues=true'],
            arcrole: "behavior"
        },
	    {
	        from: ['#inModification'],
	        to: ['Autocomplete?request=/@am/list/item=specialMarkingName/vehicle=/make=/model=/modification=/%40html/p/&minprefix=0&onlyAvailableValues=true'],
	        arcrole: "behavior"
	    },		
	    {
	        from: ['#inLocation'],
	        to: ['Autocomplete?request=/@am/list/item=location/region=/location=/%40html/p/&minprefix=0&onlyAvailableValues=true'],
	        arcrole: "behavior"
	    },{
	        from: ['#bLocation'],
	        to: ['Autocomplete?request=/@am/list/item=location/bregion=/blocation=/%40html/p/&minprefix=0&onlyAvailableValues=true'],
	        arcrole: "behavior"
	    }]
};




var onLastChange = { 'inMake': { value: '', needCache: false }, 'inModel': { value: '', needCache: false }, 'inModification': '', 'inLocation': '', 'bMake': { value: '', needCache: false }, 'bModel': { value: '', needCache: false }, 'bLocation': '', 'sMake': { value: '', needCache: false }, 'sModel': { value: '', needCache: false} };
/**
 * разблокирование полей
 * @param {String} elem id элемента, в зависимотси от которого будут разблокированы другие поля
 * @param {String} depend_elem id элемента, который будем разблокировать
 * @param {String} avtocomp_elem "галочка"
 * @param {String} cls1 класс, кот. нужно поставить depend_elem
 * @param {String} cls2 класс, кот. нужно поставить avtocomp_elem 
 */
var DisplayAvtokomp = function(elem,depend_elem,avtocomp_elem,cls1,cls2){
//если выбран элемент	
if($(elem).value != ''){
	//разблокируем остальные поля
        $(depend_elem).removeAttribute('disabled');
        $(depend_elem).className = cls1;
        $(avtocomp_elem).removeAttribute('disabled');
        $(avtocomp_elem).className = cls2;
}
}

var clearCacheAvtokomp = function(idAvto) {
    var obc = $(idAvto);
    if (obc) {
        obc.value = '';
        if (typeof (onLastChange[idAvto].needCache) == undefined)
            onLastChange[idAvto] = '';
        else {
            if (onLastChange[idAvto].needCache)
                onLastChange[idAvto].value = '';
        }
        obc._behaviors[1].clearCache();
    }
}

var onVehicleChange = function() {

    var pRubric = $('sVehicle').value;    
        onLastChange['inMake'].needCache = true;
        onLastChange['inModel'].needCache = true;
		onLastChange['sMake'].needCache = true;
        onLastChange['sModel'].needCache = true;            
        NoneErrorDisplay();    
    SetStandartStyle($('sVehicle'));
    StyleDisplayNoneHtml('sVehicleError');    
    clearCacheAvtokomp('inMake');
    clearCacheAvtokomp('inModel');
    clearCacheAvtokomp('sMake');
    clearCacheAvtokomp('sModel');
    clearCacheAvtokomp('inModification');	
    var mod = $('inModel').disabled;
    var med = $('inMake').disabled;
    var smod = $('sModel').disabled;
    var smed = $('sMake').disabled;
    $("inModel").setAttribute('disabled', 'disabled');
    $("sModel").setAttribute('disabled', 'disabled');
    $("inModification").setAttribute('disabled', 'disabled');
	  
	$("sSubVehicle").innerHTML = '<option> </option>';
	addClass($("sSubVehicle"),'disabled_text');
	$("sSubVehicle").setAttribute('disabled', 'disabled');	

    if (isNullOrUndefined(mod)) $("inModel").setAttribute('disabled', 'disabled');
    $("inModel").className = 'input_select disabled_text';
    $("ImAvtokompModel").setAttribute('disabled', 'disabled');
    $("ImAvtokompModel").className = 'avtokompl1';

    addClass($("sModel"),'disabled_text');
    $("sImAvtokompModel").setAttribute('disabled', 'disabled');
    $("sImAvtokompModel").className = 'b_avtocompl';

    $("inModification").className = 'input_select disabled_text';
    $("ImAvtokompModification").setAttribute('disabled', 'disabled');
    $("ImAvtokompModification").className = 'avtokompl1';

    if ($('sVehicle').options[$('sVehicle').selectedIndex].value == '') {
        if (isNullOrUndefined(med)) $("inMake").setAttribute('disabled', 'true');
        $("inMake").className = 'input_select disabled_text';
        $("ImAvtokompMake").setAttribute('disabled', 'true');
        $("ImAvtokompMake").className = 'avtokompl1';
    }
    else {
        if (!isNullOrUndefined(med)) $('inMake').removeAttribute('disabled');
        if (!isNullOrUndefined(smed)) $('sMake').removeAttribute('disabled');
        $("inMake").className = 'input_select';
        $('ImAvtokompMake').removeAttribute('disabled');
        $("ImAvtokompMake").className = 'avtokompl2';

        removeClass($("sMake"), 'disabled_text');
        $('sImAvtokompMake').removeAttribute('disabled');
        $("sImAvtokompMake").className = 'b_avtocompl2';
    }
    ChangeNeedStyle($("sVehicle").value);
};

var onRegionChange = function() {
    clearCacheAvtokomp('inLocation');

    var med = $('inLocation').disabled;
    StyleDisplayNoneHtml('sRegionListError');
    if ($('sRegionList').options[$('sRegionList').selectedIndex].value == '') {
        if (isNullOrUndefined(med)) $("inLocation").setAttribute('disabled', 'true');
        $("inLocation").className = 'input_select disabled_text';
        $("ImAvtokompLocation").setAttribute('disabled', 'true');
        $("ImAvtokompLocation").className = 'avtokompl1';
    }
    else {
        if (!isNullOrUndefined(med)) $('inLocation').removeAttribute('disabled');
        $("inLocation").className = 'input_select';
        $('ImAvtokompLocation').removeAttribute('disabled');
        $("ImAvtokompLocation").className = 'avtokompl2';
    }
};

//var synhElID = function(elid) {
//    $(elid + 'Id').selectedIndex = $(elid).selectedIndex;
//};
/**
    * добавление класса к элементу
    * @param el {Object} элемент
    * @param cls {String} класс, кот нужно добавить
*/
var addClass = function(el,cls){
    if(el.className.indexOf(cls) == -1){
        el.className += (el.className == '')?cls:(' '+cls);
    }
}
/**
    * удаление класса у элемента
    * @param el {Object} элемент
    * @param cls {String} класс, кот нужно удалить
*/

function removeClass (el,cls){
    if(el){
        el.className = el.className.replace(cls,'');
    }    
}

/*-----------------правильность заполнения полей-----------*/
/**
 * проверка правильности ввода объема двигателя
*/
    
var testVolumeEngine = function(el){
    var reg = /^\d+(\.\d+)?$/;
    var val = el.value.trim();
    if(val != ''){
        if(!(reg.test(val))){
            el.value = '';
        }
    }
}

var testKey = function(e) {
    var reg = /^\d+$/;
    var val = e.srcElement.value.trim();
    var idError = e.srcElement.id;
    if (val != "") {
        if (!(reg.test(val))) {
            e.srcElement.value = '';            
            if (idError != undefined)
                StyleDisplayHtml(idError + 'Error');            
        }
        else {
            if (idError != undefined)
                StyleDisplayNoneHtml(idError + 'Error');
        }
    }
};

var testEmailKey = function(e) {
    var reg = /^[a-zA-Z0-9\._-]+@[a-zA-Z0-9\._-]+\.[a-zA-Z\.]{2,4}$/;
    var val = e.srcElement.value;
    var idError = e.srcElement.id;
    if (val != "") {
        if (!(reg.test(val))) {
            e.srcElement.value = '';
            if (idError != undefined)
                StyleDisplayHtml(idError + 'Error');
        }
        else {
            if (idError != undefined)
                StyleDisplayNoneHtml(idError + 'Error');
        }
    }
};

//Проверка телефона наложенная на код
var testPhoneKey = function(kod, phone) {
    var reg = /^\d+$/;
    var valCode = kod.value.trim();    
    var valPhone = phone.value.trim();
    if (!(reg.test(valCode)))
        return false;
    if (!(reg.test(valPhone)))
        return false;    
    if ((valCode.length + valPhone.length) != 10)
        return false;
    return true;
};

//Проверка email - булевская
var testKeyEmail = function(email) {
    var reg = /^[a-zA-Z0-9\._-]+@[a-zA-Z0-9\._-]+\.[a-zA-Z\.]{2,4}$/;
    var valemail = email.value.trim();
    if (!(reg.test(valemail)))
        return false;
    if ("" == valemail)
        return false;
    return true;
};
/*---------------------------------------------------------*/

var onMakeChange = function (code, p) {
    if ((onLastChange['inMake'].value != $('inMake').value) && (code != -1)) {
        clearCacheAvtokomp('inModel');
        clearCacheAvtokomp('inModification');
		//очищаем и блокируем раздел
		var elem = $('sSubVehicle');
		elem.innerHTML = '';
		setOption(elem,' ');
		setDisabledToField(elem);										
    }
    SetStandartStyle($('inMake'));
    StyleDisplayNoneHtml('inMakeError');
    var mod = $('inModel').getAttribute('disabled');    
    switch (code) {
        // заблокировать модель     
        case -1: //Нет в списке
            if (p == 1) {//ввод окончен
                if (onLastChange['inMake'].needCache)//Если ввод только из списка
                    $('inMake').value = onLastChange['inMake'].value;
                else {//Можно вводить не из списка
                    if (!isNullOrUndefined(mod)) $('inModel').removeAttribute('disabled');
                    $("inModel").className = 'input_select';
                    $('ImAvtokompModel').removeAttribute('disabled');
                    onLastChange["inModel"].value = '';
                    $("inModel").value = '';
                }
                //if (isNullOrUndefined(mod)) $("inModel").setAttribute('disabled', 'true');
                //$("inModel").className = 'disabled_text';
            }
            break;

        //разблокировать модель     
        default: //Есть в списке
            onLastChange['inMake'].value = $('inMake').value;
            if (!isNullOrUndefined(mod)) $('inModel').removeAttribute('disabled');
            $("inModel").className = 'input_select';
            $('ImAvtokompModel').removeAttribute('disabled');
            $("ImAvtokompModel").className = 'avtokompl2';
            break;
    }
};

var onModelChange = function (code, p) {
    if ((onLastChange['inModel'].value != $('inModel').value) && (code != -1)) {
        clearCacheAvtokomp('inModification');	
    }
    SetStandartStyle($('inModel'));
    StyleDisplayNoneHtml('inModelError');
    var mod = $('inModification').getAttribute('disabled');	
    switch (code) {
        // заблокировать модель  
        case -1:
            if (p == 1) {
                if (onLastChange['inModel'].needCache)
                    $('inModel').value = onLastChange['inModel'].value;
            }
            break;

        //разблокировать модификацию  
        default:
            onLastChange['inModel'].value = $('inModel').value;
            if (!isNullOrUndefined(mod)) $('inModification').removeAttribute('disabled');			
            $("inModification").className = 'input_select';
            $('ImAvtokompModification').removeAttribute('disabled');
            $("ImAvtokompModification").className = 'avtokompl2';
            
			//разблокируем подраздел если это не раздел легковые 
			if ($('sVehicle').value != 'легковые'){						
				updateSelect();
			}
            break;
    }
};

var encodeValue = function(id){
	return encodeURIComponent($(id).value);
}

var updateSelect = function (callback){
	var url = '/@am/list/item=subvehicle/vehicle='+encodeValue('sVehicle')+'/make='+encodeValue('inMake')+'/model='+encodeValue('inModel')+'/@html/p/';
	try{
        Ext.Ajax.request({            
            url: url,
            //кешировать или нет запрос(добавляет параметр)
            disableCaching: false,
            success: function(response) {
				innerHtmlSelect(Ext.util.JSON.decode(response.responseText));
				if(typeof callback == 'function'){
					callback();
				}
            },
            failure: function() {}
        });}
		catch (e){}
}
/**
 * обработка ответа на запрос о подразделах
 * @param {Array} mass
 */
var innerHtmlSelect = function(mass){
	var length = mass.length;
	var elem = $('sSubVehicle');
	elem.innerHTML = '';	
	if (length == 1){
			removeDisabledField(elem);	
			setOption(elem,mass[0][0].value);			
	}	else {
			setOption(elem,' ');
			if (length == 0){
				setDisabledToField(elem);
			}						
			if (length > 1) {
				removeDisabledField(elem);
				Ext.each(mass,function(el){
					setOption(elem,el[0].value);						
	});		
			}
	}			
	
}

var setDisabledToField = function(el){
	el.setAttribute('disabled','disabled');
	addClass(el,'disabled_text');
}

var removeDisabledField = function(el){
	el.removeAttribute('disabled');
	removeClass(el,'disabled_text');		
}

var setOption = function(elem,val){
	var opt = document.createElement('option');
	opt.setAttribute('value',val);
	opt.innerHTML = val;
	elem.appendChild(opt);
}

var setListSubVehicles = function(){
	var sel_opt = selectElemForm('sSubVehicle');
	updateSelect(function(){
		if ('' != sel_opt) {
			var mass = Ext.get('sSubVehicle').select('option[value=' + sel_opt + ']').elements;
			if (mass.length != 0) {
				mass[0].setAttribute('selected', 'selected');
			}
		}
	});
}

//Можно вводить только из списка
var onLocationChange = function(code, p) {
StyleDisplayNoneHtml('inLocationError');
    switch (code) {
        // Нет элемента в списке
        case -1:
            if (p == 1) {
                $('inLocation').value = onLastChange['inLocation'];
            }
            break;
        // сохраняем в последний удачный ввод
        default:
            onLastChange['inLocation'] = $('inLocation').value;
            break;
    }
};

/**********************************************************************************************************************************/
var onChange = function(code, o, p) {
    var eId = null;
    try {
        eId = o._domElement.id;
    }
    catch (e) {
    }
    switch (eId) {
        case 'inMake':
            onMakeChange(code, p);
            break;
        case 'sMake':
            onbMakeChange(code, p,'s');
            break;
        case 'bMake':
        	onbMakeChange(code, p,'b');
            break;
        case 'inModel':
            onModelChange(code, p);
            break;
        case 'sModel':
            onbModelChange(code, p,'s');
            break;
        case 'bModel':
            onbModelChange(code, p,'b');
            break;
        case 'inLocation':
            onLocationChange(code, p);
            break;
        case 'bLocation':
            onbLocationChange(code, p);
            break;
        case 'inModification':
            if ((code == -1) && (p == 0)) {
                $("ImAvtokompModification").setAttribute('disabled', 'disabled');
                $("ImAvtokompModification").className = 'avtokompl1';                
            }
            break;       
        default:
            break;
    }
};

/**
* проверка формы на правильность заполнения
*/
var checkForm = function (pSender) {
    var form = null;
    try {
        form = pSender;
    } catch (e) { }
    if (form.getAttribute("id") == 'sNewob') {
        NoneErrorDisplay();
        // Хэш с текстом ошибок (ключ - ID ошибки)
        var errorList = [];
        // Хэш с текстом ошибок (ключ - ID ошибки)
        var errorText = {
            1: "Код телефона либо номер контакта, введенный вами, неверен",
            2: "Вы не выбрали Раздел",
            3: "Вы не указали марку вашего авто",
            4: "Вы не указали модель вашего авто",
            5: "Вы не указали год выпуска вашего авто",
            6: "Вы не указали Регион",
            7: "Вы не указали Город",
            8: "Вы не указали Цену",
            9: "Вы не указали тип КПП",
            10: "Вы не выбрали Цвет",
            11: "Вы не указали пробег. Если вы не хотите указывать пробег установите не указывать!",
            12: "Введенный вами e-mail не верен",
            13: "Вы не указали тип кузова",
            14: "Вы не указали тип топлива",
            15: "Вы не указали объем двигателя",
            16: 'Вы не указали заголовок'
        }

        var setError = function (id, num, cls) {
            errorList.push(num);
            StyleDisplayHtml(id + 'Error');
            addClass($(id), cls);
            if (errorFocus == '')
                errorFocus = id;
        }

        var elemVehicle = $("sVehicle").value;
        var errorFocus = '';
        //e-mail
        var elemMail = $("inEmail");
        var GoodMail = testKeyEmail(elemMail);
        if (!GoodMail) {
            setError('inEmail', 12, 'err_style');            
        }
        // телефоны
        var ii = 1;
        while (ii < maxPhone + 1) {
            var elemCode = $("inCodePhone" + ii);
            var elemPhone = $("inPhone" + ii);
            if (elemCode == null) {
                ii = maxPhone + 1;
            }
            if (ii < maxPhone + 1) {
                var GoodTel = testPhoneKey(elemCode, elemPhone);
                if (!GoodTel) {
                    errorList.push(1);
                    StyleDisplayHtml('inPhoneError');
                    SetErrorElementStyle($("inPhone" + ii));
                    SetErrorElementStyle($("inCodePhone" + ii));
                    if (errorFocus == '')
                        if (elemCode.value == '')
                            errorFocus = "inCodePhone" + ii;
                        else
                            errorFocus = "inPhone" + ii;
                }
            }
            ii += 1;
        }

        var ii = 1;
		var one_correct_seller_phone = false;
		var err_index_mass = [];
        while (ii < maxsellerPhone + 1) {
            var elemSellerCode = $("inSellerCodePhone" + ii);
            var elemSellerPhone = $("inSellerPhone" + ii);			
            if (elemSellerCode == null) {
                ii = maxsellerPhone + 1;
            }
            if (ii < maxsellerPhone + 1) {
				var GoodTel = testPhoneKey(elemSellerCode, elemSellerPhone);
				if (!GoodTel) {
					if(elemSellerCode.value != '' && elemSellerPhone != ''){					
						err_index_mass.push(ii);						
					}					
				}else {
					one_correct_seller_phone = true;
				}				
            }			
            ii += 1;        	
		}			
		if(!one_correct_seller_phone || (one_correct_seller_phone && err_index_mass.length)){
			if(!err_index_mass.length){
				err_index_mass.push('1');
			}
			for (var ii = 0; ii < err_index_mass.length; ii++){
				errorList.push(1);
						StyleDisplayHtml('inSellerPhoneError');
						SetErrorElementStyle($("inSellerPhone" + err_index_mass[ii]));
						SetErrorElementStyle($("inSellerCodePhone" + err_index_mass[ii]));
						if (errorFocus == '') 
							if (elemSellerCode.value == '') 
								errorFocus = "inSellerCodePhone" + err_index_mass[ii];
							else 
								errorFocus = "inSellerPhone" + err_index_mass[ii];
			}
		}
		
        //раздел
        if (elemVehicle == '') {
            setError('sVehicle', 2, 'err_style');             
        }
        //марка и цена обязательны для всех полей, кроме разделов разное и запчасти
        if (elemVehicle != 'запчасти' && elemVehicle != 'разное') {
            if ($("inMake").value == '') {
                setError('inMake', 3, 'err_style');                             
            }

            if ($("inPrice").value == '') {
                setError('inPrice', 8, 'err_style');                
            }
        } else {
            if ($('sTitle').value == '') {
                setError('sTitle', 16, 'err_style');                
            }
        }

        if ($("sRegionList").value == '') {
            setError('sRegionList', 6, 'err_style');            
        }
        if ($("inLocation").value == '') {
            setError('inLocation', 7, 'err_style');            
        }
		if (elemVehicle == "легковые" || elemVehicle == "микроавтобусы" || elemVehicle == "мототранспорт") {
			if ($('inVolumeEngine').value == '') {
                setError('inVolumeEngine', 15, 'error-style');               
            }
		}
        if (elemVehicle == "легковые") {            
            if ($('sBodyType').value == '') {
                setError('sBodyType', 13, 'error-style');                  
            }
        }
        if (elemVehicle == "легковые" || elemVehicle == "грузовые" || elemVehicle == "автобусы" || elemVehicle == "микроавтобусы" || elemVehicle == "водный транспорт" || elemVehicle == "мототранспорт" || elemVehicle == "прицепы" || elemVehicle == "спецтехника") {
            if ($("inModel").value == '') {
                setError('inModel', 4, 'err_style');                
            }
        }

        if (elemVehicle == "легковые" || elemVehicle == "грузовые" || elemVehicle == "автобусы" || elemVehicle == "микроавтобусы" || elemVehicle == "спецтехника" || elemVehicle == "мототранспорт" || elemVehicle == "водный транспорт" || elemVehicle == "прицепы") {
			if ($("inYear").value == '') {
				setError('inYear', 5, 'err_style');
			}
		}		
		if (elemVehicle == "легковые" || elemVehicle == "грузовые" || elemVehicle == "автобусы" || elemVehicle == "микроавтобусы") {
            if ($('sFuelUsed').value == '') {
                setError('sFuelUsed', 14, 'error-style');                 
            }
            if ($("sTransmissionType").value == '') {
                setError('sTransmissionType', 9, 'err_style');                
            }
            if ($("sColor").value == '') {
                setError('sColor', 10, 'err_style');                
            }
            if (($("inRun").value == '') && (!($("noRace").checked))) {
                setError('inRun', 11, 'err_style');                
            }
        }

        // Финальная стадия
        // Если массив ошибок пуст - возвращаем true
        if (!errorList.length) {            
            $("inRaz").focus();            
            return true;
        }       
        if (errorFocus != '')
            $(errorFocus).focus();       
        return false;
    }
    return true;
};

var onClick = function(el) {
    if (!el.disabled) {
        el.focus();
        /*var dictionary = {};
        dictionary['prefix'] = el.value;
        dictionary['count'] = el._behaviors[1]._options$1.itemCount;
        var tRef = correctingUrl(el._behaviors[1]._options$1.service);
        el._behaviors[1]._itemRequest$1 = ScriptFX.Net.HTTPRequest.createRequest(ScriptFX.Net.HTTPRequest.createURI(tRef, dictionary), ScriptFX.Net.HTTPVerb.GET);
        el._behaviors[1]._itemRequest$1.invoke(Delegate.create(el._behaviors[1], el._behaviors[1]._onRequestComplete$1), dictionary);*/
    }
};

//Стиль элемента с ошибкой
var SetErrorElementStyle = function(element) {
    if (typeof (element) != undefined) {
    	addClass(element,'err_style');
    }
};

//Стандартый стиль
var SetStandartStyle = function(element) {
    if (typeof (element) != undefined) {
        removeClass(element,'err_style');
    }
};

//Скрыть все надписи об ошибках
var NoneErrorDisplay = function() {
    SetStandartStyle($("inYear"));
    SetStandartStyle($("inPrice"));
    SetStandartStyle($("inRun"));
    var ii = 1;
    while (ii < maxPhone + 1) {
        var elemCode = $("inCodePhone" + ii);
        var elemPhone = $("inPhone" + ii);
        if (elemCode == null) {
            ii = maxPhone + 1;
        }
        else {
            SetStandartStyle($("inCodePhone" + ii));
            SetStandartStyle($("inPhone" + ii));
            ii += 1;
        }
    }
    ii = 1;
    while (ii < maxsellerPhone + 1) {
        var elemCode = $("inSellerCodePhone" + ii);
        var elemPhone = $("inSellerPhone" + ii);
        if (elemCode == null) {
            ii = maxPhone + 1;
        }
        else {
            SetStandartStyle($("inSellerCodePhone" + ii));
            SetStandartStyle($("inSellerPhone" + ii));
            ii += 1;
        }
    }
    SetStandartStyle($("inEmail"));
    SetStandartStyle($("sTransmissionType"));
    SetStandartStyle($("inMake"));
    SetStandartStyle($("inModel"));
    SetStandartStyle($("sColor"));
    $('sFuelUsed').className = $('sFuelUsed').className.replace('error-style','');
    $('inVolumeEngine').className = $('inVolumeEngine').className.replace('error-style','');
    $('sBodyType').className = $('sBodyType').className.replace('error-style','');
    StyleDisplayNoneHtml('sVehicleError');
    StyleDisplayNoneHtml('inMakeError');
    StyleDisplayNoneHtml('inModelError');
    StyleDisplayNoneHtml('inEmailError');
    StyleDisplayNoneHtml('inPhoneError');
    StyleDisplayNoneHtml('inSellerPhoneError');
    StyleDisplayNoneHtml('inYearError');
    StyleDisplayNoneHtml('sRegionListError');
    StyleDisplayNoneHtml('inLocationError');
    StyleDisplayNoneHtml('inPriceError');
    StyleDisplayNoneHtml('sTransmissionTypeError');
    StyleDisplayNoneHtml('sColorError');
    StyleDisplayNoneHtml('inRunError');
    StyleDisplayNoneHtml('sFuelUsedError');
    StyleDisplayNoneHtml('inVolumeEngineError');
    StyleDisplayNoneHtml('sBodyTypeError');
    SetStandartStyle($('sTitleError'));	
};
//Установка необходимых стилей в зависимости от выбранного раздела
var ChangeNeedStyle = function (pRubric) {
	
	/**
		 * блокировка полей
		 * @param {Array} mass массив id элементов
		 */
		var disabledFields = function(mass){
			Ext.each(mass,function(el){
			$(el).removeAttribute('disabled','disabled');
		});
		} 

		/**
		 * разблокируем поля
		 * @param {Array} mass массив id элементов
		 */
		var enabledFields = function(mass){
			Ext.each(mass,function(el){
			$(el).setAttribute('disabled','disabled');
		});
		} 

		var mass1 = ['inYear','sCondition','notCleared','credit','mortgage','inPrice','sCurrency','possibleExchange',
		'sEngineType','sFuelUsed','inVolumeEngine','inHorsepower','inOutGo','sTransmissionType','inTransmissionSteps',
		'sBodyType','inDoorsAmount','sColor','inTinge','inRun','sUnit','inNoRunSNG','list2','list1'];
		
		var mass2 = ['sTitle','sPrice','sCurr'];
	
    //установка нужных полей для раздела разное и запчасти
    if (pRubric == 'запчасти' || pRubric == 'разное') {
        $('makeFl').style.display = 'none';
        $('modelFl').style.display = 'none';        
        $('modificatFl').style.display = 'none';
        $('creditFl').style.display = 'none';
        $('mortgageFl').style.display = 'none';
        $('prFl').style.display = 'none';
        $('engFl').style.display = 'none';
        $('transmFl').style.display = 'none';
        $('bodyFl').style.display = 'none';
        $('raceFl').style.display = 'none';
        $('featureFl').style.display = 'none';
		$('subVehFl').style.display = 'none';
			
		enabledFields(mass1);

		disabledFields(mass2);

        $('titleFl').style.display = '';
        $('priceFl').style.display = '';
        $('makeModelFl').style.display = '';
    } else {
		enabledFields(mass2);
		
        $('makeFl').style.display = '';
        $('modelFl').style.display = '';
        $('modificatFl').style.display = '';
        $('creditFl').style.display = '';
        $('mortgageFl').style.display = '';
        $('prFl').style.display = '';
        $('engFl').style.display = '';
        $('transmFl').style.display = '';
        $('bodyFl').style.display = '';
        $('raceFl').style.display = '';
        $('featureFl').style.display = '';
		$('subVehFl').style.display = '';

		disabledFields(mass1);

        $('titleFl').style.display = 'none';
        $('priceFl').style.display = 'none';
        $('makeModelFl').style.display = 'none';
    }
    // установка обязательности полей в зависимости от выбора раздела
    if (pRubric == "легковые" || pRubric == "грузовые" || pRubric == "автобусы" || pRubric == "микроавтобусы") {
        //ставим звездочки(обязательный пункт заполнения), если выбрана рубрика "легковые"
        if (pRubric == "легковые" || pRubric == "микроавтобусы") {
            addRequiredField(['VolumeEngineLabel', 'BodyLabel']);
        } else {
            removeRequiredField(['VolumeEngineLabel', 'BodyLabel']);
        }
        removeRequiredField(['titleLabel']);           
        addRequiredField(['FuelLabel', 'KPPLabel', 'ColorLabel', 'modelLabel', 'YearLabel', 'inRunLabel', 'makeLabel', 'priceLabel']);
    }

    else {
		if (pRubric == 'спецтехника' || pRubric == 'мототранспорт' || pRubric == 'водный транспорт' || pRubric == 'прицепы'){
			addRequiredField(['YearLabel']);
		}else{
			removeRequiredField(['YearLabel']);
		}
        if (pRubric == "водный транспорт" || pRubric == "мототранспорт" || pRubric == "прицепы"|| pRubric == "спецтехника") {
            addRequiredField(['modelLabel']);
        } else {
            removeRequiredField(['modelLabel']);
        }		
        if (pRubric == "запчасти" || pRubric == "разное") {
            addRequiredField(['titleLabel']);
            removeRequiredField(['makeLabel', 'priceLabel']);
        } else {
            removeRequiredField(['titleLabel']);
            addRequiredField(['makeLabel', 'priceLabel']);
        }		
		if (pRubric == "мототранспорт") {
            addRequiredField(['VolumeEngineLabel']);
        } else {
            removeRequiredField(['VolumeEngineLabel']);
        }
        removeRequiredField(['FuelLabel','ColorLabel','KPPLabel', 'BodyLabel','inRunLabel']);
    }
};


var addRequiredField = function (mass_id) {
    for (var ii = 0; ii < mass_id.length; ii++) {
        addClass($(mass_id[ii]), 'bold');
        StyleDisplayHtml(mass_id[ii] + 'Star');
    }
}

var removeRequiredField = function (mass_id) {
    for (var ii = 0; ii < mass_id.length; ii++) {
        removeClass($(mass_id[ii]), 'bold');              
        StyleDisplayNoneHtml(mass_id[ii] + 'Star');
    }
}


//Установка идентификатора звездочки
var SetIdToStar = function(elemId) {
    var elem = $(elemId);
    for (var i = 0; i < elem.children.length; i++) {
        if (elem.children[i].className == 'label')
            elem.children[i].id = elemId + 'Star';
    }
};

//Галочка не указывать пробег
var onNoRaceChange = function() {
    if ($('noRace').checked) {
        $("sUnit").setAttribute('disabled', 'true');
        $("inRun").setAttribute('disabled', 'true');
        $("inNoRunSNG").checked = false;
        $("inNoRunSNG").setAttribute('disabled', 'true');
        $("inRun").value = 'не указан';
    }
    else {
        $("sUnit").removeAttribute('disabled');
        $("inRun").removeAttribute('disabled');
        $("inNoRunSNG").removeAttribute('disabled');
        $("inRun").value = '';
    }
};

/**
* отправка информации о несуществующем разделе 
*/
var sendInfo = function (titText, defaultText) {
    try {
        defaultText = defaultText || '';
               
            //Создаются панели
            //begin
            var CentrPanel = new Ext.Panel({
                region: 'center',
                margins: '3 3 3 0',
                activeTab: 0,
                html: '<center><h1>Ваши пожелания:</h1><br/>'
					+ '<textarea name="text" cols="55" rows="5">' + defaultText + '</textarea><br/><br/>'
					+ '<h1>Контактная информация:</h1><br/>'
					+ '<input type="text" name="email_address" autocomplete="off"/><br/>'
					+ '<small>Если Вы укажите адрес e-mail, то мы обязательно ответим.</small></center>'
				, defaults: {
				    autoScroll: true
				}
            });
            //end

            //рисуем окно
            //begin

           win = new Ext.Window({
                title: 'Пожелание разработчикам',
                id: 'win',
                modal: true,
                layout: 'border',
                width: 500,
                height: 350,
                closeAction: 'hide',
                plain: true,
                //animateTarget: ElemEvent.id,
                buttonAlign: 'left',
                //анимация
                items: [CentrPanel],
                buttons: [{
                    text: 'ОК',
                    handler: function () {
                        SubmitCommitRC(titText);
                        win.destroy();

                    }
                }, {
                    text: 'Закрыть',
                    handler: function () {
                        win.destroy();
                       
                    } 
                }
					]
            })            
            win.show();    
    }
    catch (e) {}
}

/**
* отправка информации
*/
var SubmitCommitRC = function (titText) {
    try {
        var text_send = Ext.get('win').select('textarea[name=text]').elements[0].value;
        var email_address_send = Ext.get('win').select('input[name=email_address]').elements[0].value;
        if (text_send != '') {
            Ext.Ajax.request({
                url: '/html/php/send_info.php',
                params: {
                    text: text_send,
                    email_address: email_address_send,
                    titleText: titText
                },
                success: function (response) {
                    win.destroy();                
                },
                failure: function () { }
            });
        } 
    }
    catch (e) {}
}

Ext.onReady(function(){
	ChangeNeedStyle(Ext.getDom('sVehicle').value);
	setFields(Ext.getDom('bVehicle').value);
	if(Ext.getDom('sVehicle').value != ''){
		onLastChange['inMake'].needCache = true;
        onLastChange['inModel'].needCache = true;
		onLastChange['sMake'].needCache = true;
        onLastChange['sModel'].needCache = true;		
	}
	if(Ext.getDom('bVehicle').value != ''){
		onLastChange['bMake'].needCache = true;
        onLastChange['bModel'].needCache = true;
	}
});
//window.onload = function() {ChangeNeedStyle(document.getElementById('sVehicle').value);
//setFields(document.getElementById('bVehicle').value);};
/*-----------------------------------------------------------------------------------------*/
/*--------------- РАЗДЕЛ КУПЛЮ-------------------------------------------------------------*/
/*-----------------------------------------------------------------------------------------*/
/**
 * изменения, в зависимости от выбора раздела
 */
var setFields = function(val){
	if(val == 'запчасти' || val == 'разное'){
		$('yearItem').style.display = 'none';
		$('raceItem').style.display = 'none';
		$('volumeItem').style.display = 'none';
		$('conditionItem').style.display = 'none';
		$('transmTypeItem').style.display = 'none';
		$('bodyTypeItem').style.display = 'none';
	}else{
		$('yearItem').style.display = '';
		$('raceItem').style.display = '';
		$('volumeItem').style.display = '';
		$('conditionItem').style.display = '';
		$('transmTypeItem').style.display = '';
		$('bodyTypeItem').style.display = '';
	}
}
var onbVehicleChange = function() {

    var pRubric = $('bVehicle').value;    
        onLastChange['bMake'].needCache = true;
        onLastChange['bModel'].needCache = true;    
    SetStandartStyle($('bVehicle'));
    StyleDisplayNoneHtml('bVehicleError');    
    clearCacheAvtokomp('bMake');
    clearCacheAvtokomp('bModel');    

    var mod = $('bModel').disabled;
    var med = $('bMake').disabled;
    //$("inModel").setAttribute('disabled', 'disabled');   

    if (isNullOrUndefined(mod)) $("bModel").setAttribute('disabled', 'disabled');
    addClass($("bModel"),'disabled_text');
    $("bImAvtokompModel").setAttribute('disabled', 'disabled');
    $("bImAvtokompModel").className = 'b_avtocompl';

    if ($('bVehicle').options[$('bVehicle').selectedIndex].value == '') {
        if (isNullOrUndefined(med)) $("bMake").setAttribute('disabled', 'disabled');
        addClass($('bMake'),'disabled_text');
        $("bImAvtokompMake").setAttribute('disabled', 'disabled');
        $('bImAvtokompMake').className = 'b_avtocompl';
    }
    else {
        if (!isNullOrUndefined(med)) $('bMake').removeAttribute('disabled');
        removeClass($('bMake'),'disabled_text');
        $('bImAvtokompMake').removeAttribute('disabled');
        $("bImAvtokompMake").className = 'b_avtocompl2';
    }
    setFields($("bVehicle").value);
};
/**
 * изменения в случае выбора марки
 */
function onbMakeChange(code, p,prefix) {
    if ((onLastChange[prefix + 'Make'].value != $(prefix + 'Make').value) && (code != -1)) {
        clearCacheAvtokomp(prefix + 'Model');        
    }
    SetStandartStyle($(prefix + 'Make'));    
    var mod = $(prefix + 'Model').getAttribute('disabled');    
    switch (code) {
        // заблокировать модель    
        case -1: //Нет в списке
            if (p == 1) {//ввод окончен
                if (onLastChange[prefix + 'Make'].needCache)//Если ввод только из списка
                    $(prefix + 'Make').value = onLastChange[prefix + 'Make'].value;
                else {//Можно вводить не из списка
                    if (!isNullOrUndefined(mod)) $(prefix + 'Model').removeAttribute('disabled');
                    removeClass($(prefix + 'Model'),'disabled_text');
                    $(prefix + 'ImAvtokompModel').removeAttribute('disabled');
                    onLastChange[prefix + 'Model'].value = '';
                    $(prefix + 'Model').value = '';
                }                
            }
            break;

        //разблокировать модель    
        default: //Есть в списке
            onLastChange[prefix + 'Make'].value = $(prefix + 'Make').value;
            if (!isNullOrUndefined(mod)) $(prefix + 'Model').removeAttribute('disabled');
            removeClass($(prefix + 'Model'),'disabled_text');
            $(prefix + 'ImAvtokompModel').removeAttribute('disabled');
            $(prefix + 'ImAvtokompModel').className = 'b_avtocompl2';
            break;
    }
};
/**
 * изменение модели
 */
var onbModelChange = function(code, p,prefix) {
    switch (code) {
        // заблокировать модель 
        case -1:
            if (p == 1) {
                if (onLastChange[prefix + 'Model'].needCache)
                    $(prefix + 'Model').value = onLastChange[prefix + 'Model'].value;
            }
            break;

        //разблокировать модификацию 
        default:
            onLastChange[prefix + 'Model'].value = $(prefix + 'Model').value;                       
            break;
    }
};
//Можно вводить только из списка
/**
 * изменение города
 */
var onbLocationChange = function(code, p) {
    switch (code) {
        // Нет элемента в списке
        case -1:
            if (p == 1) {
                $('bLocation').value = onLastChange['bLocation'];
            }
            break;
        // сохраняем в последний удачный ввод
        default:
            onLastChange['bLocation'] = $('bLocation').value;
            break;
    }
};
/**
 * изменение региона
 */
var onbRegionChange = function() {
    clearCacheAvtokomp('bLocation');

    var med = $('bLocation').disabled;    
    if ($('bRegion').options[$('bRegion').selectedIndex].value == '') {
        if (isNullOrUndefined(med)) $("bLocation").setAttribute('disabled', 'disabled');
        addClass($('bLocation'),'disabled_text');
        $("bImAvtokompLocation").setAttribute('disabled', 'disabled');
        $("bImAvtokompLocation").className = 'b_avtocompl';
    }
    else {
        if (!isNullOrUndefined(med)) $('bLocation').removeAttribute('disabled');
        removeClass($('bLocation'),'disabled_text');
        $('bImAvtokompLocation').removeAttribute('disabled');
        $("bImAvtokompLocation").className = 'b_avtocompl2';
    }
};
/**
 * добавить выбранные марку-модель или регион-город
 * @param {String} idm id главного элемента (например, марка или регион) 
 * @param {String} idd id зависимого элемента (например, модель или город)
 */
var AddSelectedItems = function (idm, idd, params) {
    var val = $(idm).value;
    var vald = $(idd).value;

    var mass_name = params.mass || params.el1;

    var n = numberItems[mass_name];

    if (val != '' && (n <= maxItems[mass_name])) {
        //повторения не добавлять!
        var fl = true;
        for (var ii = 0; ii < mass_selected_items[mass_name].length; ii++) {
            if (mass_selected_items[mass_name][ii].e1 == val && mass_selected_items[mass_name][ii].e2 == vald) {
                fl = false;
                break;
            }
        }
        if (fl) {
            var elem = document.createElement('div');
            elem.className = 'select_items';
            var inner_elem = '<input type="checkbox" checked="checked" id="' + mass_name + '_' + params.el2 + n + '" name="' + params.el1 + '_' + params.el2 + '[]" value=\'["' + val + '","' + vald + '"]\' class="mult_choice" />';
            inner_elem += '<span>' + val + (vald != '' ? ' ' : '') + vald + '</span>';
            elem.innerHTML = inner_elem;
            $(params.divId).appendChild(elem);
            mass_selected_items[mass_name].push({ e1: val, e2: vald });
            // увеличиваем счетчик успешно добавленных элементов
            numberItems[mass_name]++;
        }
        $(idd).value = '';
        if (idm == 'bMake' || idm == 'sMake') {
            $(idm).value = '';
        }
    }
}
/**
 * подстановка выбора года
 */
var setYearRange = function(from,to){
	var sel_from = $('fromYear');
	var sel_to = $('toYear');
	function checkS(check,sel){
		for(var ii=0; ii<sel.length; ii++){
		if(sel.options[ii].value == check){
			sel.selectedIndex = ii;
		}
	}}
	checkS(from,sel_from);
	checkS(to,sel_to);

}
/**
 * 
 */
var setRange = function(params){
	try {
		$(params.idFrom).value = params.from;
		$(params.idTo).value = params.to;
		
	}catch(e){}
}
 /**
  * убрать все сообщения об ошибках
  */
 var noFormErrorDisplay  = function(){
	 removeClass($("bEmail"),'err_style');
	 removeClass($("bVehicle"),'err_style');
	 removeClass($("inTitle"),'err_style');
	 removeClass($("priceFrom"),'err_style');
	 removeClass($("priceTo"),'err_style');
	 StyleDisplayNoneHtml('bEmailError'); 
	 StyleDisplayNoneHtml('bVehicleError');
	 StyleDisplayNoneHtml('inTitleError');
	 StyleDisplayNoneHtml('idErrPrice');
 }
/**
 * проверка полей формы на правильность заполнения
 */
var checkBuyForm = function(form){
	 noFormErrorDisplay();
	 var errorList = [];
     // Хэш с текстом ошибок (ключ - ID ошибки)
     var errorText = {
         1: "Вы не указали Ваш email",
         2: "Вы не выбрали hаздел",
         3: "Вы не заголовок",
         4: "Вы не указали цену"
     }
     var errorFocus = '';

     var setError = function (id, num, cls) {
         errorList.push(num);
         StyleDisplayHtml(id + 'Error');
         addClass($(id), cls);
         if (errorFocus == '')
             errorFocus = id;
     }

     var elemMail = $("bEmail");
     var mail = testKeyEmail(elemMail);
     if (!mail) {
         setError('bEmai', 1, 'err_style');          
     }
     if ($('bVehicle').value == '') {
         setError('bVehicle', 2, 'err_style');                   
     }
     
     if ($('inTitle').value == '') {
         setError('inTitle', 3, 'err_style');                            
     }
     
     if ($('priceFrom').value == '' && $('priceTo').value == '') {
         errorList.push(4);
         StyleDisplayHtml('idErrPrice');
         SetErrorElementStyle($('priceFrom'));
         SetErrorElementStyle($('priceTo'));
         if (errorFocus == '')
             errorFocus = 'priceFrom';
     }
	if (!errorList.length) {	 	    
	    $("bRaz").focus();	    
	    return true;
	}
	 if (errorFocus != ''){
         $(errorFocus).focus();     
     return false;
	 }
	 return true;
}
/*------------------------------------------*/
