// detect IE6
var isRunningIE6 = false /*@cc_on || @_jscript_version < 5.7 @*/;
// detect IE6-7
var isRunningBadIE = false /*@cc_on || @_jscript_version < 5.8 @*/;
var aniT=(isRunningBadIE)?250:350;
var cur;
var isCur;

if (isRunningBadIE){
	$(window).resize(function() {
		$("#n").css({position:""}).css({position:"relative"});
	});
}

$(document).ready(function() {
	// ррровняйсь, смирррно!
	
	$("#n>li:nth-child(1)>a").css({position:"absolute",left:"30px", width:"69px"});//30
	$("#n>li:nth-child(2)>a").css({position:"absolute",left:"212px", width:"76px"})//212
	$("#n>li:nth-child(3)>a").css({position:"absolute",left:"401px", width:"80px"});//401
	$("#n>li:nth-child(4)>a").css({position:"absolute",left:"594px", width:"104px"});//586
	$("#n>li:nth-child(5)>a").css({position:"absolute",left:"812px", width:"99px"});//804
	
	isCur = ($('#n>li').hasClass('here') || $('#n>li').hasClass('parent_here'))?true:false;

		// set cur проверим есть ли каррент? и назначим ролловеры
		if(isCur){
				cur = ($('#n>li.here a').length)?$('#n>li.here'):$('#n>li.parent_here');
				setTimeout(function(){drDwn(cur.children('a'))},100);
				$("#n").bind("mouseleave", function(e){
					//var cur = ($('#n>li.here a').length)?$('#n>li.here'):$('#n>li.parent_here');
					$(cur.children('a')).parent('li').children('ul').fadeIn(aniT);
				});
			}
	
			$("#n>li").bind("mouseleave", function(e){ 	
					//if (!$(this).hasClass('here')) drUp(this);
					if (!$(this).hasClass('here') && !$(this).hasClass('parent_here')) drUp(this);
			});
			$("#n>li>a").bind("mouseover", function(e){
					//if (!$(this).parent('li').hasClass('here')) 
					drDwn(this);
			});	
		
		// build footer nava
		$("#fn").html($("#n").html()).find('a').removeAttr('style');
		//$("#fn a").removeAttr('style');
		$("#fn>li:nth-child(2)").height($("#fn>li:nth-child(1)").height());
		
		//vab
		$(".vab1").setVAB();
		$(".vab2").setVAB();
		$(".vab3").setVAB();
		$(".vab4").setVAB();
		$(".vab5").setVAB();
		
		$(".rndc").setFixedRoundCorner();
		
		//n2l
		$("#n2l>li:nth-child(1),#nb2l>li:nth-child(1)").addClass('first');
		$("#nb2l>li:last").addClass('last');
		$("#n2l>li.here,#nb2l>li.here").each(function() {
			if($(this).hasClass('first')) $(this).addClass('curFirst');
			if($(this).hasClass('last')) $(this).addClass('curLast');
		});
		
			$("#n2l>li,#nb2l>li").bind("mouseleave", function(e){ 	
			if($(this).hasClass('first')) {
				$(this).removeClass('fR');
				if (isRunningIE6) $(this)[0].style['backgroundPosition'] = '0px 0px';
			}
			else if($(this).hasClass('last')) {
				$(this).removeClass('lR');
				if (isRunningIE6) $(this)[0].style['backgroundPosition'] = '0px -74px';
			}
			else if(!$(this).hasClass('here')){ 	
				$(this).removeClass('R');
				if (isRunningIE6) $(this)[0].style['backgroundPosition'] = '0px -37px';
				}
		});
				
		$("#n2l>li,#nb2l>li").bind("mouseenter", function(e){
		
			if($(this).hasClass('first')) {
				$(this).addClass('fR');
				if (isRunningIE6) $(this)[0].style['backgroundPosition'] = '0px -111px';
				}
			else if($(this).hasClass('last')) {
				$(this).addClass('lR');
				if (isRunningIE6) $(this)[0].style['backgroundPosition'] = '0px -185px';
				}
			else {
				$(this).addClass('R');
				if (isRunningIE6) $(this)[0].style['backgroundPosition'] = '0px -148px';
				}
			
		});	
		
		//route
		$('.gR').growToRight();
		$('.gL').growToLeft();
		
		$('.i-slider').Listalka();
		

	// hide
	//$('.toggle').click(function () {
	$(".toggle").live("click", function(){
		$(this).next('div').slideToggle(aniT);
	  	return false;
    }).each(function () {
		var o = $(this);
        $(this).wrapInner('<b></b>').children('b').css({borderBottom:'1px dashed '+jQuery.curCSS(this,"color")});  
      }).next('div').hide();
	
	$.localScroll({duration:600,easing:'easeOutQuart'});
	
	
	// галерея у продуктов
	$("div.g_6 div div div.g_2:nth-child(3n)").addClass('last');
	
	$( '#srt' ).scrollFollow(
					{
						speed: 500,
						offset: 10,
						easing: 'easeOutExpo'
					}
				).parent('.g_4').height($( '#srt' ).parent('.g_4').prev('.g_8').height());
	$( '#srt p a' ).click(function(){
		var loc_hash = $('#'+$(this).attr('href').split('#')[1]);
		locHash(loc_hash);
		});
	
});
// READY

