var reg_isAgency = 0;

// Получение аргументов запроса
function getQueryArgument(name) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(window.location.href);
	if( results == null ) {
		return '';
	}
	else {
		return results[1];
	}
}

// correctly handle PNG transparency in Win IE 5.5 & 6
function correctPNG()
{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if ((version >= 5.5) && (document.body.filters)) 
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }    
}

// Выделить все (для чекбоксов)
function toggleCheckAll(chk) {
	for (i=0;i<chk.length;i++) {
		if (chk[i].checked == false) {
			chk[i].checked = true;
		}
		else {
			chk[i].checked = false;
		}
	}
}

function delMyAds(chk) {
	for (i=0;i<chk.length;i++) {
		if (chk[i].checked == true) {
			eval(chk[i].value);
		}
	}
}

function delMySubscribes(chk) {
	for (i=0;i<chk.length;i++) {
		if (chk[i].checked == true) {
			eval(chk[i].value);
		}
	}
}

// Изменение режима отображение формы поиска "Краткий/Подробный"
function toggleRealtySearchForm() {
   // alert(123);
	extendedFormCookie = Get_Cookie('isExtendedForm');
	// Если выбран краткий поиск
	if (extendedFormCookie == '1') {
		document.getElementById('RealtySearchFormExtendedText').style.display='none';
		document.getElementById('RealtySearchFormExtendedLink').innerHTML ='Расширенный >>';
		document.getElementById('RealtySearchFormExtendedCommonInfo').style.display='none';
        document.getElementById('searchSubmit').style.visibility='visible';
		Set_Cookie('isExtendedForm', '0', '365', '/', '', '');
	}
	// Если текущий поиск расширенный
	else {
		document.getElementById('RealtySearchFormExtendedText').style.display='inline';
		document.getElementById('RealtySearchFormExtendedLink').innerHTML ='<< Краткий';
		document.getElementById('RealtySearchFormExtendedCommonInfo').style.display='inline-block';
        var typeSel =  document.getElementById('TYPE_SELECT');
        if (document.getElementById('TYPE_SELECT').options[typeSel.selectedIndex].value!=5){
            document.getElementById('searchSubmit').style.visibility='hidden';
        }
		Set_Cookie('isExtendedForm', '1', '365', '/', '', '');
	}
}
// Изминение поиска Продажа/Аренда
function toggleCategoryRealtySearchForm(value) {
	Set_Cookie('searchCategory', value, '365', '/', '', '');
    setSerchType(value);    	
	
}

// Если нет фотки недвижимости
function NoPhotoRealtyList(img) {
	img.src = '/src/realtylist_nophoto.gif';
}
function NoPhotoRealtyBig(img) {
	//document.getElementById('ad_photos_table').style.display='none';
	//document.getElementById('tb_big_photo').style.display='none';
	// img.src = '/src/realtylist_nophoto_big.gif';
}

// Изменение режима отображения формы регистрации
function toggleRegisterForm(isAgency) {
	if (parseInt(isAgency) == 1) {
		document.getElementById('profileUserFeatures').style.display='none';
		document.getElementById('profileAgencyFeatures').style.display='inline';
		document.getElementById('profileAgencyStreet').style.display='inline';
		reg_isAgency = 1;
	}
	else {
		document.getElementById('profileUserFeatures').style.display='inline';
		document.getElementById('profileAgencyFeatures').style.display='none';
		document.getElementById('profileAgencyStreet').style.display='none';
		reg_isAgency = 0;
	}
}

// AJAX-поиск агенств
function agencySearch(city, region) {
	loadHTML('/ajax.php?mode=agencySearch&city='+city+'&region='+region, 'agencysContainer');
}

