

subscribe_emails_later_rules = [
	typical_multifield_check(".subscribe_email2",function(root){
		return root.find(".subscribe_email2").val() == root.find(".subscribe_email").val();
	},"Емайлы не совпадают", [".subscribe_email2", ".subscribe_email"] )
	,
	typical_one_field_check(".subscribe_name",function(root){
		return root.find(".subscribe_name").val().length >= 3;
	}, "Имя слишком коротко")
	,
	typical_one_field_check(".subscribe_email",function(root){
		return /^.+@.{3,}\..{2,}$/.test( root.find(".subscribe_email").val() );
	}, "Вы неверно ввели емейл")
	,
	typical_one_field_check(".subscribe_captcha",function(root){

		val = root.find(".subscribe_captcha").val();
		if( ! /^[0-9]{6}$/.test( val ) ) return false;
		return 'true' == ajax_get_sync("./check_captcha.php?captcha=" + val);

	}, "Вы неверно ввели проверочный код")
];


function subscribe_emails_later(callback)
{

	dialog = $('<div></div>').html(''

		//+'<div style="position: relative; z-index: 2">'
		//+'<div style="position:absolute; z-index:1;">'

		+'<p>Хотите экономить вместе с нами и получать от информацию о '
		+'специальных предложениях и акциях страховых компаний по другим видам страховых продуктов?</p>'

		+'<div class="ib w300px">Имя</div>'
		+'<input type="text" class="subscribe_name w260px" '
		+'value="" />'
		//+'value="{/literal}{$userinfo.name1|escape}{if $userinfo.name2} {/if}{$userinfo.name2|escape}{if $userinfo.name3} {/if}{$userinfo.name3|escape}{literal}" />'

		+'<div class="ib w300px" >Емейл</div>'
		+'<input type="text" class="subscribe_email w260px" '
		+'value="" />'
		//+'value="{/literal}{$userinfo.email|escape}{literal}" />'

		+'<br/><div class="ib w300px" >Повторить емейл</div>'
		+'<input type="text" class="subscribe_email2 w260px" '
		+'value="" />'


		+'<br/><div class="ib w300px">Введите шесть арабских цифр с картинки</div>'
		+'<input type="text" class="subscribe_captcha w120px"  />'
		+'<div class="ib w300px"><span style="font-size:11px;">Если Вы не можете прочитать эти цифры, кликните по ним мышкой, чтобы поменять цифры</span></div>'
		+'<div class="ib"><img style="vertical-align:middle;" '
		+'src="./captcha/?" id="captchaimage" onclick="this.src=this.src+\'q\';" /></div>'

		//+'</div>'
		//+'</div>'
	);

	////
	dialog.find(".subscribe_name").keyup(function(){
		if( dialog.find(".subscribe_name").val() == '123' )
		{
			dialog.find(".subscribe_name").val('Евгений');
			dialog.find(".subscribe_email,.subscribe_email2").val('zxc@chetvertakov.com');
			dialog.find(".subscribe_captcha").val( ajax_get_sync('./check_captcha.php?request_captcha'));
		}
	});
	////

	my_form_validator(dialog, subscribe_emails_later_rules);

	$(".inputfield-ie6-bug").hide();

	dialog.dialog({
		autoOpen: false,
		title: 'Basic Dialog',
		buttons: { 
			   "Отменить"	 :
				function() { 
					$(this).dialog("close").dialog("destroy"); 
					$(".inputfield-ie6-bug").show();
				}
			   ,	
			   "Оформить подписку" :
				function() { 
					if( my_form_validator_final(dialog, subscribe_emails_later_rules) )
					{
						arr = { 
							'subscribe_name' : '.subscribe_name', 
							'subscribe_email' : '.subscribe_email', 
							'captcha' : '.subscribe_captcha'
						};	
						
						res = {};
						for( i in arr ) res[i] = dialog.find(arr[i]).val();

						callback(res);
						$(this).dialog("close").dialog("destroy");
						$(".inputfield-ie6-bug").show();
					}
				}
			},
		closeText: "Отменить",
		draggable : false,
		modal: true,
		resizable: false,
		width: 600,
		title: "Получать спецпредложения страховых компаний"
	});
		
	dialog.dialog('open');

	return false;
}

function subscribe_emails_later_step2_cancel(ajax)
{
	ajax.abort();
	alert("Операция отменена");
}