$(window).load(function(){
	// apply transparent png for IE6
	if (isRunningIE6) {
		DD_belatedPNG.fix("#n2l li, .png");
		}
});

// for route
$(window).resize(function(){
		$('.gR').growToRight();
		$('.gL').growToLeft();
});

//listalka

;(function($) {
	$.fn.Listalka = function() {
		return this.each(function() {

		
			var o = this;

		
				if (!isMSIE) $(o).find('a.prev').css({opacity:'0',cursor:'default'});
				else $(o).find('a.prev').hide();
				
				var p = $(o).find('.i>ul>li').length; // calculate slider "items"
				if (p<=1) { //hide slider nav
					$(o).find('.prev, .next').remove();
				}
				
				$(o).find('.i>ul').width((p*$(o).attr('rel'))-0); // make all pages length
				$(o).serialScroll({
					target:'.i',
					items:'li',
					prev:'a.prev',
					next:'a.next',
					offset:0, //when scrolling to photo, stop 230 before reaching it (from the left)
					start:0, //as we are centering it, start at the 2nd
					duration:600,
					//interval:2400,
					force:true,
					stop:true,
					lock:false,
					//exclude:2,
					cycle:false, //don't pull back once you reach the end
					easing:'easeOutQuart', //use this easing equation for a funny effect
					jump: false, //click on the images to scroll to them
					onBefore:function( e, elem, $pane, $items, pos ){
						if (pos+2>p) {
								if (!isMSIE) $(o).find('a.next').css({cursor:'default'}).animate( { opacity:'0' }, { queue:false, duration:300 } );
								else $(o).find('a.next').hide();
							}else{
								if (!isMSIE) $(o).find('a.next').css({cursor:'hand',cursor:'pointer'}).animate( { opacity:'1' }, { queue:false, duration:300 } );
								else $(o).find('a.next').show();
							}
						if (pos<1) {
								if (!isMSIE) $(o).find('a.prev').css({cursor:'default'}).animate( { opacity:'0' }, { queue:false, duration:300 } );
								else $(o).find('a.prev').hide();
							}else{
								if (!isMSIE) $(o).find('a.prev').css({cursor:'hand',cursor:'pointer'}).animate( { opacity:'1' }, { queue:false, duration:300 } );
								else $(o).find('a.prev').show();
							}						
					},
					onAfter:function( elem ){}
				});
			
		
		
		});
	};
})(jQuery);



;(function($) {
	$.fn.setFixedRoundCorner = function() {
		return this.each(function() {
				var css = $(this)[0].className;
				$(this).after('<div class="rndcB B'+css.replace(/rndc /,'')+'">&nbsp;</div>');
		});
	};
})(jQuery);

;(function($) {
	$.fn.growToRight = function() {
		return this.each(function() {
			if (!$.data(this, 'processed')) {	
				$(this).before('<br clear="all" /><b style="float:left;" />');	
				$(this).css({background:'url('+$(this).attr('src')+')'}).attr('src','/i/d.png');
				$.data(this, 'processed', true);
			}	
			$(this).width($(window).width()-$(this).prev('b').offset().left);
		});
	};
})(jQuery);

;(function($) {
	$.fn.growToLeft = function() {
		return this.each(function() { 
		
			if (!$.data(this, 'processed')) {		//,marginLeft:-($(this).offset().left)
				$(this).before('<br clear="all" /><b style="float:left;" />');
				$(this).after('<p style="float:right;" /><br clear="all" />');
				$(this).css({background:'url('+$(this).attr('src')+')',backgroundPosition:'right'}).attr('src','/i/d.png');
				$.data(this, 'processed', true);
			}
			$(this).width($(this).next('p').offset().left).css({marginLeft:-($(this).prev('b').offset().left)});
		});
	};
})(jQuery);
// \\