// AJAX-загрузка формы авторизации
function showAuthForm() {
	loadHTML('/ajax.php?mode=getAuthForm', 'main_content');
}
// AJAX-перезагрузка режима поиска для поиска
function toggleRealtyTypeSearch(type) {
	url = window.location.href;
	if (url.search('subscribe') != -1) {
		page = 'subscribe';
	}
	else {
		page = 'search';
	}
  /*  extendedFormCookie = Get_Cookie('isExtendedForm');
    // Если выбран краткий поиск
    if (extendedFormCookie == '1') {
     if (parseInt(type)!=1 && parseInt(type)!=3) {
        document.getElementById('NewBuildChecker').style.visibility='hidden';
    } else {
        document.getElementById('NewBuildChecker').style.visibility='visible';
    }
     if (parseInt(type)!=5) {
         document.getElementById('searchSubmit').style.visibility='hidden';
     } else {
        document.getElementById('searchSubmit').style.visibility='visible';
       
     }
    }*/
    //loadHTML('/ajax.php?mode=toggleRealtyTypeSearch&type='+type+'&page='+page, 'RealtySearchFormExtendedCommonInfo');
  
	loadHTML('/ajax.php?mode=toggleRealtyTypeSearchFullForm&type='+type+'&page='+page, 'main_content');
}

function toggleRealtyTypeSearch2(type,owner) {
    // modify owner style
    if (owner!=null) {
        var old=document.getElementById('active_ad_menu');
        old.id="";
        old.style.fontWeight="normal";
        old.style.color="#000";
        owner.id='active_ad_menu';
        owner.style.fontWeight="bold";
        owner.style.color="#FFF";
       
    }  
	url = window.location.href;
    if (url.search('/realty_search/')==-1){
	   if (url.search('subscribe') != -1) {
		   page = 'subscribe';
	    }
	    else {
		page = 'search';
	    }
	    loadHTML('/ajax.php?mode=toggleRealtyTypeSearchFullForm&type='+type+'&page='+page, 'main_content');
    } else {
     //  document.getElementById('TYPE_SELECT').selectedIndex=type-1;
    	toggleRealtyTypeSearch(type);
    }
}
// AJAX-перезагрузка режима поиска для добавления
function toggleRealtyTypeAdd(type) {
	loadHTML('/ajax.php?mode=toggleRealtyTypeAdd&type='+type, 'main_content');
}
// call when user change region value
function onRegionChange(region) {
    // alert(123);
    loadHTML('/ajax.php?mode=getDistrictsForRegion&region='+region, 'RealtyDistrictsContainer');
}
function onDistrictChange(district) {
    loadHTML('/ajax.php?mode=getSettlementsForDistrict&district='+district, 'RealtyCityesContainer');
}

function onCityChange(city) {
    loadHTML('/ajax.php?mode=getLabelForCity&city='+city, 'CITY_LABEL');
}
function onCityCapitalChange(city) {
    loadHTML('/ajax.php?mode=setAllGis&city='+city,'RealtyDistrictsContainer');
}
function getSettlementsForDistrictByRegSet(set_region) {
    loadHTML('/ajax.php?mode=getSettlementsForDistrictByRegSet&district='+set_region, 'RealtyDistrictsContainer');
}
// AJAX-перезагрузка списка регионов
function getCityesForRegion(region) {
	loadHTML('/ajax.php?mode=getCityesForRegion&region='+region, 'RealtyCityesContainer');
}
function getDistrictsForRegion(region) {
    loadHTML('/ajax.php?mode=getDistrictsForRegion&region='+region, 'RealtyCityesContainer');
    }