function subscribe_emails_later_step2(arr)
{
	dialog = $('<div></div>').html(''
		+'<p>отправляем данные, одну секундочку...<p>'
	);	

	data = '';
	for( i in arr )
		data = data + i + '=' + encodeURI(arr[i]) + '&';

	var ajax = $.ajax({
		url: "./subscribe_emails.php?" + data,
		cache:false,
		success : function(html) {

				ajax = undefined;
				dialog.dialog("close").dialog("destroy"); 

				if( /^SUCCESS$/.test(html) )
					subscribe_emails_later_step3();
				else
				{
					if( /^ERROR /.test(html) )
						subscribe_emails_later_step2_failure(html.substr(6));
					else
						subscribe_emails_later_step2_failure(html);
				}
			 }
	});


	dialog.dialog({
		autoOpen: false,
		title: 'Basic Dialog',
		buttons: { 
			   "Отменить"	 :
				function() { 
					$(this).dialog("close").dialog("destroy"); 
					if(ajax) subscribe_emails_later_step2_cancel(ajax);
					ajax=undefined;
				}
			},
		close: function() { 
					if(ajax) subscribe_emails_later_step2_cancel(ajax);
					ajax=undefined;
			},
		closeText: "Отменить",
		draggable : false,
		modal: true,
		resizable: false,
//		width: 333,
		title: "Отправка данных"
	});

	dialog.dialog('open');

}

function subscribe_emails_later_step2_failure(msg)
{
	dialog = $('<div></div>').html(''
		+'<p>К сожалению, регистрация не удалась. Попробуйте позже</p>'
		+'<p>' + ((msg==undefined)?'':msg) + '</p>'
	);	
	dialog.dialog({
		autoOpen: false,
		title: 'Basic Dialog',
		buttons: { 
			   "Ok"	 :
				function() { 
					$(this).dialog("close").dialog("destroy"); 
				}
			},
		draggable : false,
		modal: true,
		resizable: false,
//		width: 333,
		title: "Отправка данных"
	});

	dialog.dialog('open');
	
}

function subscribe_emails_later_step3()
{
	dialog = $('<div></div>').html(''
		+'<p>Теперь Вы будете получать информацию о '
		+'специальных предложениях и акциях страховых компаний по другим видам страховых продуктов</p>'
	);	

	dialog.dialog({
		autoOpen: false,
		title: 'Basic Dialog',
		buttons: { 
			   "Ok"	 :
				function() { 
					$(this).dialog("close").dialog("destroy"); 
				}
			},
		draggable : false,
		modal: true,
		resizable: false,
		title: "Ваши данные добавлены"
	});

	dialog.dialog('open');
}



remind_about_casco_later_rules = [ 
/*	{
	recheck_on_change: [".reminder_name"],
	rule: function( root ) { return root.find(".reminder_name").val().length > 3; },
	onerror: function(root){ typical_error(root,".reminder_name"); },
	onerror_cancel: function(root){ typical_error_cancel(root,".reminder_name"); },
	} ,
*/
	typical_multifield_check(".reminder_email2",function(root){
		return root.find(".reminder_email2").val() == root.find(".reminder_email").val();
	},"Емейлы не совпадают", [".reminder_email2", ".reminder_email"] )
	,
	typical_one_field_check(".reminder_name",function(root){
		return root.find(".reminder_name").val().length >= 3;
	}, "Имя слишком коротко")
	,
	typical_one_field_check(".reminder_email",function(root){
		return /^.+@.{3,}\..{2,}$/.test( root.find(".reminder_email").val() );
	}, "Вы неверно ввели емейл")
	,
	typical_one_field_check(".reminder_date",function(root){
		return /^[0-3][0-9]\.[0-1][0-9]\.201[0-9]$/.test( root.find(".reminder_date").val() );
	}, "Дата должна быть в формате ДД.ММ.ГГГГ")
	,
	typical_one_field_check(".reminder_captcha",function(root){

		val = root.find(".reminder_captcha").val();
		if( ! /^[0-9]{6}$/.test( val ) ) return false;
/*
		var return_value= $.ajax({ 
			type: "GET", 
			url: "./check_captcha.php?captcha=" + val , 
			async: false }).responseText;
		return 'true' == return_value;
*/
		return 'true' == ajax_get_sync("./check_captcha.php?captcha=" + val);

	}, "Вы неверно ввели проверочный код")
];