// вертикально по низу
;(function($) {
	$.fn.setVAB = function(minHeight, maxHeight) {
		tallest = (minHeight) ? minHeight : 0;
		this.each(function() {
			if($(this).height() > tallest) {
				tallest = $(this).height();
			}
		});
		if((maxHeight) && tallest > maxHeight) tallest = maxHeight;
		return this.each(function() {
			//$(this).height(tallest).css("overflow","auto");
			$(this).height(tallest).wrapInner("<b></b>");
		});
	};
})(jQuery);

var drDwn =  $.debounce(function(o) {
		var e = $(o).parent('li')[0];
		if (!$.data(e, 'fussy')) {
		
			if(isCur){
				//var cur = ($('#n>li.here a').length)?$('#n>li.here'):$('#n>li.parent_here');
				if ($("*").index(o)!=$("*").index($(cur.children('a')))) $(cur.children('a')).parent('li').children('ul').fadeOut(aniT);
			}
			
			$(o).parent('li').children('ul').fadeIn(aniT);
			if (!$.data(o, 'firstTime')) {
				var w=0;
				$(o).parent('li').children('ul').addClass($(o).attr('href').replace(/\/+/g,""));
				$(o).next('ul').children('li').each(function (i) {
		        	w+=$(this).width();
		      	});
				$(o).next('ul').children('li:nth-child(1)').css({marginLeft:(($("#n").width()-w)*0.5)+'px'});
			}
			$.data(o, 'firstTime', true);
		}
		
}, 100,false);

var drUp = function(o) {
		$(o).children('ul').fadeOut(aniT);
		$.data(o, 'fussy', true);
		setTimeout(function(){$.data(o, 'fussy', false);},150);
};

// Easing equation, borrowed from jQuery easing plugin
// http://gsgd.co.uk/sandbox/jquery/easing

$.easing.easeOutQuart = function (x, t, b, c, d) {
	return -c * ((t=t/d-1)*t*t*t - 1) + b;
};

$.easing.easeOutExpo = function (x, t, b, c, d) {
	return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
};





// Publish
function validate_publish_form(formData, jqForm, options)
{
	var form = jqForm[0]; 
	var reEmail = /^[0-9a-z\-_\.]*@[0-9a-z \-_\.]*\.[a-z]{2,5}$/i;
	if(!form.title.value.length)
		{
			alert("Укажите Заголовок"); form.title.focus(); return false;
		}
	
	if(!form.field_id_41.value.length)
		{
			alert("Текст забыли..."); form.field_id_41.focus(); return false;
		}
	
	$("#re_publish_form").html('<img src="/i/ajaxLoader.gif" width="16" height="16" id="snake">');
}

$(document).ready(function() { 
	$("#publish").live("submit", function(){
	//$("#publish").submit(function() {
		 $(this).ajaxSubmit({ 
			
			beforeSubmit: validate_publish_form,
			//target: '#result',
			success: function(responseText, statusText){
												$("#re_publish_form").html('');
												var reg=/\s*Спасибо/gi
												var result=reg.test(responseText) ? 1 : 0; 
												if(result){
													$.jGrowl(responseText, { 
														life: 5000,
														beforeClose: function(e,m) {
													        $.nyroModalRemove();
													    }
													});
												}else{
													$.jGrowl(responseText, { 
														life: 5000 
													});
												}
											}
			
			});
		  return false;
	    });
});




// FAQ
//function validate_qaf_form(form)
function validate_qaf_form(formData, jqForm, options)
{
	var form = jqForm[0]; 
	var reEmail = /^[0-9a-z\-_\.]*@[0-9a-z \-_\.]*\.[a-z]{2,5}$/i;
	if(!form.qa_name.value.length)
		{
			alert("Укажите ваше имя"); form.qa_name.focus(); return false;
		}
	
	if(!form.qa_email.value.length)
		{
			alert("Укажите ваш email"); form.qa_email.focus(); return false;
		}
	
	if(!reEmail.test(form.qa_email.value))
		{
			alert("Не похоже, что это корректный email"); form.qa_email.focus(); return false;
		}
	
	if(!form.qa_message.value.length)
		{
			alert("А как же вопрос?"); form.qa_message.focus(); return false;
		}
	//form.submit()
	$("#tnx").html('');
	$("#re_qaf_form").html('<img src="/i/ajaxLoader.gif" width="16" height="16" id="snake">');
}
/*
$("#qaf").submit(function() {
	  validate_qaf_form(this);
	  return false;
    });
*/	
$(document).ready(function() { 
	$("#qaf").live("submit", function(){
	//$("#qaf").submit(function() {
		 $(this).ajaxSubmit({ 
			
			beforeSubmit: validate_qaf_form,
			//target: '#result',
			success: function(responseText, statusText){
												$("#re_qaf_form").html('');
												var reg=/\s*<jGrowl>/gi
												var result=reg.test(responseText) ? 1 : 0; 
												if(!result){
													$('#result').html(responseText);
												}else{
													$.jGrowl(responseText, { 
														life: 5000 
													});
												}
											}
			
			});
		  return false;
	    });
});



