// expand jquery 
$.fn.hasAttr = function(name) {  
   return this.attr(name) !== undefined;
};


function customAjax(action, data, callback, fallback)
{
	$.ajax({
		type: "POST",
	    url: action,  //new
	    data: data,
		success : function(data)
		{
			if (callback) { callback(data); }
		},
		error : function(data)
		{
			if (fallback) { fallback(); }
		}
	});
}

function makePopup(el, closeRelationPath)
{
	var pos = {};
	
	// calc pos
	$(el).css({
		left : ($(window).width() - $(el).width()) / 2,
		top : ($(window).height() - $(el).height()) / 2 + $(window).scrollTop(),
		display : 'block',
		zIndex : 1001
	}).append('body');
	
	var bg = $('<div class="popupBg"></div>').css({
		width : $(document).width(),
		height : $(document).height(),
		position : 'absolute',
		zIndex : 1000,
		background : '#000',
		opacity : 0.6,
		top : 0,
		left : 0
	});
	$('body').append(bg);
	
	// dynamic top to el
	$(window).scroll(function(){
		$(el).css('top', ($(window).height() - $(el).height()) / 2 + $(window).scrollTop());
	});
	
	// dynamic repositon on resize
	$(window).resize(function(){
		$(el).css({
			left : ($(window).width() - $(el).width()) / 2,
			top : ($(window).height() - $(el).height()) / 2 + $(window).scrollTop()
		});
		
		$(bg).css({
			width : $(window).width()
		});
	});
	
	$(bg).click(function(){ $(bg).remove(); $(el).hide(); });
	$(el).find(closeRelationPath).click(function(){ $(bg).remove(); $(el).hide(); });
}

function regAuth(type)
{
	if( type == 'auth' ){
		$('#reg_popup').addClass('collapsed');
		$('#auth_popup').removeClass('collapsed'); 
	} else {
		$('#auth_popup').addClass('collapsed');
		$('#reg_popup').removeClass('collapsed'); 
	
		// добавляем код зеропикселя 
		$('#reg_popup').append('<img src="http://ad.adriver.ru/cgi-bin/rle.cgi?sid=176542&sz=registr&bt=21&pz=0&rnd=1534693997" border=0 width=1 height=1>');
		
	}
	
	makePopup($('#regAuth'), '.close');
}

// textarea autogrow
(function($) {
    $.fn.autogrow = function(options) {
        this.filter('textarea').each(function() {
            var $this       = $(this),
                minHeight   = $this.height(),
                lineHeight  = $this.css('lineHeight');
            
            var shadow = $('<div></div>').css({
                position:   'absolute',
                top:        -10000,
                left:       -10000,
                width:      $(this).width() - parseInt($this.css('paddingLeft')) - parseInt($this.css('paddingRight')),
                fontSize:   $this.css('fontSize'),
                fontFamily: $this.css('fontFamily'),
                lineHeight: $this.css('lineHeight'),
                resize:     'none'
            }).appendTo(document.body);
            var update = function() {
                var times = function(string, number) {  for (var i = 0, r = ''; i < number; i ++) r += string;  return r; };
                var val = this.value.replace(/</g, '&lt;')
                                    .replace(/>/g, '&gt;')
                                    .replace(/&/g, '&amp;')
									.replace('<br>', '')
                                    .replace(/\n$/, '<br/>&nbsp;')
                                    .replace(/\n/g, '<br/>')
                                    .replace(/ {2,}/g, function(space) { return times('&nbsp;', space.length -1) + ' ' });
                
                shadow.html(val);
                $(this).css('height', Math.max(shadow.height() + 20, minHeight));
            }
            
            $(this).change(update).keyup(update).keydown(update);
            update.apply(this);
        });
        return this;
    }
})(jQuery);