function remind_about_casco_later(callback)
{

	dialog = $('<div></div>').html(''

		+'<p>Вам напомнить о том, '
		+'когда подойдет срок обновления? Мы вышлем Вам напоминание на указанный '
		+'емейл за месяц до даты обновления Вашего полиса</p>'

		+'<div class="ib w300px">Имя</div>'
		+'<input type="text" class="reminder_name w260px" '
		+'value="" />'
		//+'value="{/literal}{$userinfo.name1|escape}{if $userinfo.name2} {/if}{$userinfo.name2|escape}{if $userinfo.name3} {/if}{$userinfo.name3|escape}{literal}" />'

		+'<div class="ib w300px" >Емейл</div>'
		+'<input type="text" class="reminder_email w260px" '
		+'value="" />'
		//+'value="{/literal}{$userinfo.email|escape}{literal}" />'

		+'<br/><div class="ib w300px" >Повторить емейл</div>'
		+'<input type="text" class="reminder_email2 w260px" '
		+'value="" />'

		+'<br/><div class="ib w300px">Дата окончания полиса КАСКО</div>'
		+'<input type="text" class="reminder_date w260px" '
		+'value="" />'


		+'<br/><div class="ib w300px">Введите шесть арабских цифр с картинки</div>'
		+'<input type="text" class="reminder_captcha w120px"  />'
		+'<div class="ib w300px"><span style="font-size:11px;">Если Вы не можете прочитать эти цифры, кликните по ним мышкой, чтобы поменять цифры</span></div>'
		+'<div class="ib"><img style="vertical-align:middle;" '
		+'src="./captcha/?" id="captchaimage" onclick="this.src=this.src+\'q\';" /></div>'


	);

	dialog.find(".reminder_date").datepicker(
		   $.extend
		   ({showMonthAfterYear: false, 
			changeYear: true, 
			changeMonth:true, 
			shortYearCutoff: 50,
			minDate:"0y", maxDate:"+2y",
			defaultDate: "+1m"
			//yearRange:"0y:+1y"

			 }
		   , $.datepicker.regional['ru']
		   )
	);

	////
	dialog.find(".reminder_name").keyup(function(){
		if( dialog.find(".reminder_name").val() == '123' )
		{
			dialog.find(".reminder_name").val('eugene');
			dialog.find(".reminder_email,.reminder_email2").val('zxc@chetvertakov.com');
			dialog.find(".reminder_date").val('30.06.2010');
			dialog.find(".reminder_captcha").val( ajax_get_sync('./check_captcha.php?request_captcha'));
		}
	});
	////

	my_form_validator(dialog, remind_about_casco_later_rules);

	$(".inputfield-ie6-bug").hide();

	dialog.dialog({
		autoOpen: false,
		title: 'Basic Dialog',
		buttons: { 
			   "Отменить"	 :
				function() { 
					$(this).dialog("close").dialog("destroy"); 
					$(".inputfield-ie6-bug").show();
				}
			   ,	
			   "Напомнить по емайлу" :
				function() { 
					if( my_form_validator_final(dialog, remind_about_casco_later_rules) )
					{
						arr = { 
							'reminder_about_casco_name' : '.reminder_name', 
							'reminder_about_casco_email' : '.reminder_email', 
							'reminder_about_casco_date' : '.reminder_date', 
							'captcha' : '.reminder_captcha'
						};	
						
						res = {};
						for( i in arr ) res[i] = dialog.find(arr[i]).val();

						callback(res);
						$(this).dialog("close").dialog("destroy");
						$(".inputfield-ie6-bug").show();
					}
				}
			},
		closeText: "Отменить",
		draggable : false,
		modal: true,
		resizable: false,
		width: 600,
		title: "Напоминание об истекающем полисе КАСКО"
	});
		
	dialog.dialog('open');

	return false;
}

function remind_about_casco_later_step2_cancel(ajax)
{
	ajax.abort();
	alert("Операция отменена");
}