function getSettlementsForDistrict(district) {
    // alert(district);
    loadHTML('/ajax.php?mode=getSettlementsForDistrict&district='+district, 'RealtyDistrictsContainer');
}   
// AJAX-перезагрузка списка регионов
function getDistrictsForCity(city) {
	loadHTML('/ajax.php?mode=getDistrictsForCity&city='+city, 'RealtyDistrictsContainer');
}
// AJAX-добавление полей для фотографий при добавлении объявления
function getRealtyPhotoField(nextPhoto, photoContainer) {
	loadHTML('/ajax.php?mode=getRealtyPhotoField&nextPhoto='+nextPhoto, photoContainer);
}
// AJAX-редактирование профиля
function editProfile() {
	loadHTML('/ajax.php?mode=editProfile', 'main_content');
}
// AJAX-добавление в блокнот
function add_to_notepad(ad) {
	loadHTML('/ajax.php?mode=addToNotepad&ad='+ad, '');
}
// AJAX-удаление из блокнота
function remove_from_notepad(ad) {
	loadHTML('/ajax.php?mode=removeFromNotepad&ad='+ad, '');
}
// AJAX-работа с блокнотом
function notepadAddRemove(mode, realty_type, id, isFromNotepad) {
	if (mode == 'add') {
		loadHTML('/ajax.php?mode=notepadAdd&realty_type='+realty_type+'&id='+id, 'notepadControl'+id);
		document.getElementById('notepadAdsCount').innerHTML = parseInt(document.getElementById('notepadAdsCount').innerHTML) + 1;
	}
	else if (mode == 'remove') {
		if (isFromNotepad) {
			loadHTML('/ajax.php?mode=notepadRemove&realty_type='+realty_type+'&id='+id+'&isFromNotepad='+1, 'notepadElement'+id);
		}
		else {
			loadHTML('/ajax.php?mode=notepadRemove&realty_type='+realty_type+'&id='+id, 'notepadControl'+id);
		}
		document.getElementById('notepadAdsCount').innerHTML = parseInt(document.getElementById('notepadAdsCount').innerHTML) - 1;
	}
}
function setSerchType(id) {
    loadHTML('/ajax.php?mode=serchTypeEdit&id='+id, 'SERCH_TYPE_SELECT');
}
// AJAX-работа с рассылкой
function subscribeEdit(id) {
	loadHTML('/ajax.php?mode=subscribeEdit&id='+id, 'main_content');
}
function subscribeDelete(id) {
	loadHTML('/ajax.php?mode=subscribeDelete&id='+id, 'subscribeModule'+id);
}
function subscribeToggleDispatch(id, oldValue) {
	loadHTML('/ajax.php?mode=subscribeToggleDispatch&id='+id+'&oldValue='+oldValue, 'subscribeModuleStatus'+id);
}
// AJAX-работа с моими объявлениями
function adEdit(type, id) {
	loadHTML('/ajax.php?mode=adEdit&id='+id+'&type='+type, 'main_content');
}
function adDelete(type, id) {
	loadHTML('/ajax.php?mode=adDelete&id='+id+'&type='+type, 'adModule'+type+'|'+id);
}
function adRefresh(type, id) {
    alert(type);
	loadHTML('/ajax.php?mode=adRefresh&id='+id+'&type='+type, 'adRefresher'+id);
}
function adToProlong(type, id) {
    loadHTML('/ajax.php?mode=adToProlong&id='+id+'&type='+type, 'adProlonger'+id);
}
function DeletePhotoADV(type, id, photo) {
	loadHTML('/ajax.php?mode=DeletePhotoADV&id='+id+'&type='+type+'&photo='+photo, 'BLOCK_PHOTOS');
}

