
/*
// Индикатор работы ajax
$(document).ready(function(){
	$("#loading").bind("ajaxSend", function(){
	    $(this).show(); // показываем элемент
	}).bind("ajaxComplete", function(){
	    $(this).hide(); // скрываем элемент
	});
});
*/

function enableWysiwyg(element)
{
	element.wysiwyg({
		controls : {
			h1mozilla : { visible : false },
			h2mozilla : { visible : false },
			h3mozilla : { visible : false },
			h1 : { visible : false },
			h2 : { visible : false },
			h3 : { visible : false },
			separator06 : { visible : false },
			
			strikeThrough : { visible : true },
			underline : { visible : true },
			
			justifyLeft : { visible : false },
			justifyCenter : { visible : false },
			justifyRight : { visible : false },
			indent : { visible : false },
			outdent : { visible : false },
			undo : { visible : false },
			redo : { visible : false },
			
			createLink : { visible : false },
			insertImage : { visible : false },
			
			separator05 : { visible : false },
			
			html : { visible : false },
			
			separator08 : { visible : false },
			increaseFontSize :	{ visible : false },
			decreaseFontSize :	{ visible : false },
			
			cutSep : { separator : true },
			insertcut : {
				visible   : true,
				exec      : function() {
					
					var sz = prompt('Текст ката', 'Узнать больше');

					if ( sz && sz.length > 0 ) {
						id = element.attr('id');
						$( $('#'+id+'IFrame').document() ).find('hr').remove();
						$('#'+id+'IFrame').document().execCommand("InsertHorizontalRule", false, 0);
						$( $('#'+id+'IFrame').document() ).find('hr').removeAttr("style");
						$( $('#'+id+'IFrame').document() ).find('hr').attr("value", sz);
						$( $('#'+id+'IFrame').document() ).find('hr').attr("class", "cut");
					}
				},
				className : 'cut'
			}
		}
	});
}

function getClientWidth()
{
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientWidth:document.body.clientWidth;
}

function getClientHeight()
{
  return document.compatMode=='CSS1Compat' && !window.opera?document.documentElement.clientHeight:document.body.clientHeight;
}

function closeAllNiceForms()
{
    $('.inline_window').hide();
	overInlineWnd = false;
}

// Показывает скрытый див в лучшем виде
function openNiceForm(link, divId, width)
{
    closeAllNiceForms();
    
    // Изменим атрубуты дива
    div = $("#"+divId);
    div.addClass('inline_window');
	
	overInlineWnd = true;
	div.hover(function() {overInlineWnd = true;}, function() {overInlineWnd = false;});

    // Если задана ширина блока
    if (width) {
        div.css("width", width);
    }
    
    // Добавим заголовок с кнопкой Закрыть, если его нет
    html = "<div class='inlw_caption' style='width: 100%'>";
	html += "<div style='float:left'>";
	html += "</div>";
	html += "<div style='float:right'>";
	html += "<small><a href='#' class='inlw_close'>Закрыть</a></small>";
	html += "</div>";
	html += "</div>";
	html += "<br/><br/>";
    
    if (!$(".inlw_caption", div).length) {
        div.prepend(html);
    }
    
    // кнопка закрытия
    $(".inlw_close", div).bind("click", function(){
        $('.inline_window').hide();
        return false;
    });
    
    // при отправке формы окошко должно закрываться
    //$("input[type='submit']", div).bind("click", function(){
    //    $('.inline_window').hide();
    //});
		
    var p = $(link).position();
    
	if (p.top + div.height() > getClientHeight())
		div.css("top", p.top - div.height() + $(link).height());
	else
		div.css("top", p.top /*+ $(link).height()*/);
	
	if (p.left + div.width() > getClientWidth())
		div.css("left", p.left - div.width() + $(link).width());
	else
		div.css("left", p.left);
    
    div.fadeIn(300);
}

// Универсальное ajax-заполнение select
function getItemsToSelect(module, ref, select, val)
{
    select.empty();
    $("<option></option>")  
        .attr("value", 0)  
        .html("идет загрузка...") 
        .appendTo(select);
    
    // получаем список подчиненных тегов с помощью ajax
    //$.get("/admin/get_ajax/module/"+module+"/ref/"+ref, function(data) {
	$.get("/admin/get_ajax/module/"+module+"/ref/"+ref+".ajax", function(data) {
        
        //alert(data);
        
        select.empty();
        $("<option></option>") 
        .attr("value", 0)
        .html("нет") 
        .appendTo(select);
        
        $("item", data).each(function(){
            
            name = $(this).text();
     	    id = $(this).attr("id");
            
            //alert(name);
            
            opt = $("<option></option>") 
            .attr("value", id) 
            .html(name);
            
            if (id == val) {
                opt.attr("selected", "selected");
            }
            
            opt.appendTo(select);
        }
        );        
    });   
}