function remind_about_casco_later_step2(arr)
{
	dialog = $('<div></div>').html(''
		+'<p>отправляем данные, одну секундочку...<p>'
	);	

	data = '';
	for( i in arr )
		data = data + i + '=' + encodeURI(arr[i]) + '&';

	var ajax = $.ajax({
		url: "./remind_about_casco.php?" + data,
		cache:false,
		success : function(html) {

				ajax = undefined;
				dialog.dialog("close").dialog("destroy"); 

				if( /^SUCCESS$/.test(html) )
					remind_about_casco_later_step3();
				else
				{
					if( /^ERROR /.test(html) )
						remind_about_casco_later_step2_failure(html.substr(6));
					else
						remind_about_casco_later_step2_failure(html);
				}
			 }
	});


	dialog.dialog({
		autoOpen: false,
		title: 'Basic Dialog',
		buttons: { 
			   "Отменить"	 :
				function() { 
					$(this).dialog("close").dialog("destroy"); 
					if(ajax) remind_about_casco_later_step2_cancel(ajax);
					ajax=undefined;
				}
			},
		close: function() { 
					if(ajax) remind_about_casco_later_step2_cancel(ajax);
					ajax=undefined;
			},
		closeText: "Отменить",
		draggable : false,
		modal: true,
		resizable: false,
//		width: 333,
		title: "Отправка данных"
	});

	dialog.dialog('open');

}

function remind_about_casco_later_step2_failure(msg)
{
	dialog = $('<div></div>').html(''
		+'<p>К сожалению, регистрация не удалась. Попробуйте позже</p>'
		+'<p>' + ((msg==undefined)?'':msg) + '</p>'
	);	
	dialog.dialog({
		autoOpen: false,
		title: 'Basic Dialog',
		buttons: { 
			   "Ok"	 :
				function() { 
					$(this).dialog("close").dialog("destroy"); 
					$(".inputfield-ie6-bug").show();
				}
			},
		draggable : false,
		modal: true,
		resizable: false,
//		width: 333,
		title: "Отправка данных"
	});

	dialog.dialog('open');
	
}

function remind_about_casco_later_step3()
{
	dialog = $('<div></div>').html(''
		+'<p>Ваши данные добавлены. Мы напомним вам, когда прийдёт срок покупать новый полис КАСКО </p>'
	);	

	dialog.dialog({
		autoOpen: false,
		title: 'Basic Dialog',
		buttons: { 
			   "Ok"	 :
				function() { 
					$(this).dialog("close").dialog("destroy"); 
				}
			},
		draggable : false,
		modal: true,
		resizable: false,
		title: "Ваши данные добавлены"
	});

	dialog.dialog('open');
}



function open_500rub_rules()
{

	dialog = $('<div></div>').html(''

	//Как получить 500 руб. от НеУверен.ру:
 
		+"<p>Воспользуйтесь <a href='/steps.html'>нашим калькулятором</a>, выберите самый выгодный вариант КАСКО.</p>"
		+"<p>Затем купите эту страховку напрямую у страховой компании, сославшись на сервис НеУверен.ру.</p>"
		+"<p><a href='/feedback.html'>Сообщите нам</a> название страховой компании, в которой Вы купили КАСКО и номер полиса."
		+"И укажите, куда именно Вам перечислить 500 руб: номер сотового телефона или кошелек электронных денег. Мы переведем деньги в течение 3 дней.</p>"

/*
		+'<p>Ваш друг планирует покупать/обновлять КАСКО?</p>'
		+'<p>Помогите ему сэкономить при покупке КАСКО и оба получите вознаграждение в размере 500 рублей!</p>'
		+'<p>Порекомендуйте другу наш сервис и попросите его указать Ваш контакт (имя и телефон) при заполнении обратной связи. Эти данные вводятся после покупки полиса КАСКО в выбранной на нашем сайте страховой компании с ссылкой на нас.</p>'
		+'<p>Мы свяжемся с Вами для уточнения, как именно Вам удобно <a href="/500rub-popup.html" class="open500rub">получить вознаграждение 500 рублей</a>.</p>'
		+'<p>Также и Ваш друг получит <a href="/500rub-popup.html" class="open500rub">дополнительное вознаграждение</a>.</p>'
		+'<p>Если у Вас возникли вопросы, звоните нам по телефону <nobr>+7 (495) 502-26-22</nobr> или пишите на <a href="mai'+'lto:pr'+'@'+'neuveren.ru">pr'+'@'+'neuveren.ru</a></p>'
		+'<p>Экономьте на КАСКО вместе с нами!</p>'
*/
		/*
		+'<p>У Вас есть знакомый, покупающий КАСКО?</p>'

		+'<p>Помогите ему сэкономить при следующей покупке КАСКО, '
		+'порекомендовав наш сервис и он будет Вам благодарен. Кроме того, '
		+'и Вы, и Ваш знакомый получите вознаграждение от нас по 500 рублей!</p>'
		*/
	);

	dialog.find('.open500rub').popupWindow({ height:500, width:800, top:50, left:50, scrollbars:1 , location:0}); 

	dialog.dialog({
		autoOpen: false,
		title: 'Получите от НеУверен.ру 500 руб.!',
		buttons: { 
			   "Закрыть"	 :
				function() { 
					$(this).dialog("close").dialog("destroy"); 
					$(".inputfield-ie6-bug").show();

				}
			},
		closeText: "Закрыть",
		draggable : false,
		modal: true,
		resizable: false,
		width: 500
	});
		
	$(".inputfield-ie6-bug").hide();
	dialog.dialog('open');


	return false;
}