// Проверка форм регистрации и редактирования профайла
function checkRegisterForm(isEditProfile) {
	if (isEditProfile) {
		profile_type = parseInt(Get_Cookie('is_agency'));
	}
	else {
		profile_type = parseInt(reg_isAgency);
	}
	// Define regular expressions
	var emailRegEx = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
	var passwordRegEx = /^[A-Z0-9]{6,20}$/i;
	var phoneRegEx = /^\([0-9]{3}\)[0-9]{3}-[0-9]{2}-[0-9]{2}$/;
	// Check specefic fields for user registration
	if (profile_type == 0) {
		if (document.getElementById('USER_CONTACT_PERSON').value.length < 3) {
			document.getElementById('USER_CONTACT_PERSON').style.background = '#FFF699';
			errorContactPerson = true;
		}
		else {
			document.getElementById('USER_CONTACT_PERSON').style.background = '#FFFFFF';
			errorContactPerson = false;
		}
		if (document.getElementById('USER_PHONE').value.search(phoneRegEx) == -1) {
			document.getElementById('USER_PHONE').style.background = '#FFF699';
			errorPhone = true;
		}
		else {
			document.getElementById('USER_PHONE').style.background = '#FFFFFF';
			errorPhone = false;
		}
		if (errorContactPerson || errorPhone) {
			error = true;
		}
		else {
			document.getElementById('CONTACT_PERSON').value = document.getElementById('USER_CONTACT_PERSON').value;
			document.getElementById('PHONE').value = document.getElementById('USER_PHONE').value;
			error = false;
		}
	}
	// Check specefic fields for agency registration
	else if (profile_type == 1) {
		if (document.getElementById('COMPANY_CONTACT_PERSON').value.length < 3) {
			document.getElementById('COMPANY_CONTACT_PERSON').style.background = '#FFF699';
			errorContactPerson = true;
		}
		else {
			document.getElementById('COMPANY_CONTACT_PERSON').style.background = '#FFFFFF';
			errorContactPerson = false;
		}
		if (document.getElementById('COMPANY_PHONE').value.search(phoneRegEx) == -1) {
			document.getElementById('COMPANY_PHONE').style.background = '#FFF699';
			errorPhone = true;
		}
		else {
			document.getElementById('COMPANY_PHONE').style.background = '#FFFFFF';
			errorPhone = false;
		}
		if (document.getElementById('COMPANY_NAME').value.length < 3) {
			document.getElementById('COMPANY_NAME').style.background = '#FFF699';
			errorCompanyName = true;
		}
		else {
			document.getElementById('COMPANY_NAME').style.background = '#FFFFFF';
			errorCompanyName = false;
		}
		if (document.getElementById('COMPANY_INFORMATION').value.length < 10) {
			document.getElementById('COMPANY_INFORMATION').style.background = '#FFF699';
			errorCompanyInformation = true;
		}
		else {
			document.getElementById('COMPANY_INFORMATION').style.background = '#FFFFFF';
			errorCompanyInformation = false;
		}
		if (errorContactPerson || errorPhone || errorCompanyName || errorCompanyInformation) {
			error = true;
		}
		else {
			document.getElementById('CONTACT_PERSON').value = document.getElementById('COMPANY_CONTACT_PERSON').value;
			document.getElementById('PHONE').value = document.getElementById('COMPANY_PHONE').value;
			error = false;
		}
	}
	// Check EMAIL field
	if (document.getElementById('EMAIL').value.search(emailRegEx) == -1) {
		document.getElementById('EMAIL').style.background = '#FFF699';
		errorEmail = true;
	}
	else {
		document.getElementById('EMAIL').style.background = '#FFFFFF';
		errorEmail = false;
	}
	// Separated checking for add and edit
	if (isEditProfile) {
		// Check PASSWORD_OLD field
		authkey = Base64.decode(Get_Cookie('authkey'));
		password = authkey.substr(authkey.length-32);
		if (document.getElementById('PASSWORD_OLD')) {
		if (hex_md5(document.getElementById('PASSWORD_OLD').value) != password &&
			document.getElementById('PASSWORD_OLD').value.length != 0) {
			document.getElementById('PASSWORD_OLD').style.background = '#FFF699';
			errorPasswordOld = true;
		}
		else {
		   if (document.getElementById('PASSWORD_OLD')) {
		      document.getElementById('PASSWORD_OLD').style.background = '#FFFFFF';
			  errorPasswordOld = false;
			}
		 }
		}
		// Check PASSWORD field
		if ((document.getElementById('PASSWORD').value != document.getElementById('PASSWORD_RETYPE').value ||
			document.getElementById('PASSWORD').value.search(passwordRegEx) == -1) &&
			(document.getElementById('PASSWORD').value.length != 0 || errorPasswordOld)) {
			document.getElementById('PASSWORD').style.background = '#FFF699';
			document.getElementById('PASSWORD_RETYPE').style.background = '#FFF699';
			errorPassword = true;
		}
		else {
			document.getElementById('PASSWORD').style.background = '#FFFFFF';
			document.getElementById('PASSWORD_RETYPE').style.background = '#FFFFFF';
			errorPassword = false;
		}
	}
	else {
		// Check PASSWORD field 
		if (document.getElementById('PASSWORD').value != document.getElementById('PASSWORD_RETYPE').value ||
			document.getElementById('PASSWORD').value.search(passwordRegEx) == -1) {
			document.getElementById('PASSWORD').style.background = '#FFF699';
			document.getElementById('PASSWORD_RETYPE').style.background = '#FFF699';
			errorPassword = true;
		}
		else {
			document.getElementById('PASSWORD').style.background = '#FFFFFF';
			document.getElementById('PASSWORD_RETYPE').style.background = '#FFFFFF';
			errorPassword = false;
		}
	}
	// Check DISTRICT field
	if (parseInt(document.getElementById('DISTRICT').value) == 0) {
		document.getElementById('DISTRICT').style.background = '#FFF699';
		errorCity = true;
	}
	else {
		document.getElementById('DISTRICT').style.background = '#FFFFFF';
		errorCity = false;
	}
	// Check SETTLEMENT field
	if (document.getElementById('SETTLEMENT')){
	 if (parseInt(document.getElementById('SETTLEMENT').value)==0) {
	     document.getElementById('SETTLEMENT').style.background = '#FFF699';
	     errorSett = true;
	 } else {
	    document.getElementById('SETTLEMENT').style.background = '#FFF';
	    errrorSett= false;
	
	 }
	}
	// Check captcha
	if (document.getElementById('CAPTCHA').value.length != 5) {
		document.getElementById('CAPTCHA').style.background = '#FFF699';
		errorCaptcha = true;
	}
	else {
		document.getElementById('CAPTCHA').style.background = '#FFFFFF';
		errorCaptcha = false;
	}
	// Return FALSE if some errors
	if (error || errorEmail || errorPasswordOld || errorPassword || errorCity || errorCaptcha) {
		if (document.getElementById('successMessageBox')) {
			document.getElementById('successMessageBox').style.display = 'none';
		}
		document.getElementById('embeddedError').innerHTML = '&nbsp;&nbsp;* Не все поля были заполнены';
		document.getElementById('errorMessageBox').style.display = 'block';
		document.getElementById('embeddedError').style.display = 'block';
		return false;
	}
	// Separated return TRUE for add and edit
	if (isEditProfile) {
		return AIM.submit(document.edit_profile_form, {'onStart' : startCallbackEditProfile, 'onComplete' : completeCallbackEditProfile});
	}
	else {
		return true;
	}
}

