/**
 * @author Ivan Priorov [iPrior] darkmonk9@gmail.com
 */
var newProjectForm = {
	closeForm:function() {
		alert('Проект сохранен');
		$('apDivProjectForm_BG').remove();
		$('apDivProjectForm').remove();
		window.location = window.location;
	},
	getForm:function() {
		/*
		if(!$('apDivProjectForm_BG')) {
			var doc = document.getElementsByTagName("body")[0];
			var div = new Element('div',{
				'id':'apDivProjectForm_BG',
				'style':'cursor:pointer; position:absolute; width:100%; height:100%; z-index:1; display:block; background-color:#f4f8ed; top:0px; left:0px;',
				'onclick':'javascript:$(\'apDivProjectForm\').remove(); $(\'apDivProjectForm_BG\').remove();'
			}).update('<b>закрыть</b>');
			doc.appendChild(div);
			$('apDivProjectForm_BG').setOpacity(0.9);
		}
		
		if(!$('apDivProjectForm')) {
			var div = new Element('div',{
				'id':'apDivProjectForm',
				'style':'position:absolute; width:675px; left:5px; z-index:2; display:block; background:url("/img/col2_bg.gif") repeat-y scroll center center #FFFFFF; top:50px; left:350px;'
			}).update();
//			$("col_2").appendChild(div);
			$('light_project_form').appendChild(div);
		}*/
		new Ajax.Updater('light_project_form','/new_project.php',{
			onComplete:function(transport) {
				
			}
		});
	},
	updateContent:function(content) {
		$('light_project_form').update(content);
	},
	newProjectStep:1,
	actNext:function() {
		if(this.validator()) {
			$('newProject'+this.newProjectStep).hide();
			$('step'+this.newProjectStep).style.fontWeight = 'normal';
			this.newProjectStep++;
			$('step'+this.newProjectStep).style.fontWeight = 'bold';
			$('newProject'+this.newProjectStep).show();
		}
		this.buttonsControl();
	},
	actBack:function() {
		$('newProject'+this.newProjectStep).hide();
		$('step'+this.newProjectStep).style.fontWeight = 'normal';
		this.newProjectStep--;
		$('step'+this.newProjectStep).style.fontWeight = 'bold';
		$('newProject'+this.newProjectStep).show();
		this.buttonsControl();
	},
	buttonsControl:function() {
		if(this.newProjectStep==1) $('butBack').hide();
		if(this.newProjectStep>1)  $('butBack').show();
		if(this.newProjectStep<6)  { $('butNext').show(); $('butSubmit').hide(); }
		if(this.newProjectStep==6) { $('butNext').hide(); }
		if(this.newProjectStep>6) $('butBack').hide();
	},
	pay_methods: $H({pay_method_1:'Банковский перевод',pay_method_2:'Электронные деньги',pay_method_3:'Наличные'}),
	validator:function() {
		switch(this.newProjectStep) {
			case 1:
				if(!$F('name')) {
					$('name').focus();
					alert('Введите название проекта');
					return false;
				}
				if(!$F('finish')) {
					$('finish').focus();
					alert('Введите срок выполнения проекта в днях');
					return false;
				}
				var reg = /\D{1,}/
				if(reg.test($F('finish'))) {
					$('finish').focus();
					alert('Срок выполнение указывается цифрой');
					return false;
				}
				if($F('finish')=="0") {
					$('finish').focus();
					alert('Срок выполнение не может быть нулевым');
					return false;
				}
				if(!$('np_rules').checked) {
					$('np_rules').focus();
					alert('Для продолжения необходимо согласиться с правилами ресурса');
					return false;
				}
				break;
			case 2:
				if(!$F('descr')) {
					$('descr').focus();
					alert('Введите описание проекта');
					return false;
				}
				break;
			case 3:
				if(!$F('requirements')) {
					$('requirements').focus();
					alert('Введите обязательные требования');
					return false;
				}
				break;
			case 4:
				if($('fp').checked) {
					$('newProject_varOpl_1').hide();
					$('newProject_varOpl_2').hide();
					$('tenderDescr').hide();
					if(!$F('cost') || $F('cost')==0) $('cost').value = 1000;
				}
				else {
					$('newProject_varOpl_1').show();
					$('newProject_varOpl_2').show();
					$('tenderDescr').show();
					if(!$F('cost')) $('cost').value = 0;
				}
				break;
			case 5:
				if(!$F('cost')) {
				$('cost').focus();
				alert('Введите стоимость проекта в рублях.');
				return false;
				}
				var reg = /\D{1,}/
				if(reg.test($F('cost'))) {
					$('cost').focus();
					alert('Стоимость указывается цифрой');
					return false;
				}
				if(!$('fp').checked) {
					var lsr = false;
					var id_pm = this.pay_methods.keys();
					for(var a=0; a<id_pm.length; a++) {
						if($(id_pm[a]).checked) lsr = true;
					}
					if(!lsr) {
						alert('Выберите способ оплаты');
						return false;
					}
				}
				else {
					var id_pm = this.pay_methods.keys();
					for(var a=0; a<id_pm.length; a++) {
						if($(id_pm[a]).checked) $(id_pm[a]).checked = false;
					}
					$('pay_method_2').checked='checked';
				}
				this.getSummary()
				$('butSubmit').show();
				break;
			case 6:
				$('newProject6').update('Пожалуйста дождитесь загрузки.');
				$('newProjectsStepsInfo').hide();
				$('butBack').hide();
				$('butNext').hide();
				$('butSubmit').hide();
				this.validateUser();
				return false;
				break;
		}
		return true;
	},
	validateUser:function() {
		new Ajax.Updater('newProject6','/new_project.php',{
			method:'post',
			parameters:'act=validateUser',
			evalScripts:true,
			onComplete:function(transport) {
			//alert(transport.responseText);
			}
		});
	},
	getSummary:function() {
		var category = false;
		for(var a=0; a<$('spec').options.length; a++) {
			if($('spec').options[a].selected) {
				category = $('spec').options[a].innerHTML;
				break;
			}
		}
		var pm = '';
		var id_pm = this.pay_methods.keys();
		for(var a=0; a<id_pm.length; a++) {
			if($(id_pm[a]).checked) {
				pm += this.pay_methods.get(id_pm[a]) + '; ';
			}
		}
		var strInner = '<p><b>Название проекта:</b> ' + $F('name') + '</p>' +
		'<p><b>Категория:</b> ' + category + '</p>' +
		'<p><b>Описание проекта:</b><br />' + $F('descr') + '</p>' +
		'<p><b>Обязательные требования:</b><br />' + $F('requirements') + '</p>' +
		'<p><b>Стоимость:</b> ' + $F('cost') + ' руб.</p>';
		if($('fp').checked) strInner += '<p><b>Используется FairPlay</b></p>';
		else {
			strInner += '<p><b>Способы оплаты: </b>'+pm+'</p>';
			if($('predoplataY').checked) strInner += '<p><b>Возможна предоплата</b></p>';
			else strInner += '<p><b>Предоплата невозможна</b></p>';
		}
		strInner += '<p><b>Срок выполнения:</b> ' + $F('finish') + ' дней.</p>';
		var pub_i = false;
		for(var a=0; a<$('pub_interval').options.length; a++) {
			if($('pub_interval').options[a].selected) {
				pub_i = $('pub_interval').options[a].innerHTML;
				break;
			}
		}
		strInner += '<p><b>Период публикации:</b> '+pub_i+'</p>';
		$('newProject6').update(strInner);
	},
	getRegForm:function() {
		$('np_RegUser').show();
		$('np_SiginUser').hide();
		$('np_RegUserTitle').style.fontWeight = 'bold';
		$('np_SiginUserTitle').style.fontWeight = 'normal';
		$('np_SiginUserTitle').style.textDecoration = 'underline';
		$('np_RegUserTitle').style.textDecoration = 'none';
	},
	getSiginForm:function() {
		$('np_RegUser').hide();
		$('np_SiginUser').show();
		$('np_RegUserTitle').style.fontWeight = 'normal';
		$('np_SiginUserTitle').style.fontWeight = 'bold';
		$('np_SiginUserTitle').style.textDecoration = 'none';
		$('np_RegUserTitle').style.textDecoration = 'underline';
	},
	sendRegData:function() {
		if(!$F('mail')) {
			$('mail').focus();
			alert('Укажите Ваш адрес электронной почты');
			return false;
		}
		var reg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
		if(!reg.test($F('mail'))) {
			$('mail').focus();
			alert('Неверно указан адрес электронной почты');
			return false;
		}
		if(!$F('np_login_r')) {
			$('np_login_r').focus();
			alert('Укажите желаемый логин');
			return false;
		}
		var reg = /\w{3,}/;
		if(!reg.test($F('np_login_r'))) {
			$('np_login_r').focus();
			alert('Логин должен содержать символы лат.алфавита и цифры.\nДлина логина не может быть меньше 3 символов.');
			return false;
		}
		var img = new Element('img',{
			'src':'http://freelance.ru/img/ajax-loader.gif',
			'id':'np_LoaderIMG',
			'alt':'Загрузка данных',
			'title':'Загрузка данных'});
		$('np_RegUserTitle').appendChild(img);
		new Ajax.Request('/new_project.php',{
			method:'post',
			parameters:'act=sendRegData&login='+$F('np_login_r')+'&email='+$F('mail'),
			onComplete:function(transport) {
				if(transport.responseText=='OK') {
					newProjectForm.submitForm();
				}
				else {
					alert(transport.responseText);
				}
				$('np_LoaderIMG').remove();
			}
		});
	},
	sendSiginData:function() {
		if(!$F('np_passwd_s')) {
			$('np_passwd_s').focus();
			alert('Укажите Ваш пароль');
			return false;
		}
		if(!$F('np_login_s')) {
			$('np_login_s').focus();
			alert('Укажите Ваш логин');
			return false;
		}
		var reg = /\w{3,}/;
		if(!reg.test($F('np_login_s'))) {
			$('np_login_s').focus();
			alert('Логин должен содержать символы лат.алфавита и цифры.\nДлина логина не может быть меньше 3 символов.');
			return false;
		}
		var img = new Element('img',{
			'src':'http://freelance.ru/img/ajax-loader.gif',
			'id':'np_LoaderIMG',
			'alt':'Загрузка данных',
			'title':'Загрузка данных'});
		$('np_SiginUserTitle').appendChild(img);
		new Ajax.Request('/new_project.php',{
			method:'post',
			parameters:'act=sendSiginData&login='+$F('np_login_s')+'&password='+$F('np_passwd_s'),
			onComplete:function(transport) {
			//alert('Response: '+transport.responseText);
				if(transport.responseText=='OK') {
					newProjectForm.submitForm();
				}
				else {
					alert(transport.responseText);
				}
				$('np_LoaderIMG').remove();
			}
		});
	},
	submitForm:function() {
	//alert('submit start');
		$('np_form').style.display='none';
		$('np_submit_loader').style.display='block';
		this.newProjectStep = 1;
		for(var a=1; a<6; a++) {
			this.newProjectStep = a;
			if(!this.validator()) {
				alert('Непредвиденная ошибка');
				window.location = window.location;
				return false;
			}
		}
		//alert('submit finish');
		$('np_form').submit();
	},
	resetSubmit:function(message) {
		this.newProjectStep=6;
		$('newProjectsStepsInfo').show();
		$('step6').style.fontWeight = 'bold';
		$('newProject6').show();
		this.buttonsControl();
		this.getSummary();
		$('np_submit_loader').hide();
		$('np_form').show();
		alert(message);
	}
}
//setTimeout('newProjectForm.getForm()',4000);
