window.reEmail = /^([\w\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/i;
window.uploadedPhotos = [0, 0, 0];

function wizardSelectCategory() {
	var oBlockRegions      = $('wizardRegions');
	var oBlockDetails      = $('wizardDetails');
	var oBlockDetailsEmail = $('wizardDetailsEmail');
	var oBlockDetailsPhoto = $('wizardDetailsPhoto');
	var oBlockDetailsMore  = $('wizardDetailsMore');

	var oBlockRegionsTitle      = $('wizardRegionsTitle');
	var oBlockDetailsTitle      = $('wizardDetailsTitle');
	var oBlockDetailsEmailTitle = $('wizardDetailsEmailTitle');

	var oBlockContactInfo       = $('wizardContactInfo');
	var oBlockContactInfoTitle       = $('wizardContactInfoTitle');
	var oBlockContactInfoSubmit = $('wizardContactInfoSubmit');

	if (oBlockRegions) {
        oBlockRegions.style.display = 'none';
    }

	if (oBlockDetails) {
        oBlockDetails.style.display = 'none';
    }

    if (oBlockDetailsEmail) {
        oBlockDetailsEmail.style.display = 'none';
    }

    if (oBlockDetailsPhoto) {
        oBlockDetailsPhoto.style.display = 'none';
    }

    if (oBlockContactInfo) {
        oBlockContactInfo.style.display = 'none';
    }

    if (oBlockContactInfoTitle) {
        oBlockContactInfoTitle.style.display = 'none';
    }

    if (oBlockContactInfoSubmit) {
        oBlockContactInfoSubmit.style.display = 'none';
    }

    if (oBlockRegionsTitle) {
        oBlockRegionsTitle.style.display = 'none';
    }

    if (oBlockDetailsTitle) {
        oBlockDetailsTitle.style.display = 'none';
    }

    if (oBlockDetailsEmailTitle) {
        oBlockDetailsEmailTitle.style.display = 'none';
    }

    if (oBlockDetailsMore) {
        oBlockDetailsMore.style.display = 'none';
    }

    selectWizard(1);
}

function wizardDetails() {
	var oBlockRegions      = $('wizardRegions');
	var oBlockDetails      = $('wizardDetails');
	var oBlockDetailsEmail = $('wizardDetailsEmail');
	var oBlockDetailsPhoto = $('wizardDetailsPhoto');
	var oBlockDetailsMore  = $('wizardDetailsMore');

	var oBlockRegionsTitle      = $('wizardRegionsTitle');
	var oBlockDetailsTitle      = $('wizardDetailsTitle');
	var oBlockDetailsEmailTitle = $('wizardDetailsEmailTitle');

	var oBlockContactInfo       = $('wizardContactInfo');
	var oBlockContactInfoTitle       = $('wizardContactInfoTitle');
	var oBlockContactInfoSubmit = $('wizardContactInfoSubmit');

	if (oBlockRegions) {
        oBlockRegions.style.display = '';
    }

	if (oBlockRegionsTitle) {
        oBlockRegionsTitle.style.display = '';
    }

	if (oBlockDetailsTitle) {
        oBlockDetailsTitle.style.display = '';
    }

	if (oBlockDetails) {
        oBlockDetails.style.display = '';
    }

	if (oBlockDetailsEmail) {
        oBlockDetailsEmail.style.display = '';
    }

	if (oBlockDetailsEmailTitle) {
        oBlockDetailsEmailTitle.style.display = '';
    }

	if (oBlockDetailsPhoto) {
        oBlockDetailsPhoto.style.display = '';
    }

	if (oBlockDetailsMore) {
        oBlockDetailsMore.style.display = '';
    }

	if (oBlockContactInfo) {
        oBlockContactInfo.style.display = 'none';
    }

	if (oBlockContactInfoTitle) {
        oBlockContactInfoTitle.style.display = 'none';
    }

	if (oBlockContactInfoSubmit) {
        oBlockContactInfoSubmit.style.display = 'none';
    }

	if ($('detailsPasswordBlock')) {
        $('detailsPasswordBlock').style.display = 'none';
    }

	if ($('details-email-block')) {
        $('details-email-block').style.display = '';
    }

	if ($('detailsPassword')) {
        $('detailsPassword').value = '';
    }

	selectWizard(2);
}

function saveSession(callback) {
	var el;
	var i = 0;
	var params = 'add-parent_id=' + $('add-category').value + '&add-region_id=' + $('add-region').value;

	for (i = 0; i < 3; i ++) {
		if (uploadedPhotos[i] == 1 && $('ad-caption-' + (i + 1))) {
			params += '&add-captions[]=' + $('ad-caption-' + (i + 1)).value;
		}
	}

	for (i = 0, n = fields.length; i < n; i ++) {
		el = $('add-' + fields[i]);

		if (!el) {
            el = $('add-' + fields[i] + '-id');
        }

		if (el.tagName == 'INPUT' && el.type == 'checkbox') {
            params += '&add-' + fields[i] + '=' + ((el.checked) ? 1 : 0);
        } else {
            params += '&add-' + fields[i] + '=' + encodeURIComponent(el.value);
        }
	}
	new Ajax.Request('/plugins/ajax/save_session.php', {
		parameters : params,
        onSuccess : function(transport, json) {
            if (callback) {
                callback();
            }
        }
    });
}

function wizardContactInfo() {
	var  oEmail = $('emailDetails');
	var oPassword = $('detailsPassword');

	if($('add-region').value==567){
    	alert('Выберите регион');
    	return false;
    }

	var requiredFields = new Array();
    if (necessaryFields && necessaryFields.length) {
        for (var i = 0, n = necessaryFields.length; i < n; i ++) {
            if ($('add-' + necessaryFields[i].name).value.replace(/\s/, '').length == 0 ||
            	!$('add-' + necessaryFields[i].name).value.replace(/\s/, '').length ||
            	($('add-' + necessaryFields[i].name).value == 0 && necessaryFields[i].name != 'mileage')) {
            	requiredFields.push(necessaryFields[i].caption);
            }
        }
    }

    if (requiredFields.length > 0) {
    	alert('Заполните обязательные поля:\n\n- ' + requiredFields.join('\n- '));
    	return false;
    }


	if (!reEmail.test(oEmail.value)) {
		alert('Укажите корректный email');
		return false;
	}
	saveSession();


	if (oPassword && oPassword.value.replace(/\s/, '').length > 0) {
		//Logging user throught AJAX or registering new user. Step 2 - password
		new Ajax.Request('/plugins/ajax/check_user.php', {
			parameters : 'login=' + oEmail.value + '&password=' + oPassword.value,
			onSuccess  : function(transport, json) {
				if (json.success) {
					$('wizardContactInfoEmailBlock').style.display = 'none';
					if ($('contactAuthBlock')) {
                        $('contactAuthBlock').style.display = 'none';
                    }

					var oBlockRegions      = $('wizardRegions');
					var oBlockDetails      = $('wizardDetails');
					var oBlockDetailsEmail = $('wizardDetailsEmail');
					var oBlockDetailsPhoto = $('wizardDetailsPhoto');
					var oBlockDetailsMore  = $('wizardDetailsMore');

					var oBlockContactInfo       = $('wizardContactInfo');

					var oBlockRegionsTitle      = $('wizardRegionsTitle');
					var oBlockDetailsTitle      = $('wizardDetailsTitle');
					var oBlockDetailsEmailTitle = $('wizardDetailsEmailTitle');
					var oBlockContactInfoTitle       = $('wizardContactInfoTitle');

					var oBlockContactInfoSubmit = $('wizardContactInfoSubmit');

					if (oBlockRegions)
					{
                        oBlockRegions.style.display = '';
                    }

					if (oBlockRegionsTitle)
					{
                        oBlockRegionsTitle.style.display = '';
                    }

					if (oBlockDetails)
					{
                        oBlockDetails.style.display = '';
                    }

					if (oBlockDetailsTitle)
					{
                        oBlockDetailsTitle.style.display = '';
                    }

					if (oBlockDetailsPhoto)
					{
                        oBlockDetailsPhoto.style.display = '';
                    }

					if (oBlockDetailsEmail)
					{
                        oBlockDetailsEmail.style.display = 'none';
                    }

					if (oBlockDetailsEmailTitle)
					{
                        oBlockDetailsEmailTitle.style.display = 'none';
                    }

					if (oBlockDetailsMore)
					{
                        oBlockDetailsMore.style.display = 'none';
                    }

					if (/*json.ispp==0*/ 0){
						if (oBlockContactInfo)
						{
                            oBlockContactInfo.style.display = '';
                        }

						if (oBlockContactInfoTitle)
						{
                            oBlockContactInfoTitle.style.display = '';
                        }

					}

					if (oBlockContactInfoSubmit)
					{
                        oBlockContactInfoSubmit.style.display = '';
                    }

					$('contactFirstName').value = json.userdata.first_name;
					//$('contactLastName').value = json.userdata.last_name;
					$('contactPhone').value = json.userdata.phone;
					$('contactMobile').value = json.userdata.mobile;
					$('contactICQ').value = json.userdata.icq;
					$('contactDay').value = json.userdata.dob_day;
					$('contactYear').value = json.userdata.dob_year;
					$('contactMonth').selectedIndex = json.userdata.dob_month - 1;
					$('contactCity').value = json.userdata.city;
					$('contactStreet').value = json.userdata.street;
					//$('contactBuilding').value = json.userdata.building;
					//$('contactZIP').value = json.userdata.zip;
					//$('contactFax').value = json.userdata.fax;
					$('contactSite').value = json.userdata.site;

					selectWizard(3);
					sendAd();
				}
				else {
					alert('Неверный пароль');
				}
			}
		});
	} else if (oEmail.type == 'text') {
    	//Logging user throught AJAX. Step 1 - checking E-mail
		new Ajax.Request('/plugins/ajax/check_user.php', {
			parameters : 'login=' + oEmail.value,
			onSuccess  : function(transport, json) {
				if (json.success==1) {
					var oBlockDetailsPassword = $('detailsPasswordBlock');
					if (oBlockDetailsPassword) {
						oBlockDetailsPassword.style.display = '';
						$('details-email-block').style.display = 'none';
						$('details-email-span').innerHTML = oEmail.value;
					}
				}else if (json.success==2){
					alert('Аккаунт заблокирован');
				} else if( json.success==4 ) {
					alert( "Истек срок оплаты услуги Интернет-партнер. Продлите оплату размещения на сайте, чтобы подавать новые объявления. За более подробной информацией обращайтесь в службу поддержки по адресу support@trucklist.ru" );
				} else {
					if ($('contactEmail')) {
						$('contactEmail').value = oEmail.value;
						$('wizardContactInfoEmail').innerHTML = oEmail.value;
						$('wizardContactInfoShowEmailBlock').style.display = '';
						$('wizardContactInfoEmailBlock').style.display = 'none';
					}

					var oBlockRegions      = $('wizardRegions');
					var oBlockDetails      = $('wizardDetails');
					var oBlockDetailsEmail = $('wizardDetailsEmail');
					var oBlockDetailsPhoto = $('wizardDetailsPhoto');
					var oBlockDetailsMore  = $('wizardDetailsMore');
					var oBlockContactInfo       = $('wizardContactInfo');

					var oBlockRegionsTitle      = $('wizardRegionsTitle');
					var oBlockDetailsTitle      = $('wizardDetailsTitle');
					var oBlockDetailsEmailTitle = $('wizardDetailsEmailTitle');
					var oBlockContactInfoTitle       = $('wizardContactInfoTitle');
					var oBlockContactInfoSubmit = $('wizardContactInfoSubmit');

					if (oBlockRegions)
					{
                        oBlockRegions.style.display = '';
                    }

					if (oBlockRegionsTitle)
					{
                        oBlockRegionsTitle.style.display = '';
                    }

					if (oBlockDetails)
					{
                        oBlockDetails.style.display = '';
                    }

					if (oBlockDetailsTitle)
					{
                        oBlockDetailsTitle.style.display = '';
                    }

					if (oBlockDetailsPhoto)
					{
                        oBlockDetailsPhoto.style.display = '';
                    }

					if (oBlockDetailsEmail)
					{
                        oBlockDetailsEmail.style.display = 'none';
                    }

					if (oBlockDetailsEmailTitle)
					{
                        oBlockDetailsEmailTitle.style.display = 'none';
                    }

					if (oBlockDetailsMore)
					{
                        oBlockDetailsMore.style.display = 'none';
                    }

					if (oBlockContactInfo)
					{
                        oBlockContactInfo.style.display = '';
                    }

					if (oBlockContactInfoTitle)
					{
                        oBlockContactInfoTitle.style.display = '';
                    }

					if (oBlockContactInfoSubmit)
					{
                        oBlockContactInfoSubmit.style.display = '';
                    }

					selectWizard(3);
				}
			}
		});
	} else {
		//User is already logged in
		if ($('contactEmail')) {
			$('contactEmail').value = oEmail.value;
			$('wizardContactInfoEmail').innerHTML = oEmail.value;
			$('wizardContactInfoShowEmailBlock').style.display = '';
			$('wizardContactInfoEmailBlock').style.display = 'none';
		}

		var oBlockDetailsEmail = $('wizardDetailsEmail');
		var oBlockDetailsMore  = $('wizardDetailsMore');

		var oBlockContactInfo       = $('wizardContactInfo');

		var oBlockDetailsEmailTitle = $('wizardDetailsEmailTitle');

		if (oBlockDetailsEmail)
		{
            oBlockDetailsEmail.style.display = 'none';
        }

		if (oBlockDetailsEmailTitle)
		{
            oBlockDetailsEmailTitle.style.display = 'none';
        }

		if (oBlockDetailsMore)
		{
            oBlockDetailsMore.style.display = 'none';
        }

		if (oBlockContactInfo)
		{
            oBlockContactInfo.style.display = 'none';
        }

		sendAd();
	}

}

function selectWizard(item) {

	var oWizard = $('wizardMenu');
	var els = oWizard.getElementsByTagName('LI');
	var spans = {};
    var j, jLength;

	if (!item) {
        item = 1;
    }

	for (var i = 0, n = els.length; i < n; i ++) {
		els[i].className = (i == 0) ? 'first' : '';
		spans = els[i].getElementsByTagName('SPAN');
		for (j = 0, jLength = spans.length; j < jLength; ++ j) {
			spans[j].className = spans[j].className.replace(/w-/, 'stp-');
		}
	}

	spans = els[item - 1].getElementsByTagName('SPAN');
	for (j = 0, jLength = spans.length; j < jLength; ++ j) {
		spans[j].className = spans[j].className.replace(/stp-/, 'w-');
	}

	els[item - 1].className = ((item == 1) ? 'first ' : '') + 'selected';
}

function updateCategories(aCategories) {
	var oCategories = $('oCategories');
	var el = document.createElement('OPTION');

	oCategories.innerHTML = '';

	el.value = '0';
	el.selected = true;
	el.appendChild(document.createTextNode('Выберите раздел'));

	oCategories.appendChild(el);

	for (var i = 0, n = aCategories.length; i < n; i ++) {
		el = document.createElement('OPTION');
		el.value = aCategories[i].unified_id;
		el.appendChild(document.createTextNode(aCategories[i].item_name));
		oCategories.appendChild(el);
	}
}

function replaceAnchorBySelect(_this) {
	wizardSelectCategory();

	var message = $('waitMessage');
	var oCategories = $('oCategories');
	var parentNode = _this.parentNode;
	var el = {};
	while (el = _this.nextSibling) {
        parentNode.removeChild(el);
    }

	new Ajax.Request('/plugins/ajax/categories.php', {
		parameters  : 'parent=' + _this.getAttribute('parent'),
		onCreate    : function() { message.style.display = '';     },
		onComplete  : function() { message.style.display = 'none'; },
		onSuccess   : function(transport, json) { updateCategories(json.categories); }
	});

	parentNode.removeChild(_this);
	oCategories.style.display = '';

	return false;
}

function getCategories(nParent) {
	var oCategories = $('oCategories');
	$('link-first-step').focus();

	if (nParent == 0) {
        return false;
    }

	new Ajax.Request('/plugins/ajax/categories.php', {
		parameters  : 'parent=' + nParent,
		onCreate    : function() { $('waitMessage').style.display = '';     },
		onComplete  : function() { $('waitMessage').style.display = 'none'; },
		onSuccess   : function(transport, json) {
			if (200 == transport.status) {
				var oCategories = $('oCategories');
				$('link-first-step').focus();
				var oCategoriesNavigation = $('categoriesNavigation');
				var el = document.createElement('A');

				el.href = '/add/data/site/' + nParent + '/';
				el.setAttribute('parent', json.item);
				el.onclick = function() { replaceAnchorBySelect(this); return false; }
				el.appendChild(document.createTextNode(oCategories.options[oCategories.selectedIndex].innerHTML));

				oCategoriesNavigation.appendChild(el);

				el = document.createTextNode(' ');
				oCategoriesNavigation.appendChild(el);

				if (json.categories.length > 0) {
					el = document.createElement('IMG');
					el.src = '/webroot/delivery/pic/ar6.gif';
					el.alt = '&raquo;';
					el.width  = 5;
					el.height = 5;

					oCategoriesNavigation.appendChild(el);

					el = document.createTextNode(' ');
					oCategoriesNavigation.appendChild(el);

					updateCategories(json.categories);
				} else {
					oCategories.style.display = 'none';
					document.location = '/add/data/site/' + nParent + '/';
					$('waitMessage').style.display = '';
					return true;
				}
			}
		}
	});
}

function updateEmail(el) {
	$('wizardContactInfoEmail').innerHTML = el.value;
	toggle('wizardContactInfoEmailBlock');
	toggle('wizardContactInfoShowEmailBlock');
}

function removePhoto(i)
{
	var block = $('downloaded-photo-' + i);
	var src = block.getElementsByTagName('IMG')[0].src;
	var parentNode = block.parentNode;

	parentNode.removeChild(block);

	var node, link, label, input;
	var childs = parentNode.getElementsByTagName('TD');

	window.uploadedPhotos = [0, 0, 0];

	for (var i = 1, length = childs.length; i < length; ++ i) {
		node  = childs[i];
		link  = node.getElementsByTagName('A')[0];
		label = node.getElementsByTagName('LABEL')[0];
		input = node.getElementsByTagName('INPUT')[0];

		node.id = 'downloaded-photo-' + i;

		label.setAttribute('for', 'ad-caption-' + i);
		input.id = 'ad-caption-' + i;
		link.setAttribute('imageid', i - 1);


		window.uploadedPhotos[i - 1] = 1;
	}

	new Ajax.Request('/plugins/ajax/remove_photo.php', {
		parameters : 'photo=' + src + '&id=' + i,
		onComplete : function() {
			$('downloaded-photo-form').style.display = '';
		}
	});

	return false;
}

function uploadPhoto(src, width, height) {
	var inp = $('input-file-upload');
	if (inp) {
		var parentNode = inp.parentNode;
		if (parent) {
			parentNode.removeChild(inp);
			inp = document.createElement('INPUT');
			inp.type = 'file';
			inp.name = 'photo';
			inp.id   = 'input-file-upload';
			inp.size = 16;
			parentNode.appendChild(inp);
		}
	}

	var i = 0;

	if (window.uploadedPhotos[0] == 0) {
		i = 0;
	} else if (window.uploadedPhotos[1] == 0) {
		i = 1;
	} else if (window.uploadedPhotos[2] == 0) {
		i = 2;
	} else {
		return false;
	}

	window.uploadedPhotos[i] = 1;

	var origin 	= $('downloaded-photo-');
	var node 	= origin.cloneNode(true);
	var img 	= node.getElementsByTagName('IMG')[0];
	var link 	= node.getElementsByTagName('A')[0];
	var label 	= node.getElementsByTagName('LABEL')[0];
	var input  	= node.getElementsByTagName('INPUT')[0];

	node.id += (i + 1);

	link.setAttribute('imageid', i);

	img.src 	= src;
	img.width 	= width;
	img.height 	= height;

	label.setAttribute('for', (i + 1));
	input.id += (i + 1);

	link.onclick = function()
	{
		var i = this.getAttribute('imageid');
		i = parseInt(i);
		removePhoto(i + 1);
		return false;
	}

	origin.parentNode.appendChild(node);
	node.style.display = '';

	if (window.uploadedPhotos[0] == 1 && window.uploadedPhotos[1] == 1 && window.uploadedPhotos[2] == 1) {
        $('downloaded-photo-form').style.display = 'none';
    }
}

function lockSendButton(){
	$('wizardContactInfoSubmit').style.display="none";
	$('wizardContactInfoSubmit').style.visibility="hidden";
	$('wizardContactInfoSubmitWait').style.display="block";
}


function unLockSendButton(){
	$('wizardContactInfoSubmitWait').style.display="none";
	$('wizardContactInfoSubmit').style.visibility="visible";
	$('wizardContactInfoSubmit').style.display="block";
}

function sendAd() {
    var params = '';
    var oEmail = $('contactEmail');
    var oAgree = $('contactAgree');
    var oName = $('contactFirstName');
    lockSendButton();

    if ($('add-region').value == 567) {
        alert('Выберите регион');
        unLockSendButton();
        return false;
    }

    regFloat = /^[0-9]*[\.\,]{0,1}[0-9]*$/i;
    regInteger = /^[0-9]*$/i;
    errorfields = 'Ввведите корректные данные в поля:';
    error = false;

    var i;

    for (i = 0; i < fields.length; i++)
    {
        elem = $('add-' + fields[i]);
        if (!elem) {
            elem = $('add-' + fields[i] + '-id');
        }

        switch (elem.readAttribute('filter'))
        {
            case "filterFloat":
                if (regFloat.test(elem.value) == false) {
                    errorfields = errorfields + '\n- ' + elem.readAttribute('title');
                    error = true;
                }
                break;
            case "filterInteger":
                if (regInteger.test(elem.value) == false) {
                    errorfields = errorfields + '\n- ' + elem.readAttribute('title');
                    error = true;
                }
                break;
        }
    }
    if (error) {
        alert(errorfields);
        unLockSendButton();
        return false;
    }
    var requiredFields = new Array();
    if (necessaryFields && necessaryFields.length) {

        for (i = 0, n = necessaryFields.length; i < n; i ++) {

            elem = $('add-' + necessaryFields[i].name);
            if (!elem) {
                elem = $('add-' + necessaryFields[i].name + '-id');
            }

            if (elem.value.replace(/\s/, '').length == 0 ||
                !elem.value.replace(/\s/, '').length ||
                (elem.value == 0 && necessaryFields[i].name != 'mileage')) {
                requiredFields.push(necessaryFields[i].caption);
            }
        }
    }

    if (requiredFields.length > 0) {
        alert('Заполните обязательные поля:\n\n- ' + requiredFields.join('\n- '));
        unLockSendButton();
        return false;
    }


    var addText = $('add-text').value;
    if (addText.length > 32) {
        var arrayText = addText.split(/\s+/);
        for (i = 0; i < arrayText.length; i++) {
            if (arrayText[ i ].length >= 32) {
                alert('Ваш текст содержит слишком мало пробельных символов');
                unLockSendButton();
                return false;
            }
        }
    }

    if (!oAgree.checked) {
        alert('Для подачи объявления вы должны согласится с нашими условиями');
        unLockSendButton();
        return false;
    }

    var parentID = $('add-category');

    if (($('contactAuthBlock')) && $('contactAuthBlock').style.display == '') {
        var oPassword = $('contactPassword');
        var oConfirm = $('contactConfirm');
        var reSymbols = /[^\w]/i;

        oPassword.value = oPassword.value.replace(/\s/, '');

        if (oPassword.value.length < 6) {
            alert('Пароль не может быть меньше шести символов');
            unLockSendButton();
            return false;
        }

        if (reSymbols.test(oPassword.value)) {
            alert('Пароль может содержать только буквы латинского алфавита, цифры и символ "_"');
            unLockSendButton();
            return false;
        }

        if (oName.value.replace(/\s/, '').length == 0) {
            alert('Введите имя');
            unLockSendButton();
            return false;
        }

        if (oPassword.value != oConfirm.value) {
            alert('Подтвердите пароль');
            unLockSendButton();
            return false;
        }

        saveSession(function() {
            new Ajax.Request('/plugins/ajax/check_user.php?', {
                parameters : 'login=' + oEmail.value,
                onSuccess  : function(transport, json) {
                    if (json.success) {
                        alert('Пользователь с таким e-mail уже существует');
                        unLockSendButton();
                    } else {
                        new Ajax.Request('/plugins/ajax/create_ad.php', {
                            parameters : 'password=' + oPassword.value + '&' +
                                'login=' + oEmail.value + '&' +
                                'parent_id=' + parentID.value + '&' +
                                'first_name=' + $('contactFirstName').value + '&' +
                                //'last_name='  + $('contactLastName').value   + '&' +
                                'phone=' + $('contactPhone').value + '&' +
                                'mobile=' + $('contactMobile').value + '&' +
                                'icq=' + $('contactICQ').value + '&' +
                                'dob=' + $('contactYear').value + '-' + $('contactMonth').value + '-' + $('contactDay').value + '&' +
                                'city=' + $('contactCity').value + '&' +
                                'street=' + $('contactStreet').value + '&' +
                                //'building='   + $('contactBuilding').value   + '&' +
                                //zip='        + $('contactZIP').value        + '&' +
                                //'fax='        + $('contactFax').value        + '&' +
                                'captcha=' + $('contactCaptcha').value + '&' +
                                'site=' + $('contactSite').value,
                            onSuccess : function(transport, json) {
                                if (json && json.success && json.success != 3) {
                                    //								  document.location = '/userarea/';
                                    document.location = '/add/data/' + json.id + '/';
                                } else if (json.success == 3) {
                                    alert('Неверный код антиспама');
                                    regetCaptcha();
                                } else {
                                    alert('Произошла ошибка при добавлении');
                                }
                                unLockSendButton();
                            },
                            onFailed : function() {
                                alert('Неизвестная ошибка');
                                unLockSendButton();
                            }
                        });
                    }
                }
            });
        });
    } else {
        saveSession(function() {
            var params = 'login=' + $('emailDetails').value + '&' +
                'parent_id=' + parentID.value + '&' +
                'first_name=' + $('contactFirstName').value + '&' +
                //'last_name='  + $('contactLastName').value   + '&' +
                'phone=' + $('contactPhone').value + '&' +
                'mobile=' + $('contactMobile').value + '&' +
                'icq=' + $('contactICQ').value + '&' +
                'dob=' + $('contactYear').value + '-' + $('contactMonth').value + '-' + $('contactDay').value + '&' +
                'city=' + $('contactCity').value + '&' +
                'street=' + $('contactStreet').value + '&' +
                //'building='   + $('contactBuilding').value   + '&' +
                //'zip='        + $('contactZIP').value        + '&' +
                //'fax='        + $('contactFax').value        + '&' +
                'site=' + $('contactSite').value;
            new Ajax.Request('/plugins/ajax/create_ad.php?' + Math.random(0, 1000), {
                parameters : params,
                onSuccess : function(transport, json) {
                    if (json && json.success) {
                        //						  document.location = '/userarea/';
                        if (json.success == 2) {
                            alert("Вам запрещено публиковать объявления в этом разделе");
                        } else {
                            if (json.success == 3) {
                                alert('Вы достигли лимита на количество объявлений, разрешенное для одновременной публикакции на сайте. Удалите или отредактируйте одно из старых объявлений, чтобы опубликовать новую информацию.');
                                document.location = '/userarea/';
                            } else {
                                document.location = '/add/data/' + json.id + '/';
                            }
                        }
                    } else {
                        alert('Произошла ошибка при добавлении');
                    }
                    unLockSendButton();
                    $('wizardContactInfo').style.display = 'none';
                },
                onFailed : function() {
                    alert('Неизвестная ошибка');
                    unLockSendButton();
                }
            });
        });
    }

    return true;
}


function replaceRegionAnchor(_this) {
	var el = {};
	while (el = _this.nextSibling) {
        _this.parentNode.removeChild(el);
    }

	new Ajax.Request('/plugins/ajax/districts.php', {
		parameters  : 'parent=' + _this.getAttribute('parent'),
		onCreate    : function() { $('waitMessageDistricts').style.display = '';     },
		onComplete  : function() { $('waitMessageDistricts').style.display = 'none'; },
		onSuccess   : function(transport, json) {
			updateDistricts(json.items);
		}
	});

	_this.parentNode.removeChild(_this);
	$('oDistricts').style.display = '';
	$('add-region').value = _this.getAttribute('parent');

	return false;
}

function getDistricts(parent) {

	$('link-first-step').focus();
	$('add-region').value = parent;
	if (parent == 0) {
        return false;
    }
	new Ajax.Request('/plugins/ajax/districts.php', {
		parameters  : 'parent=' + parent,
		onCreate    : function() { $('waitMessageDistricts').style.display = '';     },
		onComplete  : function() { $('waitMessageDistricts').style.display = 'none'; },
		onSuccess   : function(transport, json) {
			if (200 == transport.status) {

				var oDistricts = $('oDistricts');
				var oDistrictsNavigation = $('districtsNavigation');
				var el = document.createElement('A');

				el.href = '#';
				el.setAttribute('parent', json.item);
				el.onclick = function() {
					replaceRegionAnchor(this);
					return false;
				}
				el.appendChild(document.createTextNode(oDistricts.options[oDistricts.selectedIndex].innerHTML));

				oDistrictsNavigation.appendChild(el);

				el = document.createTextNode(' ');
				oDistrictsNavigation.appendChild(el);

				if (json.items.length > 0) {
					el = document.createElement('IMG');
					el.src = '/webroot/delivery/pic/ar6.gif';
					el.alt = '&raquo;';
					el.width  = 5;
					el.height = 5;

					oDistrictsNavigation.appendChild(el);

					el = document.createTextNode(' ');
					oDistrictsNavigation.appendChild(el);

					updateDistricts(json.items);
				} else {
					$('add-region').value = parent;
					oDistricts.style.display = 'none';
				}
			}
		}
	});
}

function updateDistricts(aItems) {

	var oDistricts = $('oDistricts');
	var el = document.createElement('OPTION');

	oDistricts.innerHTML = '';

	el.value = '0';
	el.selected = true;
	el.appendChild(document.createTextNode('Выберите регион'));

	oDistricts.appendChild(el);

	for (var i = 0, n = aItems.length; i < n; i ++) {
        el = document.createElement('OPTION');
        el.value = aItems[i].unified_id;
        el.appendChild(document.createTextNode(aItems[i].entry_name));
        oDistricts.appendChild(el);
	}
}

function showUploadPhotoBlock(){
    var i;
	if (window.uploadedPhotos[0] == 0) {
		i = 0;
	} else if (window.uploadedPhotos[1] == 0) {
		i = 1;
	} else if (window.uploadedPhotos[2] == 0) {
		i = 2;
	} else {
		return false;
	}

	var origin 	= $('downloaded-photo-');
	var node 	= origin.cloneNode(true);
	var textplace= node.getElementsByTagName('IMG')[0].parentNode.parentNode;
	var span 	= node.getElementsByTagName('SPAN')[0];
	var input  	= node.getElementsByTagName('LABEL')[0];
	var label  	= node.getElementsByTagName('INPUT')[0];
	label.style.visibility="hidden";
	input.style.visibility="hidden";
	span.style.visibility="hidden";
	node.id += (i + 1);
	origin.parentNode.appendChild(node);
	$('photoUploadButton').value="Ждите...";
	$('photoUploadButton').disabled=true;
	textplace.innerHTML="<div style='height:57px; font-size: 12px; font-weight: bold; color: #aaaaaa'>Загрузка...</div>";
	node.style.display = '';
    return true;
}

function hideUploadPhotoBlock(){
    var i;
	if (window.uploadedPhotos[0] == 0) {
		i = 0;
	} else if (window.uploadedPhotos[1] == 0) {
		i = 1;
	} else if (window.uploadedPhotos[2] == 0) {
		i = 2;
	} else {
		return false;
	}

	var block = $('downloaded-photo-' + Number(i+1));
	var parentNode = block.parentNode;
	$('photoUploadButton').disabled=false;
	$('photoUploadButton').value="Загрузить фото";
	parentNode.removeChild(block);

    return true;
}