// AJAX-like редактирование профайла
function startCallbackEditProfile() {
	// make something useful before submit (onStart)
	return true;
}
function completeCallbackEditProfile(response) {
	// make something useful after (onComplete)
	document.getElementById('main_content').innerHTML = response;
	if (Get_Cookie('authkey') == null) {
		document.getElementById('personal_area').innerHTML = '';
		document.getElementById('personal_area').style.display = 'none';
		document.getElementById('enter_reister_links').innerHTML = 'Пройдите процедуру авторизации!';
	}
}

// Проверка формы добавления недвижимости
function checkAddRealtyForm(type) {
	var error = true;
	switch(type) {
		case 1:
			if (isNaN(document.getElementById('ROOMS_COUNT').value) || document.getElementById('ROOMS_COUNT').value == '') {
				document.getElementById('ROOMS_COUNT').style.background = '#FFF699';
				errorRooms = true;
			}
			else {
				document.getElementById('ROOMS_COUNT').style.background = '#FFFFFF';
				errorRooms = false;
			}
			if (isNaN(document.getElementById('AREA').value) || document.getElementById('AREA').value == '') {
				document.getElementById('AREA').style.background = '#FFF699';
				errorArea = true;
			}
			else {
				document.getElementById('AREA').style.background = '#FFFFFF';
				errorArea = false;
			}
			if (isNaN(document.getElementById('FLOOR').value) || document.getElementById('FLOOR').value == '') {
				document.getElementById('FLOOR').style.background = '#FFF699';
				errorFloor = true;
			}
			else {
				document.getElementById('FLOOR').style.background = '#FFFFFF';
				errorFloor = false;
			}
			if (errorRooms || errorArea || errorFloor) {
				error = true;
			}
			else {
				error = false;
			}
			break;
		case 2:
			if (isNaN(document.getElementById('ROOMS_COUNT').value) || document.getElementById('ROOMS_COUNT').value == '') {
				document.getElementById('ROOMS_COUNT').style.background = '#FFF699';
				errorRooms = true;
			}
			else {
				document.getElementById('ROOMS_COUNT').style.background = '#FFFFFF';
				errorRooms = false;
			}
			if (isNaN(document.getElementById('AREA').value) || document.getElementById('AREA').value == '') {
				document.getElementById('AREA').style.background = '#FFF699';
				errorArea = true;
			}
			else {
				document.getElementById('AREA').style.background = '#FFFFFF';
				errorArea = false;
			}
			if (errorRooms || errorArea) {
				error = true;
			}
			else {
				error = false;
			}
			break;
		case 3:
		  
			if (isNaN(document.getElementById('AREA').value) || document.getElementById('AREA').value == '') {
				document.getElementById('AREA').style.background = '#FFF699';
				errorArea = true;
			}
			else {
				document.getElementById('AREA').style.background = '#FFFFFF';
				errorArea = false;
			}
			if (errorArea) {
				error = true;
			}
			else {
				error = false;
			}
			break;
		case 4:
			if (isNaN(document.getElementById('AREA').value) || document.getElementById('AREA').value == '') {
				document.getElementById('AREA').style.background = '#FFF699';
				errorArea = true;
			}
			else {
				document.getElementById('AREA').style.background = '#FFFFFF';
				errorArea = false;
			}
			if (errorArea) {
				error = true;
			}
			else {
				error = false;
			}
		case 5:
		    error=false;
			break;
	}
	if(!checkAddRealtyFormCommon() || error) {
		document.getElementById('embeddedError').innerHTML = '&nbsp;&nbsp;* Не все поля были заполнены';
		document.getElementById('errorMessageBox').style.display = 'block';
		document.getElementById('embeddedError').style.display = 'block';		
		return false;
	}
	else {	   
		document.forms['realty_add_form'].submit();
		
	}
}
// Проверка общих данных формы добавления недвижимости
function checkAddRealtyFormCommon() {
	if (isNaN(document.getElementById('PRICE').value) || document.getElementById('PRICE').value == '') {
		document.getElementById('PRICE').style.background = '#FFF699';
		errorPrice = true;
	}
	else {
		document.getElementById('PRICE').style.background = '#FFFFFF';
		errorPrice = false;
	}
	if (document.getElementById('DISTRICT').value == '0') {
		document.getElementById('DISTRICT').style.background = '#FFF699';
		errorSett = true;
	}
	else {
		document.getElementById('DISTRICT').style.background = '#FFFFFF';
		errorSett = false;
	}
	if (document.getElementById('DESCRIPTION').value== '') {
	    document.getElementById('DESCRIPTION').style.background = '#FFF699';
	} else {
	   document.getElementById('DESCRIPTION').style.background ='#FFF';
	   errorDescription = false;
	}
	/*
	 * if (document.getElementById('CURRENCY').value == '-1') {
	 * document.getElementById('CURRENCY').style.background = '#FFF699';
	 * errorCurrency = true; } else {
	 * document.getElementById('CURRENCY').style.background = '#FFFFFF';
	 * errorCurrency = false; }
	 */
	if (errorPrice || errorSett || errorDescription) {
		return false;
		
	}
	else {
		return true;
	}
}