// Auth
//function validate_af_form(form)
function validate_af_form(formData, jqForm, options)
{
	var form = jqForm[0]; 
	var reEmail = /^[0-9a-z\-_\.]*@[0-9a-z \-_\.]*\.[a-z]{2,5}$/i;
	if(!form.username.value.length)
		{
			alert("Веведите логин"); form.username.focus(); return false;
		}
	
	if(!form.password.value.length)
		{
			alert("Введите пароль"); form.password.focus(); return false;
		}
	//form.submit()
	$("#re_af_form").html('<img src="/i/ajaxLoader.gif" width="16" height="16" id="snake">');
}
/*
$("#qaf").submit(function() {
	  validate_qaf_form(this);
	  return false;
    });
*/	
$(document).ready(function() { 
	$("#af").live("submit", function(){
	//$("#qaf").submit(function() {
		 $(this).ajaxSubmit({ 
			
			beforeSubmit: validate_af_form,
			//target: '#result',
			success: function(responseText, statusText){
												$("#re_af_form").html('');
												var reg=/\s*<h4>Спасибо/gi
												var result=reg.test(responseText) ? 1 : 0; 
												if(result){
													location.href=location.href;
												}
													$.jGrowl(responseText, { 
														life: 5000 
													});
												
											}
			
			});
		  return false;
	    });
});

// Comment
//function validate_bcmnt_form(form)
function validate_bcmnt_form(formData, jqForm, options)
{
	var form = jqForm[0]; 
	var reEmail = /^[0-9a-z\-_\.]*@[0-9a-z \-_\.]*\.[a-z]{2,5}$/i;
	if(!form.comment.value.length)
		{
			alert("Веведите комментарий"); form.comment.focus(); return false;
		}
	$("#re_bcmnt_form").html('<img src="/i/ajaxLoader.gif" width="16" height="16" id="snake">');
}
$(document).ready(function() { 
	$("#bcmnt").live("submit", function(){
		 var url = '/blog/ajax_comments_template/'+$("input[name=entry_id]",this).val();
		 $("input[name=RET]",this).val('/blog/ajax_submit_result/');
		 $(this).ajaxSubmit({ 
			//target:'#re_comment',
			url:'/blog/ajax_submit_result/',
			beforeSubmit: validate_bcmnt_form,
			success: function(responseText, statusText){
						if(responseText == ""){
							$('#comments_container').load(url,function(){
								//$('#comments_container em:nth-child('+($('#comments_container em').length+1)+')').fadeOut(0).fadeIn(300);
							});
						}else{
							$.jGrowl(responseText, {
								life :5000
							});
							$('#comments_container').load(url,function(){
								//
							});
						}
					}
			});
		  return false;
	    });
});

//lightbox

$(function() {
	  $.fn.nyroModal.settings.processHandler = function(settings) {
	    var from = settings.from;
		 $.nyroModalSettings({
	        url: from.href		
	      });
	  };
	  
	  $.fn.nyroModal.settings.hideBackground = function(elts, settings,callback) {
						elts.bg.fadeOut(100,callback);
					}
	  $.fn.nyroModal.settings.hideContent = function(elts, settings,callback) {
						elts.contentWrapper.fadeOut(100,callback);
					}
	  
	});

	
	
//location highlight
$(document).ready(function() { 
	if (location.hash) {
		var loc_hash = $(location.hash);
		locHash(loc_hash);
		}
});
	
function locHash(loc_hash){
		loc_hash.each(function () {
			loc_hashColor= jQuery.curCSS(this,"color");
		});
		//if (loc_hashColor) 
		loc_hash.css({color:loc_hashColor,backgroundColor: '#FFF'}).animate({backgroundColor: loc_hashColor,color: '#fff'},500).animate({backgroundColor: loc_hashColor,color: '#fff'},1000).animate({backgroundColor: '#fff',color: loc_hashColor},3000,'easeOutQuart');
}