// Подгружает список тегов выбранного родителя
function getTagsByParent()
{
    //alert("getTagsByParent");
    
    var parentTag = $("select[name='parent_tag']").val();
    
    $("select[name='tag']").empty();
    $("<option></option>")  
        .attr("value", 0)  
        .html("идет загрузка...") 
        .appendTo($("select[name='tag']"));
    
    // получаем список подчиненных тегов с помощью ajax
    $.get("/companies/gettagsbyparent_ajax/id/"+parentTag, function(data) {
        
        //alert(data);
        
        $("select[name='tag']").empty();
        
        $("<option></option>") 
        .attr("value", 0)
        .html("нет") 
        .appendTo($("select[name='tag']"));
        
        $("item", data).each(function(){
            
            tagname = $(this).text();
     	    tagid = $(this).attr("id");
            
            //alert(tagname);
            
            $("<option></option>") 
            .attr("value", tagid) 
            .html(tagname) 
            .appendTo($("select[name='tag']"));   
        }
        );        
    });
}

// сериализация формы
function srlzForm(formId)
{
    var fields = $("#"+formId).serializeArray();
     var a = [];
     $.each(fields, function(i, field){
         a.push({name: field.name, value: field.value});
     });
     
     return a;
}

// отсылает форму используя ajax
// обрабатывает ответ в xml
// выводит ошибки, если они есть, или редиректит, если все ок
function ajaxSubmitFunc(formId)
{
	var fields = $("#"+formId).serializeArray();
     var a = [];
     $.each(fields, function(i, field){
        a.push({name: field.name, value: field.value});
         
        // если есть вывод ошибки, удалим его
        var div_err = $("#"+field.name+"_err").html(''); 
         
     });
	 
	 button = $("#"+formId+" input[type='submit']");
	 submtext = button.attr("value");
	 
	 button.attr("value", "Идет загрузка...");
     button.attr("disabled","disabled");
     
     $.post($("#"+formId).attr("action"), a, function(data) {
     	
     	//alert($(data).text());
		
		button.attr("value", submtext);
        
		// очищаем ошибки
     	$.each(fields, function(i, field){
			$("#"+field.name+"_err").empty();
     	});
        
     	// если форма принята, редиректим
     	if ($("result", data).text() == "Ok") {
     		var redirect = $("result", data).attr("redirectto");
            //alert(redirect);
     		if(redirect != null) {
				if (redirect == location) {
				    location.reload();
				}
				else location = redirect;
				return;
     		}
     		else {
     			location.reload();
				return;
     		}
     	}
		
		button.removeAttr("disabled");
		
		// если ошибка, выводим
     	if ($("result", data).text() == "Error") {
     		alert("Произошла ошибка: "+$("result", data).attr("description")); 
     	}
     	
		// если пришли ошибки валидации - выводим
		if ($("result", data).text() == "ValidErrors") {
		
			// выводим новые ошибки
			// ошибки выводятся в div-ы с id имяполя_err
			$("error", data).each(function(){
			
				err_text = $(this).text();
				err_field = $(this).attr("field");
				
				//alert(err_field + ": " + err_text);
				
				var field = $("#"+formId+" input[name="+err_field+"]");
				if (!field.length) {
					var field = $("#"+formId+" select[name="+err_field+"]");
				}
                if (!field.length) {
					var field = $("#"+formId+" textarea[name="+err_field+"]");
				}
				
				var div_err = $("#"+err_field+"_err");
				
				// если div-а для ошибки нет, создаем его
				if (!div_err.length) {
					div_err = $("<div id="+err_field+"_err style='color:#FF0000;display:none'></div>");
					field.after(div_err);
				}  				
				
				div_err.html(err_text);
				div_err.show();
			
			});
		}
	});
}

function checkImage(filename)
{
    return true;
	
	//var pattern = /[\w]+\.(gif|jpg|bmp|png|jpeg)$/gi;
	var pattern = /[А-Яа-яA-Za-z0-9_]+\.(gif|jpg|bmp|png|jpeg)$/gi;
    
    res = pattern.test(filename);
	if (res) {
		return true;
    }
    else {
        alert("Это не изображение");
        return false;
    }
}

function validateLogin()
{
    form = $("main_auth");
	login = $("#main_login").val();
	password = $("#main_password").val();
	
	var a = [];
    a.push({name: 'login', value: login});
	a.push({name: 'password', value: password});
	
	r = true;
	
	$.post("/user/validate", a,
		function(data) {
		    if ($("result", data).text() == "ValidErrors") {
				
				alert("Неверный логин или пароль");
				r = false;
				
			}
			else {
				//r = true;
				alert("fdfd: "+r);
			}
		}
	);
	
	//alert(r);
	
    return r;
}