$(function () {
	
	// pos Vs in MainMenu
	$(window).resize(function(){
		if ($('#mainmenu li.active').length == 0) { return false; }
		$('#mainmenu div.v').css('left', $('#mainmenu li.active').offset().left + ( $('#mainmenu li.active').width() / 2 ) ).show(); 
	}).resize();
	
	// TabController scripts. Init all tabcontrollers
	$('.tabcontroller .menu li').each(function(){ 
		$(this).find('div.v').css('margin-left', $(this).width() / 2 - 4 ); 
		$(this).find('.splashcount').css('margin-left', $(this).width() - 10 ).show();
	});
	$('.tabcontroller').each(function(){
		if ($(this).hasClass('static')) { return; }
		var parent = this;
		$(this).find('.menu li').each(function(){
			$(this).click(function(){
				$(parent).find('.tab').removeClass('active');
				$(parent).find('.menu li').removeClass('active');
				$(parent).find('.tab[rel='+$(this).attr('rel')+']').addClass('active');
				$(parent).find('.menu li[rel='+$(this).attr('rel')+']').addClass('active');
				$(parent).find('.menu li[rel='+$(this).attr('rel')+']').find('.splashcount').remove();
				
				// load data
				var tab = $(parent).find('.tab[rel='+$(this).attr('rel')+']');
				if( tab.hasAttr('action') )
				{
					tab.load(tab.attr('action'));
				}
			});
		});
	});
	
	// Add Shadows
	$(".textshadow, .infobox .header h3").prepend('<em class="shadow"></em>').each(function() { $(this).find('em').text($(this).text()); });
	
	// Calc TopMenu Splashes
	$('#mainmenu a').each(function(){ 
		var splash = $(this).find('.splashcount'); 
		if (splash)
		{
			splash.css('margin-left', $(this).width() - 9).show();
		}
	})

	// Calc Comments icon pos on photoposts
	$('.photopost div.over').each(function(){
		
		var parent = this;
		$(this).find('h4 a').each(function(){
			var text = $(this).html();
			text = text.split(' ');
			a = [];
			for (var i in text) { a.push('<span>'+text[i]+'</span>'); }
			$(this).html(a.join(''));
			
			if (!$(this).find('.comments')) { return; }
			
			
			var previews = false;
			var ready = false;
			
			// define last span in photopost title
			$(this).find('span').each(function(){
				
				// this is it!
				if (!ready && previews && $(this).offset().top != previews.offset().top)
				{
					// configure comments icon pos, based on title's last word on first row pos 
					$(parent).find('.comments').show();
					$(parent).find('.comments').css('left', previews.position().left + previews.width() - ( $(parent).find('.comments').width() - 19 ) ).show();
					ready = true;
				}
				
				previews = $(this);
			});
			
			if (!ready)
			{
					$(parent).find('.comments').css('left', previews.position().left + previews.width() - ( $(parent).find('.comments').width() - 19 ) ).show();
			}
			previews = false;
		});
	});
	
	$('.infobox').each(function(){
		
		var parent = this;
		// settings
		$(this).find('i.gear').click(function(){
			
			if ($(parent).hasClass('collapsed')) { return false; }
			if ($(parent).hasClass('settings'))
			{
				$(parent).removeClass('settings');
				$(parent).find('.settingsbox').fadeOut(200, function(){ $(this).remove(); });
				return;
			}
				$(parent).addClass('settings');
				
				var items_count = $(parent).find('.items_count').val();
				
				$(parent).find('.infobox_container').prepend($('#settings_proto').find('.settingsbox').clone());
				$(parent).find('.settingsbox .rowcount').val( items_count );				
				$(parent).find('.settingsbox').fadeIn(200);
				$(parent).find('.settingsbox .cancel').click(function(){ $(parent).find('i.gear').click(); });
				$(parent).find('.settingsbox .save').click(function(){
					
					var rowCount = $(parent).find('.settingsbox .rowcount').val();
					customAjax('/index/save_settings', {
							id : $(parent).attr('rel'),
							rowCount : rowCount,
							checkbox : $(parent).find('.settingsbox .checkbox').is(':checked')
						});
					$(parent).find('.items_count').val( rowCount );
					$(parent).removeClass('settings');
					$(parent).find('.settingsbox').fadeOut(200, function(){ $(this).remove(); });
					window.location.reload();
				});
		});
		
		// collapse expand
		$(this).find('i.collapse').click(function(){
			
			if ($(parent).hasClass('collapsed'))
			{
				$(parent).removeClass('collapsed');
				return;
			}
				$(parent).addClass('collapsed');
		});
	});
	
	
	// Dragndrop
	$('.col .dropzone').sortable({
		connectWith: '.col .dropzone',
		handle: '.header',
		cursor: 'move',
		placeholder: 'placeholder',
		forcePlaceholderSize: true,
		opacity: 0.4,
		start : function()
		{
			// cyns colsize
			var maxHeight = 0;
			$('.col').each(function(){
				var height = $(this).height();
				if (maxHeight < height) { maxHeight = height; }
			});
			$('.col .dropzone').height(maxHeight);
		},
		stop: function(event, ui){
			$(ui.item).find('.header').click().disableSelection();
			
			var data = {};
			$('.col .dropzone').each(function(){ data[$(this).attr('rel')] = $(this).sortable('toArray'); });
			customAjax('/index/blocks_order', data);
			
			
			// cyns colsize
			var maxHeight = 0;
			$('.col').each(function(){
				var height = $(this).height();
				if (maxHeight < height) { maxHeight = height; }
			});
			$('.col .dropzone').height('auto');
		}
	})
	
	// Introduce Close
	$('#introduce_customization i').click(function(){
		$('#introduce_customization').hide();
		customAjax('closeIntroduce', 'close');
	});
	
	// Init calendar
	$('.calendar').each(function(){
	
		this.month = 
		[
			'Январь',
			'Февраль',
			'Март',
			'Апрель',
			'Май',
			'Июнь',
			'Июль',
			'Август',
			'Сентябрь',
			'Октябрь',
			'Ноябрь',
			'Декабрь'
		];
	
		var self = this;
		this.current = $(this).find('.month').attr('rel');
		this.next = function()
		{
			if (this.current < 11) { this.current++; } else { return; }
			$(this).find('.month span').html(this.month[this.current]);
			$(this).find('.month').attr('rel', this.current);
			this.load();
		}
		
		this.previous = function()
		{
			if (this.current > 0) { this.current--; } else { return; }
			$(this).find('.month span').html(this.month[this.current]);
			$(this).find('.month').attr('rel', this.current);
			this.load();
		}
		
		this.load = function()
		{
			customAjax('/people/getProfileCal/'+$(self).attr('rel'), { month : this.current }, function(data){
				$(self).find('dl.events').html(data);
			});
		}
		
		$(this).find('.arrow_left').click(function(){ self.previous(); });
		$(this).find('.arrow_right').click(function(){ self.next(); });
	});
	
	// Vote button
	$('#profile .rating .vote').click(function(){
		customAjax('voteUser', { UserId : $('#profile').attr('rel') }, function(data){
			$(self).find('dl.events').html(data);
		});
	});
	
	
	// if AjaxUpload is enabled
	if (typeof(window['AjaxUpload']) != "undefined")
	{
		// INIT UPLOAD AVA ON PROFILE_EDIT
		if ($('#profile').length > 0)
		{
			new AjaxUpload($('#profile.edit .ava a'), {
				action: '', // tune here. Сюда ты принимаеш аватар. В ответ плюеш ссылкой на пикчу
				name: 'image',
				data: { ajax: 'image' },
				autoSubmit: true,
				responseType: false,
				onSubmit:function(file , ext)
				{
					if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext)))
					{
						alert('Данный формат файла не поддерживается: '+ext);
						return false;
					}
				},
				onComplete: function(file, response)
				{
					$('#profile.edit .ava img').attr('src', response)
				}
			});
		}
		
		// INIT UPLOAD AVA ON PROFILE_EDIT
		if ($('#addrecipe').length > 0)
		{
			new AjaxUpload($('#addrecipe input.photo'), {
				action: 'backend.php?action=addPhoto', // tune here. Сюда ты принимаеш аватар. В ответ плюеш ссылкой на пикчу
				name: 'image',
				data: { ajax: 'image' },
				autoSubmit: true,
				responseType: false,
				onSubmit:function(file , ext)
				{
					if (! (ext && /^(jpg|png|jpeg|gif)$/.test(ext)))
					{
						alert('Данный формат файла не поддерживается: '+ext);
						return false;
					}
				},
				onComplete: function(file, response)
				{
					var box = $('<div class="photo"><a class="remove"></a><img width="150px" height="100px" src="'+response+'"/><input type="hidden" name="photo[]" value="'+response+'" /></div>');
					$('#addrecipe div.uploadedphoto').append(box);
					box.find('a.remove').click(function(){ box.remove(); });
				}
			});
		}
	}
	
	// Make all textareas autogrow
	$('textarea').autogrow();
	
	// Check profile_edit page forms
	/*
	$('#profile.edit form').submit(function(){
		if ($(this).find('.realname') && !$(this).find('.realname').val()) { alert('Заполните поле Реальное Имя'); 
			$(this).find('.realname').focus();
			return false;
		}
		if ($(this).find('.password') && !$(this).find('.password').val()) { alert('Заполните поле пароль!'); 
			$(this).find('.password').focus();
			return false; 
		}
		if ($(this).find('.password') && $(this).find('.password') && $(this).find('.password').val() != $(this).find('.password2').val()) { alert('Введенные пароли не совпадают'); 
			$(this).find('.password2').val('');
			$(this).find('.password').val('').focus();
			return false; 
		}
		if ($(this).find('.email') && !$(this).find('.email').val()) { alert('Введите email'); return false; }
	});
	*/
	// accordion blya
	$('.special.accordion').each(function(){
		var parent = this;
		$(this).find('.infobox').each(function(){
			
			var box = this;
			$(this).find('.header').click(function(){
				if (!$(box).hasClass('collapsed')) { return ; }
				
				$(parent).find('.infobox').each(function(){
					var iterBox = this;
					if ($(this).hasClass('collapsed')) { return; }
					$(this).find('.infobox_container').slideUp(500, function(){ $(iterBox).addClass('collapsed'); });
				});
				
				$(box).find('.infobox_container').slideDown(500, function(){ $(box).removeClass('collapsed'); })
				
			});
		});
	});
	
	// Forms frame
	$('form').each(function(){
		var form = this;
		if ($(form).hasClass('custom')) { return; }
		
		$(form).find('input[type=submit]').removeAttr('disabled')
		
		$(form).submit(function() {
			var values = $(form).serialize();
			
			// deserialize from form)
			v = values.split('&'); values = {};
			for ( var i in v ) { var t = v[i].split('='); values[t[0]] = t[1]; }
			$(form).find('input[type=submit]').attr('disabled','disabled');
			
			customAjax( $(form).attr('action'), values, function(data){
					
					data = jQuery.parseJSON( data );
					
					if (data.error) { alert(data.error); }
					else
					{
						if (!data.url) { alert('Не указан URL!'); }
						else {window.location = data.url;}
					}
					
					$(form).find('input[type=submit]').removeAttr('disabled');
				});
			return false;
		});
		
	});
	
    $('#registration .agree').change(function(){ 
    	if ($(this).attr('checked')) { 
    		$('#registration input[type=submit]').removeAttr('disabled'); 
    	} else { 
    		$('#registration input[type=submit]').attr('disabled', 'disabled'); 
    	} 
    }).change();	
    
	// promobox slider
	$('#promobox').each(function(){
		var promobox = this;
		promobox.rel = 1;
		promobox.max = 0; // do not edit
		$(promobox).attr('rel', 1);
		promobox.onMove = false;
		
		promobox.arrowLeft = $(promobox).find('.arrow.left');
		promobox.arrowRight = $(promobox).find('.arrow.right');
		promobox.slider = $(promobox).find('.slider');
		
		promobox.animate = function(next, page)
		{	
			var oldSlide = $(promobox).find('.slide[rel='+promobox.rel+']');
			var newSlide = $(promobox).find('.slide[rel='+page+']');
			
			if (next)
			{
				oldSlide.animate({ marginLeft : -960 }, 500, function(){ $(this).css({display : 'none'}); });
				newSlide.css({display : 'block', marginLeft : 960 }).animate({ marginLeft : 0 }, 500, function(){ promobox.onMove = false; });
				if (page == promobox.max) { promobox.arrowRight.addClass('disabled'); }
			}
			else
			{
				oldSlide.animate({ marginLeft : 960 }, 500, function(){ $(this).css({display : 'none'}); });
				newSlide.css({display : 'block', marginLeft : -960 }).animate({ marginLeft : 0 }, 500, function(){ promobox.onMove = false; });
				if (page == 1) { promobox.arrowLeft.addClass('disabled'); }
			}
			
			promobox.rel = page;
			$(promobox).attr('rel', page);
		}
		
		promobox.previous = function()
		{
			if (promobox.rel == 1) { promobox.arrowLeft.addClass('disabled'); return; }
			if (promobox.onMove) { return false; }
			promobox.onMove = true;
				
			promobox.animate(false, promobox.rel - 1);
			promobox.arrowRight.removeClass('disabled');
		}
		promobox.next = function()
		{
			if (promobox.onMove) { return false; }
			if (promobox.max == promobox.rel) { return false; }
			promobox.onMove = true;
			promobox.arrowLeft.removeClass('disabled');
			promobox.animate(true, promobox.rel + 1);
		}
		
		$(promobox).find('.arrow.left').click(promobox.previous);
		$(promobox).find('.arrow.right').click(promobox.next);
		
		$(promobox).find('.slide').each(function(){
			var slide = this;
			promobox.max++;
			
			$(slide).attr('rel', promobox.max);
			if (promobox.max == 1) { $(this).show(); }
		});
		
		
	});
    
    
    
});

var DEBUG; 