function ask_for_phone(email,phonenum)
{

	var dialog = $('<div></div>').html(''

		+'<p>Чтобы получить скидку от Неуверен.ру , пожалуйста, оставьте свой телефон</p>'

		+'<div class="ib w300px">Телефон</div>'
		+'<form method="POST">'
		+'<input type="text" class="w260px" name="change_user_settings_tel1" value="'+phonenum+'" />'
		+'<input type="hidden" name="change_user_settings_email" value="'+email+'" />'
		+'</form>'

	);

	dialog.dialog({
		autoOpen: false,
		title: 'скидка от Неуверен.ру',
		buttons: { 
			   "Пропустить"	 :
				function() { 
					$(this).dialog("close").dialog("destroy"); 
					$(".inputfield-ie6-bug").show();
				}
			   ,	
			   "Подтвердить" :
				function() { 
					dialog.find("form").submit();
				}
			},
		closeText: "Пропустить",
		draggable : false,
		modal: true,
		resizable: false,
		width: 600
	});
		
	dialog.dialog('open');

	return false;
}

function ask_for_phone_and_name(e,email,name2,phonenum)
{

	var dialog = $('<div></div>').html(''

		+'<p>Чтобы получить скидку от Неуверен.ру , пожалуйста, оставьте своё имя и телефон</p>'

		+'<form method="POST" action="'+e.href+'">'
		+'<div class="ib w300px">Имя</div>'
		+'<input type="text" class="w260px" name="change_user_settings_name2" value="'+name2+'" />'
		+'<div class="ib w300px">Телефон</div>'
		+'<input type="text" class="w260px" name="change_user_settings_tel1" value="'+phonenum+'" />'
		+'<input type="hidden" name="change_user_settings_email" value="'+email+'" />'
		+'</form>'

	);

	dialog.dialog({
		autoOpen: false,
		title: 'скидка от Неуверен.ру',
		buttons: { 
			   "Пропустить"	 :
				function() { 
					window.location = e.href; 
				}
			   ,	
			   "Подтвердить" :
				function() { 
					dialog.find("form").submit();
				}
			},
		closeText: "Пропустить",
		draggable : false,
		modal: true,
		resizable: false,
		width: 600
	});
		
	dialog.dialog('open');

	return false;
}


function send_results_to_email(email,realemail)
{

	var dialog = $('<div></div>').html(''

		+'<p>Чтобы получить результаты расчёта по почте, пожалуйста, укажите Ваш e-mail:</p>'

		+'<div class="ib w300px">E-mail</div>'
		+'<form method="POST">'
		+'<input type="text" class="w260px" name="change_user_settings_realemail" value="'+realemail+'" />'
		+'<input type="hidden" name="user_settings_realemail_old" value="'+realemail+'" />'
		+'<input type="hidden" name="change_user_settings_email" value="'+email+'" />'
		+'<input type="hidden" name="email_result_to_email" value="1" />'
		+'</form>'

	);

	dialog.dialog({
		autoOpen: false,
		title: 'Переслать варианты на e-mail',
		buttons: { 
			   "Пропустить"	 :
				function() { 
					$(this).dialog("close").dialog("destroy"); 
					$(".inputfield-ie6-bug").show();
				}
			   ,	
			   "Подтвердить" :
				function() { 
					dialog.find("form").submit();
				}
			},
		closeText: "Пропустить",
		draggable : false,
		modal: true,
		resizable: false,
		width: 600
	});
		
	dialog.dialog('open');

	return false;
}