// AJAX-работа с отправкой жалоб и рекомендаций
function adComplain(type, id) {
	loadHTML('/ajax.php?mode=adComplain&type='+type+'&id='+id, 'popup');
}
function adSendToFriend(type, id) {
	loadHTML('/ajax.php?mode=adSendToFriend&type='+type+'&id='+id, 'popup');
}
function sendEmail() {
	loadHTML('/ajax.php?mode=sendEmail&type='+document.getElementById('TYPE').value+
			'&id='+document.getElementById('ID').value+
			'&email='+document.getElementById('EMAIL').value+
			'&comments='+document.getElementById('COMMENTS').value+
			'&captcha='+document.getElementById('CAPTCHA').value+
			'&typeOfMail='+document.getElementById('MODE').value,
			'sendEmailControl'+document.getElementById('MODE').value);
	closePopup('sendEmailPopup');
}

function orderAds(type) {
	loadHTML('/etc/modules/order.php?action=1&type='+type, 'popup');
}

// Прелоадер
function preload() {
	correctPNG();
}




// NEW LIFE---------------------------------------------------------------------

function check_required(f){
if(required){
  var fon_error   = '#FFDAB9';  // error
  var fon_default = '';         // default
  var i, j;
  for(j=0; j<required.length; j++) {
      for (i=0; i<f.length; i++) {
          f.elements[i].style.backgroundColor = fon_default;
          if (f.elements[i].name == required[j] && !f.elements[i].value ) {
              // alert('Пожалуйста, введите ' + required_show[j]);
              f.elements[i].focus();
              f.elements[i].style.backgroundColor = fon_error;
              return false;
          }
      }
  }
}
return true;
}