function equalHeight(group) {
  tallest = 0;
  group.each(function() {
    thisHeight = $(this).height();
    if(thisHeight > tallest) {
      tallest = thisHeight;
    }
  });
  group.height(tallest);
}

$(document).ready(function() {
  //equalHeight($(".eq"));
});

function checkMessages() {
	
	// проверяем входящие
	$.get("/messages/getmyinbox.ajax", function(data) {
        
        $("message", data).each(function(i){
			
			l = $(".jgrowl_message").length;
			
			// Не больше трех сообщений на экране
			if (l >= 3) { return; }
			
            c = $("content", this).text();
			url = $("url", this).text();
			h = $("header", this).text();
     	    id = $(this).attr("id");
			post_time = $(this).attr("post_time");
			
			// Не выводим, если такое сообщение уже показано
			if ($("#growl_msg_"+id).length > 0) {
				return;
			}
			
			// Заголовок и контент
			h = "<span id='growl_head_"+id+"' style='display:block; cursor: pointer;'>"+h+"</span>";
			
			//if (url.length > 0) {
				c = "<span id='growl_msg_"+id+"' style='display:block; cursor: pointer;'><a href='"+url+"'>"+c+"</a></span>";
			/*}
			else {
				c = "<span id='growl_msg_"+id+"' style='display:block;'>"+c+"</span>";
			}*/
            
            $.jGrowl(c, { header: h, sticky: true, closer: false,
				position: 'bottom-right',
				close: function(e,m,o) {
					//alert(o.message_id);
					var a = [];
					a.push({name: 'id', value: o.message_id});
					$.post("/messages/setread", a);
				},
				message_id: id
				});
			
			$("#growl_head_"+id).click( function() {
				window.location = url;
			});
			$("#growl_msg_"+id).click( function() {
				window.location = url;
			});
        }
        );
		
	});
	
}

// проверка сообщений по таймеру
$(document).ready(function() {
  checkMessages();
  setInterval(function(){
	
	checkMessages();
	
  }, 60000);
});

function checkFlashPopups() {
	
	// проверяем всплывающие флэш-сообщения
        
	$("#flash_popups li").each(function(i){
		
		var c = $(this).html();
		
		$.jGrowl(c, { header: '',
			life: 6000, glue: 'before', theme: 'notice_theme'
			});
	}
	);
	
	$("#flash_popups").remove();
	
}

// проверка всплывающих флэш-сообщений при загрузке
$(document).ready(function() {
  checkFlashPopups();
});

function initUserPopup(el, data, authorized){
	
	overUserPopup = false;
	
	el.hover(function(){
		
		// ...
		
	 },
	 function(){
		setTimeout(function(){
		    if (!overUserPopup)
				$("#user_popup_"+data.id).remove();
		}, 300);
		return false;
	 });
  
    el.bind("mousemove mouseenter", function(e) {
		
		if ($("#user_popup_"+data.id).length > 0) {
		  
		  //var pop = $("#user_popup_"+data.id);
		  //var mouseY = e.pageY;
		  //pop.css("top", mouseY-25);
		  return false;
		  
		}
		
		$(".user_popup").remove();
		
		html = "";
		//html += "<h2>"+data.name+" ("+data.login+")</h2>";
		//html += "<a class='username'>"+data.name+" ("+data.login+")</a><hr class='space' />";
		html += "<div class='user_popup_rating'>Рейтинг: "+data.rating+"</div>";
		html += "<div class='user_popup_reviews'>Обзоров написал: "+data.reviews+"</div>";
		
		pop = $("<div class='user_popup' id='user_popup_"+data.id+"'></div>");
		pop.html(html);
		
		if (authorized) {
				maila = $("<a href='#'><div class='user_popup_message'>Написать личное сообщение</div></a>");
				maila.click(function() {
					$(this).parent().remove();
					showMessageForm(data.id, data.name, data.login);
					return false;
				});
				pop.append(maila);
		}
		
		pop.appendTo("body");
		
		pop.hover(function() {
		    
			overUserPopup = true;
		},
		function() {
		    
			overUserPopup = false;
			
			setTimeout(function(){
				$("#user_popup_"+data.id).remove();
		    }, 300);
		}
		);
		
		var p = $(this).position();
		pop.css("top", p.top);
		pop.css("left", p.left+$(this).width());
		pop.show();
		
		return false;
	});
	
}

