$(document).ready(function(){

	(function($) {// Cory S.N. LaViska / A Beautiful Site (http://abeautifulsite.net/) / Visit http://abeautifulsite.net/notebook/87 for more information
		$.alerts = {
			// These properties can be read/written by accessing $.alerts.propertyName from your scripts at any time
			verticalOffset: -75,				// vertical offset of the dialog from center screen, in pixels
			horizontalOffset: 0,				// horizontal offset of the dialog from center screen, in pixels/
			repositionOnResize: true,			// re-centers the dialog on window resize
			overlayOpacity: .01,				// transparency level of overlay
			overlayColor: '#FFF',				// base color of overlay
			draggable: true,					// make the dialogs draggable (requires UI Draggables plugin)
			okButton: '&nbsp;OK&nbsp;',			// text for the OK button
			cancelButton: '&nbsp;Отмена&nbsp;',	// text for the Cancel button
			dialogClass: null,					// if specified, this class will be applied to all dialogs
			
			// Public methods
			alert: function(message, title, callback) {
				if( title == null ) title = 'Информация';
				$.alerts._show(title, message, null, 'alert', function(result) {
					if( callback ) callback(result);
				});
			},
			
			confirm: function(message, title, callback) {
				if( title == null ) title = 'Уведомление';
				$.alerts._show(title, message, null, 'confirm', function(result) {
					if( callback ) callback(result);
				});
			},
			
			prompt: function(message, value, title, callback) {
				if( title == null ) title = 'Prompt';
				$.alerts._show(title, message, value, 'prompt', function(result) {
					if( callback ) callback(result);
				});
			},
			
			// Private methods
			_show: function(title, msg, value, type, callback) {
				
				$.alerts._hide();
				if (!$.browser.msie) {$.alerts._overlay('show');}
			
				$("body").append(
					'<div id="popup_container">' +
						'<div id="popup_title"></div>' +
						'<div id="popup_content">' +
							'<div id="popup_message"></div>' +
						'</div>' +
					'</div>');
				
				if( $.alerts.dialogClass ) $("#popup_container").addClass($.alerts.dialogClass);
				
				// IE6 Fix
				var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed'; 
				
				$("#popup_container").css({
					position: pos,
					zIndex: 99999,
					padding: 0,
					margin: 0
				});
				
				$("#popup_title").text(title);
				$("#popup_content").addClass(type);
				$("#popup_message").text(msg);
				$("#popup_message").html( $("#popup_message").text().replace(/\n/g, '<br />') );
				
				$("#popup_container").css({
					minWidth: $("#popup_container").outerWidth(),
					maxWidth: $("#popup_container").outerWidth()
				});
				
				$.alerts._reposition();
				$.alerts._maintainPosition(true);
				switch( type ) {
					case 'alert':
						$("#popup_message").after('<div id="popup_panel"><input class="btn alert" type="button" value="' + $.alerts.okButton + '" id="popup_ok" /></div>');
						$("#popup_ok").click( function() {
							$.alerts._hide();
							callback(true);
						});
						$("#popup_ok").focus().keypress( function(e) {
							if( e.keyCode == 13 || e.keyCode == 27 ) $("#popup_ok").trigger('click');
						});
					break;
					case 'confirm':
						$("#popup_message").after('<div id="popup_panel" style="width: 200px; margin: 0 auto 5px;"><input class="btn fl" type="button" value="' + $.alerts.okButton + '" id="popup_ok" /><input class="btn fr" type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /><div class="clear"></div></div>');
						$("#popup_ok").click( function() {
							$.alerts._hide();
							if( callback ) callback(true);
						});
						$("#popup_cancel").click( function() {
							$.alerts._hide();
							if( callback ) callback(false);
						});
						$("#popup_ok").focus();
						$("#popup_ok, #popup_cancel").keypress( function(e) {
							if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
							if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
						});
					break;
					case 'prompt':
						$("#popup_message").append('<br /><input type="text" size="30" id="popup_prompt" />').after('<div id="popup_panel"><input class="btn" type="button" value="' + $.alerts.okButton + '" id="popup_ok" /> <input type="button" value="' + $.alerts.cancelButton + '" id="popup_cancel" /></div>');
						$("#popup_prompt").width( $("#popup_message").width() );
						$("#popup_ok").click( function() {
							var val = $("#popup_prompt").val();
							$.alerts._hide();
							if( callback ) callback( val );
						});
						$("#popup_cancel").click( function() {
							$.alerts._hide();
							if( callback ) callback( null );
						});
						$("#popup_prompt, #popup_ok, #popup_cancel").keypress( function(e) {
							if( e.keyCode == 13 ) $("#popup_ok").trigger('click');
							if( e.keyCode == 27 ) $("#popup_cancel").trigger('click');
						});
						if( value ) $("#popup_prompt").val(value);
						$("#popup_prompt").focus().select();
					break;
				}
			},
			
			_hide: function() {
				$("#popup_container").remove();
				$.alerts._overlay('hide');
				$.alerts._maintainPosition(false);
			},
			
			_overlay: function(status) {
				switch( status ) {
					case 'show':
						$.alerts._overlay('hide');
						$("BODY").append('<div id="popup_overlay"></div>');
						$("#popup_overlay").css({
							position: 'absolute',
							zIndex: 99998,
							top: '0',
							left: '0',
							width: '100%',
							height: $(document).height(),
							background: '#000',
							opacity: '0.1'
						});
					break;
					case 'hide':
						$("#popup_overlay").remove();
					break;
				}
			},
			
			_reposition: function() {
				var top = (($(window).height() / 2) - ($("#popup_container").outerHeight() / 2)) + $.alerts.verticalOffset;
				var left = (($(window).width() / 2) - ($("#popup_container").outerWidth() / 2)) + $.alerts.horizontalOffset;
				if( top < 0 ) top = 0;
				if( left < 0 ) left = 0;
				
				// IE6 fix
				if( $.browser.msie && parseInt($.browser.version) <= 6 ) top = top + $(window).scrollTop();
				
				$("#popup_container").css({
					top: top + 'px',
					left: left + 'px'
				});
			},
			
			_maintainPosition: function(status) {
				if( $.alerts.repositionOnResize ) {
					switch(status) {
						case true:
							$(window).bind('resize', function() {
								$.alerts._reposition();
							});
						break;
						case false:
							$(window).unbind('resize');
						break;
					}
				}
			}
			
		}
	
	})(jQuery);

	// Shortuct functions
	jAlert = function(message, title, callback) {
		if ($.browser.msie && parseInt($.browser.version) <= 6 ) {alert(message);} else {$.alerts.alert(message, title, callback);}
	}
	jConfirm = function(message, title, callback) {
		$.alerts.confirm(message, title, callback);
	};
		
	jPrompt = function(message, value, title, callback) {
		$.alerts.prompt(message, value, title, callback);
	};
	
	/* Form Authorization */
	$("#RegBlock input[name='email']").focus(function(){
		$(this).val('');
		$(this).unbind('focus');
	});
	$("#RegBlock input[name='password']").focus(function(){
		$(this).hide();
		$(this).after('<input name="password" class="password" type="password" value="" />');
		$(this).remove();
		$("#RegBlock input[name='password']").focus();
	});
	
	/* Button Mouse Over for IE6 */
	if ($.browser.msie && $.browser.version == 6)
	{
		$(".Button").hover
		(
			function(){ $(this).attr("style","color:#fff !important;"); },
			function(){ $(this).attr("style","color:#ccc !important;"); }
		);
	}
	
	/* Form Registration (run) */
	
	// Client Type Selected
	$("#RegistrationPage form:first select[name='client_type']",this).change(function(){
		if ($(this).val()=="other")
		{
			$("#RegistrationPage form .client_type_other").show();
			$("#RegistrationPage form .client_type_other input").focus();
		} else {
			$("#RegistrationPage form .client_type_other").hide();
		}
	});
	
	// Validation
	$("#RegistrationPage form:first").submit(function(){
		
		var ErrorMessage	= '';
		var ClientType		= $("select[name='client_type']",this).val();
		var ClientTypeOther	= $("input[name='client_type_other']",this).val();
		var ClientCity		= $("select[name='client_city']",this).val();
		var UserCompany		= $("input[name='user_company']",this).val();
		var UserPhoneCity	= $("input[name='user_phone_city']",this).val();
		var UserPhone		= $("input[name='user_phone']",this).val();
		var UserPhoneAll	= '';
		var UserSurname		= $("input[name='user_surname']",this).val();
		var UserName		= $("input[name='user_name']",this).val();
		var UserEmail		= $("input[name='user_email']",this).val();
		
		
		
		UserPhone = str_replace(/[^0-9.]/,'',UserPhone);
		
		// Clien Type
		switch(ClientType)
		{
			case "0":
				ErrorMessage += '- Кем Вы являетесь? \r\n';
			break;
			case "other":
				if (ClientTypeOther=='') ErrorMessage += '- Кем Вы являетесь? \r\n';
			break;
		}

		if (ClientCity=='0')	ErrorMessage += '- Город 				   \r\n';
		if (UserCompany=='')	ErrorMessage += '- Название предприятия    \r\n';
		if (UserPhoneCity=='' || UserPhone.length <= 4)		ErrorMessage += '- Телефон (неверный формат)  \r\n';
		if (UserSurname=='')	ErrorMessage += '- Фамилия                 \r\n';
		if (UserName=='')		ErrorMessage += '- Имя                     \r\n';

		// User Email
		if (UserEmail=='')
		{
			ErrorMessage += '- Корпоративный E-mail \r\n';
		} else {
			if (!(/^([a-z0-9_\-]+\.)*[a-z0-9_\-]+@([a-z0-9][a-z0-9\-]*[a-z0-9]\.)+[a-z]{2,4}$/i).test(UserEmail)) ErrorMessage += '- Не верный формат E-mail \r\n';
		}
		
		// Ajax Email validation
		if (!ErrorMessage)
		{
			$.ajax
			({
				url: "/ajax.php",
				type: "POST",
				dateType: "text",
				async: false,
				data: { file: '/_core/ajax.email_validation.php', email: UserEmail },
				beforeSend: function(){},
				complete: function(){},
				success: function(data){
					if (data!=="0") ErrorMessage += '- Пользователь с таким E-mail уже зарегистрирован \r\n';
				},
				error: function(){ ErrorMessage += 'Ошибка при обращении к серверу для проверки E-mail \r\n'; }
			});
		}
		
		if (ErrorMessage)
		{
			ErrorMessage = 'Не правильно заполнены следующие поля:\r\n'+ErrorMessage;
			jAlert(ErrorMessage);
		} else {
			$(this).unbind(); // delete submit events
			$(this).submit();
		}
		return false;
	});

	function str_replace(search, replace, subject) {
		return subject.split(search).join(replace);
	}

	// Submit
	$("#RegistrationPage form [type='button']").click(function(){
		$("#RegistrationPage form").submit();
		return false;
	});
	
	/* Form Registration (end) */

});

function hidePopupF(el) {
	$(el).hide();
	$("#popup_overlay1").remove();
}

function showPopupF(el) {
	$("BODY").append(($.browser.msie && parseInt($.browser.version) <= 6)?'<iframe id="popup_overlay1" src="" frameborder="0"></iframe>':'<div id="popup_overlay1"></div>');
	$("#popup_overlay1").css({position: 'absolute', zIndex: 99996, top: '0', left: '0', width: '100%', height: $(document).height(), background: '#000', opacity: '0.1'});
	var pos = ($.browser.msie && parseInt($.browser.version) <= 6 ) ? 'absolute' : 'fixed';
	var top = (($(window).height() / 2) - ($(el).outerHeight() / 2)) + $(window).scrollTop();
	var left = (($(window).width() / 2) - ($(el).outerWidth() / 2)) + $(window).scrollLeft();
	if( top < 0 ) top = 0;
	if( left < 0 ) left = 0;
	if( $.browser.msie && parseInt($.browser.version) <= 6 ) $("#popup_overlay1").css({opacity: '0'});
	$(el).css({display: 'block', top: top + 'px', left: left + 'px', zIndex: 99997});
	return false;
}

function strip(html) { //удаляет все html из строки
	return html.replace(/<.*?>/g, '');
}