/*
 * Создание XMLHttpRequest-объекта Возвращает созданный объект или null, если
 * XMLHttpRequest не поддерживается
 */
function createRequestObject() {
    var request = null;
    try {
        request=new ActiveXObject('Msxml2.XMLHTTP');
    } catch (e){}
    if(!request) try {
        request=new ActiveXObject('Microsoft.XMLHTTP');
    } catch (e){}
    if(!request) try {
        request=new XMLHttpRequest();
    } catch (e){}
    return request;
}

/*
 * Кодирование данных (простого ассоциативного массива вида { name : value, ...}
 * в URL-escaped строку (кодировка UTF-8)
 */
function urlEncodeData(data) {
    var query = [];
    if (data instanceof Object) {
        for (var k in data) {
            query.push(encodeURIComponent(k) + "=" +
            		encodeURIComponent(data[k]));
        }
        return query.join('&');
    } else {
        return encodeURIComponent(data);
    }
}

/*
 * Выполнение POST-запроса url - адрес запроса data - параметры в виде простого
 * ассоциативного массива { name : value, ...} callback - (не обяз.)
 * callback-функция, которая будет вызвана после выполнения запроса и получения
 * ответа от сервера
 */
function serverRequest(url, data, callback) {
    var request = createRequestObject();
    if(!request) return false;
    request.onreadystatechange  = function() { 
            if(request.readyState == 4 && request.status==200 && callback) callback(request.responseText);
        };
    request.open('POST', url, true);
    var params = urlEncodeData(data);
    // if (request.setRequestHeader)
        request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        request.setRequestHeader("Content-length", params.length);
				request.setRequestHeader("Connection", "close");
    request.send(params);
    // request.send(urlEncodeData(data));
    return true;
}