// ======= Форма логина ===
var loginForm = {
    
	init: function(){
		$("#login_openid_link").click(function(){ loginForm.gotoOpenId();  return false; });
		
		$("#login_our_link").click(function(){ loginForm.gotoAfishing(); return false; });
		
		$("#login_ya_link").click(function(){ loginForm.gotoYandex(); return false; });
		
		$("#login_lj_link").click(function(){ loginForm.gotoLJ(); return false; });
	},
	
	gotoOpenId: function(){
		$(".login_tab").hide();
		$("#openid_login").fadeIn(500);
	},
	
	gotoLJ: function(){
		$(".login_tab").hide();
		$("#lj_login").fadeIn(500);
	},
	
	gotoYandex: function(){
		$(".login_tab").hide();
		$("#ya_login").fadeIn(500);
	},
	
	gotoAfishing: function(){
		$(".login_tab").hide();
		$("#our_login").fadeIn(500);
	}
	
}

// ======= Код для вставки в блоги ===
var informers = {
    
	getEventsInformer: function(city_id) {
		return "<script type='text/javascript' src='http://www.afishing.ru/informers/events/city_id/"+city_id+".js'></script>"
	},
	
	showInformer: function(url, scrpt){
		
		$('#informer').remove();
		
		div = $("<div id='informer' style='text-align: center;'><p>Загрузка...</p></div>");
		div.hide();
		
		div.appendTo($("body"));
		
		if (scrpt) {
				
				data = "<script type='text/javascript' src='http://www.afishing.ru"+url+".js'></script>";
				
				$('#informer').empty();
				$("<p>Скопируйте и вставьте нижеприведенный код в свой блог</p>").appendTo($('#informer'));
				$("<textarea style='width: 430px; height: 120px;' onclick='this.select()'></textarea>")
					.val(data)
					.appendTo($('#informer'));
					
				tb_show('Код для вставки','#TB_inline?height=220&width=460&inlineId=informer');
				
		}
		
		else {
				$.get(url, function(data){
					
					$('#informer').empty();
					$("<p>Скопируйте и вставьте нижеприведенный код в свой блог</p>").appendTo($('#informer'));
					$("<textarea style='width: 430px; height: 120px;' onclick='this.select()'></textarea>")
						.val(data)
						.appendTo($('#informer'));
						
					tb_show('Код для вставки','#TB_inline?height=220&width=460&inlineId=informer');
					
				});
		}
		
	},
	
	showReviewInformer: function(id){
		informers.showInformer('/informers/review/id/'+id);
	},
	
	showEventInformer: function(id){
		informers.showInformer('/informers/event/id/'+id, true);
	},
	
	showImageInformer: function(id){
		informers.showInformer('/informers/image/id/'+id);
	}
	
}

// Активация различных контролов
$(document).ready(function() {
  
		// Закрытие высплывающих блоков по клику вне
		overInlineWnd = false;
		$("body").click(function() { if(!overInlineWnd) {closeAllNiceForms();}});
		
		// Форма логина
		loginForm.init();
  
		// Шапка сайта: поиск
		$("#main_find_text_e").blur(function(){
			this.value==''?this.value='Поиск по наименованию':'';
			if (this.value=='Поиск по наименованию') $(this).addClass('inactive_input');
			else $(this).removeClass('inactive_input');
		});
			
		$("#main_find_text_e").click(function(){
			this.value=='Поиск по наименованию'?this.value='':'';
			if (this.value=='Поиск по наименованию') $(this).addClass('inactive_input');
			else $(this).removeClass('inactive_input');
		});
		
		// Шапка сайта: выбор города
		$("#main_city_id").change(function(){
			$("#main_city").submit();
		});
  
		// Ввод времени
		$(".input_hours").blur(function(){
			  var i = parseInt(this.value);
			  if (i == 0) return;
			  this.value = isNaN(i) ? '00' : (i > 23) ? 23 : (i < 0) ? '00' : (i < 10) ? '0' + i : i;
		   });
		
		$(".input_minutes").blur(function(){
			  var i = parseInt(this.value);
			  if (i == 0) return;
			  this.value = isNaN(i) ? '00' : (i > 59) ? 59 : (i < 0) ? '00' : (i < 10) ? '0' + i : i;
		   });
		
		// Ввод даты
		$(".date").datePicker();
		
		// Активирует thickbox для ссылок
		tb_init('a.link_popup_image');//pass where to apply thickbox
		  
		// Шапка сайта: анимация меню
		/*$("#main_navigation_e a").hover(function(){
			  $(this).stop().animate({ backgroundColor: '#fdbe52', color: "#000000" }, 500);
		   },
		   function(){
			  $(this).stop().animate({ backgroundColor: '#ffffff', color: "#1c64b0" }, 1000);
		   });*/
  
});




















